texts: Is there any way of converting an existing field to a Matrix?

texts:
I'm working on an existing site that has an "Entries" field that allows authors to provide a selection of related articles. However, since some articles have titles whose meaning is not entirely clear in this different context, the client would like to be able to tweak the wording of the titles in this "related articles" context.

The best way I can see to do this would be to make the "Related articles" field a Matrix, with each block containing both an entry and an alternative title. However, this is an existing site with lots of posts that already use this field, so I'd need to somehow convert the existing "Entries" field to a Matrix. Is this possible at all?

(I realise that an alternative approach would be to add a "Short title" field to entries. However, UX-wise this feels awkward compared to the Matrix approach, since it would require the editor to also potentially edit each of the related articles, which is both more long-winded and less clear as a process)


texts: Is it possible to have a dev version path for the Element API plugin so we can keep live and dev API separated?


texts: Nesting level too deep when looping through matrix blocks

texts:
I'm running into a nesting level error when looping through matrix blocks, and I can't quite figure out what the problem is.

The problem arises when I use a variable to track the type of the previous element in the matrix. I want to be able to know within the sub-template that an element is the nth of the same type (for adding a container around some matrix block types to group them).

If I replace line 7 below with, eg. {% set n = (element.type == 'product') ? n + 1 : 0 %} (ie. a named element type rather than a variable) it works as expected, but as soon as I compare element.type to prevElementType I get a Fatal error: Nesting level too deep - recursive dependency? error. Some of the partial templates that may be included in the loop check prevElementType, but none of them modify it, so I can't see what's causing the recursion. I'd be grateful for any help with this.

{% if entry.contentBlocks is not empty %}
  {% set prevElementType = false %}

  {% for element in entry.contentBlocks %}

  {# Let's use a counter for multiple blocks of the same type: #}
  {% set n = (element.type == prevElementType) ? n + 1 : 1 %}

  {# Include the partial for this block: #}
  {% include "_pageelements/" ~ element.type|lower %}

  {# Track this element's type for the next iteration: #}
  {% set prevElementType = element.type %}

  {% endfor %}
{% endif %}


texts: Register Assetbundle in frontend template

texts:
How can I register an assetbundle in a frontend template?
This is my bundle

namespace secondred\formbuilder\assetbundles\Formbuilder;

use Craft;
use craft\web\AssetBundle;
use craft\web\assets\cp\CpAsset;

class FormbuilderAsset extends AssetBundle
{
    // Public Methods
    // =========================================================================

    /**
     * Initializes the bundle.
     */
    public function init()
    {
        // define the path that your publishable resources live
        $this->sourcePath = "@secondred/formbuilder/assetbundles/formbuilder/dist";

        // define the dependencies
        $this->depends = [
            CpAsset::class,
        ];

        // define the relative path to CSS/JS files that should be registered with the page
        // when this asset bundle is registered
        $this->js = [
            'js/Formbuilder.js',
        ];

        $this->css = [
            'css/Formbuilder.css',
        ];

        parent::init();
    }
}

And I can register it with in my controller without any problems
$this->view->registerAssetBundle(FormbuilderAsset::class);

But when I do

{% do view.registerAssetBundle("secondred\\formbuilder\\assetbundles\\formbuilder\\FormbuilderAsset") %}

nothing happens.. no request, no error, nothing in network tab and no html is added to the page

Update
I found the solution. If you are in a frontend ressource you need to call the {{ endBody() }} method in order to get the bundles


texts: Why will my custom "Entries" field not display anything?

texts:
In my entry template I have the following...

{% set entry95 = entry.story1995 %}
{{ entry95.title }}

And this displays nothing. Debug mode is on and no errors are showing. The handle for the field is set properly. Other fields for the main entry are showing up, but nothing from this custom Entries field.

I can't figure out what I could be doing wrong here.


texts: Front End Asset Management - Upload New Photos without Deleting/Overriding Existing

texts:
I'm trying to create a front end system where users can create and manage listings with multiple photos. Everything saves as a draft until approved by an admin.

In the front end edit page, uploading multiple assets works and I'm able to display those assets to the user from their draft. However, when trying to upload additional assets, the existing ones are 'removed' and replaced by the new uploads.

I've tried just about everything I can think of and searched through a ton of documentation but haven't figured out how to make it work.

Here's what I have so far:

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="entryRevisions/saveDraft">
    <input type="hidden" name="redirect" value="...">
    <input type="hidden" name="sectionId" value="...">
    {% if drafts %}
        <input type="hidden" name="draftId" value="{{ entry.draftId }}">
    {% endif %}
    <input type="hidden" name="entryId" value="...">
    <input type="hidden" name="enabled" value="1">

...

    {% if entry.photos|length %}
    {% for photo in entry.photos %}

Here is where I think something should be happening to save existing photos...

    {% endfor %}
    <input type="file" id="photos" name="fields[photos][]" class="upload" multiple>
    {% else %}
    <input type="file" id="photos" name="fields[photos][]" class="upload" multiple>
    {% endif %}

    <input type="submit" value="Publish">
</form>

I'd also like to be able to display the existing photos and give users the option to manually remove photos they've already uploaded, but that's step 2. Need to get past this point first. Any help or links to appropriate documentation would be much appreciated. Thanks!


texts: Craft Commerce - Create Order from Control Panel

texts:
We've been looking around to get some info for this feature but didn't find anything yet and wanted to ask here in case we are missing something.

Is there a way to create an order from the Control Panel?

We are working on a project that needs to track orders not done via the website and will need the ability to create manual orders from the CP but this feature doesn't seem to exist in Craft Commerce.

Does anyone know if there is a 3rd party plugin that we might have missed that allows this functionality? Or if this is a feature that might be considered in the future scope of Craft Commerce?

Thanks heaps,
Alby


texts: Twig include with noscript tag rendered as a string and not code

texts:
So I have an include file.

I am including like standard:

{% include '_includes/partials/image-noscript' %

but for some reason it is generating the code like so…

  &lt;img
    src="http://plowmancraven-v4.loc/imager/uploads/images/general/3172/PC-Enviro-Generic-London-shutterstock_370946690_3488bcae28a5a46889970c4f238b0c7c.jpg"
    alt="PC Enviro Generic London"
  /&gt;

Edit: Here are some of the things I have tried but nothing has solved this issue yet.

{%- include '_includes/partials/image-noscript' -%}
{% autoescape false %}{% include '_includes/partials/image-noscript' %}{% endautoescape %}

inside the included file:

{% spaceless %}{% endspaceless %}

{% autoescape false %}

{% endautoescape %}

{% autoescape false %}{% endautoescape %}
{% autoescape false %}

{% endautoescape %}
{% autoescape false %}{% endautoescape %}


texts: Craft 3 Session Ended modal popping up on local machine

texts:
Using MAMP Pro 5.1
Apache, self-signed SSL cert
PHP 7.2.8 module mode

OPcache enabcled
Extensions: Xdebug, Imagick/ImageMagick

Craft 3.1.22

Basically I'm having the same problem as tons of other posts here, I keep getting the session ended popup in the cpanel frequently but refreshing the page still has me logged in.

While some posts seem to have solutions here for craft 2, I've tried to replicated them on craft 3 where I could but it's not working. I've tried:

deleting storage/runtime/*
clearing all cookies, local storage, etc
restarting apache
using MAMP PROs Memcached instance and adding this to app.php

'components' => [
            'cache' => [
                'class' => yii\caching\MemCache::class,
                'useMemcached' => true,
                'defaultDuration' => 86400,
                'servers' => [
                    [
                        'host' => '127.0.0.1',
                        'persistent' => true,
                        'port' => 11211,
                    ],
                ]
            ]
        ]

a variety of combinations of these settings in general.php

'useSecureCookies' => false
'requireMatchingUserAgentForSession' => false,
'requireUserAgentAndIpForSession' => false,
'defaultCookieDomain' => '.proposify.local',
'rememberedUserSessionDuration' => 999999,
'userSessionDuration' => 0

session.auto_start = 0 set in php.ini

When I'm in the CPanel I see this request in the network tab, which as soon as the response comes back pops up the session expired popup:

https://myLocalDevDomain.com/index.php?p=admin/actions/users/get-remaining-session-time&dontExtendSession=1

which returns this:

{"timeout":0,"csrfTokenValue":"..."}

I've currently set chrome to block this request and am not getting the popup but this is of course not a great solution.


texts: Contact Form plugin email is not being received, not clear if it is being sent

texts:
I am using the Pixel & Tonic Contact Form plugin.  I set it up using the Mijingo tutorial.  Everything appears to be working ...

I hit submit, redirects to thank you, no message received.  Setup looks good.  Hidden input fields appear good.  Error messages working when required inputs (fromEmail and message) left blank.  Redirects to thank you.  Honeypot setup looks good.   But, no message received.  And I don't know how to confirm it is really being sent.  What might I try? Thanks

I am in dev mode


texts: Only allowed 100 queries with relatedto?

texts:
Despite using null and paginate false i can still only return 100 queries with this:

{% set results = craft.entries({
    limit: null,
    paginate: false,
    section: 'directory',
    relatedTo: relationParam
}) %}

How do I get all of them?

* UPDATE *

Well I found the problem and solution which is a bit strange - makes no sense to me.
I am passing relatedTo a merged string 'relationParam' which has the mulitpple categories I want to search for. Once I set the limits on the categories that are related to the entries -see below - it all works.

{% set c = craft.categories.group('locations').slug(countrySlug).limit(null) %}
{% set p = craft.categories.group('locations').slug(portSlug).limit(null) %}

So what doesn't make sense to me is that I am having to set the limit outside of the main entries query. I would have thought the entry limit specification would do this  not on the categories related.


texts:
Is it possible to eagerLoad fields in categories?

I have this code;

{% set markets = craft.categories.group({
  section: 'markets',
  with: ['bannerImage']
}) %}

which for some reason is throwing an error;

  mb_convert_case() expects parameter 1 to be string, array given

Is this a bug or something bad in my code? Removing the with call and it renders fine.


texts: How to directly access translated variables by language

texts:
I have a localized, two language site (en and fr) that I have a translated global variable set for. My question is: is there a way on a Craft 3 template to directly access a translation of a variable that isn't the same as the currentSite language. Specifically, I'd like to show both translations of the same variable on one page.
I am getting the variable with this currently: siteOwnerInfo.siteOwner


texts: How to set up Craft to use Google Cloud Storage?

texts:
I've been clattering around the google developers console for a while, and i just can't get it to work with Craft! I figured it'd be simple (and it may well be!) considering in Craft it just asks for two bits of data, "Access Key ID" and "Secret Access Key".

After an age of digging about in the google developes console site and a bit of searching, i  ended up in the Project Dashboard for my Cloud Storage.
Enabling "Interoperable Access" gave me some new tabs on the side, one of which is "Interoperable Access", and in there FINALLY i found two strings that have the names "Access Key" and "Secret".

Putting them into Craft and hitting refresh next to Bucket gives me the error "Credentials rejected by target host".

And so now i'm stumped! Does anyone have experience using Google Cloud Storage with Craft who can point me in the right direction?


texts: Channel URL Format leads to 404s for individual entries

texts:
I've broken my news channel but I don't know how I did it, or consequently to fix it.

If one clicks on 'I just installed Craft' or 'Continue reading', it will take you to the URL I specified in the Section settings using the Craft control panel, but it results in a 404.

It didn't do this at first, then (I think this is when it broke) I changed the entry URL format from news/{postDate.year}/{postDate.month}/{slug} to just {postDate.year}/{postDate.month}/{slug}. After I got the 404s assumed I couldn't do that so I changed it back, but it's still broken.

I'm quite new to this kind of thing so I apologise if I'm wasting anyone's time. Any help would be much appreciated. Thanks.


texts:
I would like to retrieve related entries that have the same tags, not just one similar tag, but all of them.

At the moment I do something like:

{% set tags = entry.tagActualite %}
{% set relatedEntries = craft.entries.relatedTo(tags).id('not ' ~ entry.id).limit(5).find() %}

{% if relatedEntries | length %}
    {% for entry in relatedEntries %}
        do stuff
    {% endfor %}
{% endif %}

But it retrieves any entry with at least one similar tag.

How would i check against ALL tags ?


texts: Plugin Store install buttons are not visible

texts:
I'm just working on a dev site and my Plugin install buttons are gone. I'm not sure how long they've been gone either, I don't really know where to start to debug it.

No errors in the console and I have run composer update to make sure I'm all up to date, too.

Below is an image of where the 'install' button should be in the plugin store.


texts: Omitting current entry from list of entries generated from a relationship

texts:
On my template I am showing detail of an entry.
Beneath this I am showing a list of other entries that share the same kind of category relationship as the entry being viewed.

This list currently includes the entry being viewed and I wish to omit that from the list.

I'm retrieving the entries like so:

{% for category in craft.entries.section('apprenticeshipsCats').relatedTo(entry).id('not ' ~ entry.id) %}

and had expected the 'not' parameter to do what I wanted but it doesn't seem to be working. entry.id is outputting the correct ID and even if I hardcode the entry id then it still appears in the list.


texts: Display categories which only contain entries

texts:
I'm grabbing a list of categories and displaying their entry count.
How can I only display categories which have entires? So I'm not getting any with 0 in them, which is occurring as I have a few entries not yet published with new categories.

{% nav category in craft.categories.group('insights') %}
{# Get the count of entries related to `category` #}
{% set entryCount = craft.entries.relatedTo(category).total() %}

        {{ category.title }} ({{ entryCount }})

{% endnav %}


texts: Do Freeform Events Fire From Control Panel?

texts:
It appears to me that Freeform Submission events do not fire when editing events in the control panel. They certainly fire from a front-end submission.

That would make this statement in the documentation untrue. Emphasis added.

  Hook into Submission events to attach your own logic for when
  submissions are being created, edited or deleted. [1]

Can someone smarter than me confirm or deny this, please?


texts: Trouble getting an asset bundle registered

texts:
I have searched for a couple hours for help on this. No luck.

Following the docs here.

My first two passes were unsuccessful so I deleted everything and started over.

1) I created a plugin scaffolding with a single controller and successfully registered that plugin. I did not edit anything in that plugin.

2) I created the file "FooBundle.php" in the following folder structure:

recoveryfinder
--myPlugin
  --src
    --FooBundle.php

3) I edited the contents of FooBundle.php to be exactly the docs:

<?php
namespace ns\prefix;

use craft\web\AssetBundle;
use craft\web\assets\cp\CpAsset;

class MyPluginAsset extends AssetBundle
{
    public function init()
    {
        // define the path that your publishable resources live
        $this->sourcePath = '@ns/prefix/resources';

        // define the dependencies
        $this->depends = [
            CpAsset::class,
        ];

        // define the relative path to CSS/JS files that should be registered with the page
        // when this asset bundle is registered
        $this->js = [
            'script.js',
        ];

        $this->css = [
            'styles.css',
        ];

        parent::init();
    }
}

Lastly I added the following line after my {% extends "base.html" %} in my index.html. My first two lines of index.html look like this:

{% extends "base.html" %}
{% do view.registerAssetBundle("ns\\prefix\\FooBundle") %}

When I refresh my site index page I get:

  ReflectionException

  Class ns\prefix\FooBundle does not exist


texts: How to create an Asset Source programmatically via a plugin?

texts:
I've taken a look at app/services/InstallService.php for some inspiration, and I'm not great at navigating/understanding the documentation. I really don't know where to begin with this.

Could I get a little push in the right direction on how to create an Asset Source programmatically via a plugin please?

I'm hoping there's a way I can generate an asset source onBeforeInstall. I'll probably need a method to remove it too should  the plugin be uninstalled.

Thanks.


texts: Enable the user to upload background Image

texts:
How do you enable a user to upload a css background Image?

Do you write some inline css in the page header with twig markup?
Do you write some twig markup inside a css file?

Or do you fake a background image by add an image and then position it absolute?

What's the best practice there?


texts:
I have a client who needs the flexibility to add new user groups in the future to allow access to only certain sections etc.

Anyone in these user groups will appear on the website team page, so what I need to do is to exclude our admin group (and an ex employees group!)

Currently i'm chaining the groups to include as per:

{% set params = { group: 'groupB,groupC,etc,etc,etc'} %}
{% for team in craft.users(params) %}

Is there a way of telling it to just exclude groupA instead?


texts: Does Craft expose PHP errors when not in devMode?

texts:
I'm seeing a lot of tasks hanging in Craft. Specifically, DeleteStaleTemplateCaches and GeneratePendingTransforms. I've followed the advice and instructions at https://craftcms.com/support/stuck-tasks to no avail. The article suggests that there may be PHP errors in the PHP error log. However, I'm not seeing anything there at all.

After some digging, I see that during bootstrapping, Craft sets error_reporting(0) to disable PHP error reporting if the site is not in devMode. Does craft override the error handling to account for errors that could be lost due to turning off error reporting? I expect there may be some fatal errors happening within my tasks, which is causing them to hang, but they are being lost.

Any insight or documentation into how Craft handles error logging would be appreciated.

Edit:

After a little more digging, I found that error_reporting(0); does suppress certain log messages when not in devMode. This is because Craft's error handler respects the error_reporting() setting when filtering log messages. In order to reproduce, do the following:

Turn off devMode in Craft config
Set memory_limit=1k in your php.ini to force a fatal php error
Open your site in your browser and see the 500 as expected. At this point you won't see anything in /storage/runtime/logs/phperrors.log or your web server logs.
Edit craft/app/bootstrap.php and set error_reporting(E_ALL); around line 150, where you see error_reporting(0);
Hit your site again in your browser, and you will see a php fatal error in /storage/runtime/logs/phperrors.log regarding the out of memory issue.

Is this to be expected? Am I missing another configuration option which would not suppress fatal error messages?


texts: front end date field format doesn't work? fields[dateField][date]

texts:
There are a number of answers on this forum for getting a front-end form to have a DateTime field that splits date and time into separate fields; It's not working for me.

If I strip back to absolute basics - hardcoded, as a test:

<input type="hidden" id="endDate" name="fields[endDate]" value="2017-12-30 02:15:00" />

Works, and a date & time is stored in the back-end field, displaying correctly.

But, if I try to split it so the date and time fields are separate (so that I can use a date picker on one and a select drop down on the other) - it doesn't save a value into the field. Even stripped back to hard-coded hidden fields...

<input type="hidden" id="endDate" name="fields[endDate][date]" value="2017-12-30" />

<input type="hidden" id="endTime" name="fields[endDate][time]" value="02:15:00" />

What am I doing wrong? The is the same format that works in the Craft back-end...


texts:
I'm writing a plugin to create users. The problem I'm having is when I create them Craft is automatically setting the user as "active". I want them to be "inactive" so that I can then send a verification email. I've look through the code and there appears to be no way to Create a user using craft()->users->saveUser($user) without having them always be active.

In the admin panel I do have the "Verify email addresses?" option checked.

Please help!


texts: frontend form action: save as draft or publish

texts:
in my frontend entry form I have a "save as draft" submit button.
The current action for this form is the following, which saves the entry submitted through the form as a draft (status: disabled):

<input type="hidden" name="action" value="entryRevisions/saveDraft">

Next to the "save as draft" button I would like to have a "publish" button. If the user clicks on it the entry should be submitted as "status: live". If the user clicks on "save as draft" it should be submitted as "status: disabled". Any idea how to do this?


texts: Strange issue with logging out user on frontend

texts:
We have a strange issue with a site we are developing. We have a user login on the front-end of the site which takes users to their profile pages. The issue we have is that on a Mac the user is being logged out randomly and irregularly on the local server.

This is odd because on PC this issue is not occurring. And what makes it even more strange is if the user is logged in as admin, whilst the user is logged out on the front-end they are still logged into the CMS?

Has anyone come across this issue before? I've tried some of the suggestions made in this post but nothing seems to be working.

Craft constantly logging out from admin area


texts:
Channel: Restaurants

Channel: Nutrition / contains entries field named restaurant.

Required URL format:
    restaurant-name-nutrition

since the URL structure is merged I can't use getSegement(x) while getting entries.

in other scenario where the URL would be

nutrition/restaurant-name

I could use something like this

{% set seg2 = craft.request.getSegment(2)
{% for entry in craft.entries.section('nutrition').slug(seg2) %}

but what is the right approach for that one?


texts:
Every minute or so I get the "Your session has ended" popup in the admin. Entering my password just pops the message back up. If I reload the page I'm still logged in.

I'm running Craft in vagrant so maybe it's a permissions problem?

It could be related to this question since I had that exact problem but setting the permissions in vagrant fixed that particular problem.

I've tried the requireUserAgentAndIpForSession, overridePHPSessionLocation, and userSessionDuration config settings, but none of them seem to solve the popup.


texts: Is there a way to print the tax and discount percentages?

texts: Is there a way to get the tax and discount percentage when applicable?


texts:
Is is possible to get UI-elements of Craft 3.5 in the front end? Specifically wanting to get hold of the headers I use to separate fields of products.
This is my current code:
{% set layout = product.getFieldLayout() %}
{% for tab in layout.tabs %}
    {% if tab.name == "Detaljer" %}
        {% for field in tab.getFields %}
            {% if not product.getFieldValue(field.handle) is empty %}
                {% switch field.className() %}

                    {# Can I get UI header out of the tab.getFields method? #}
                    {% case "craft\\fields\\UI-header-element" %}
                        {# Do stuff #}
                    {% case "craft\\fields\\PlainText" %}

                            {{ field.name|t }}
                            {{ product.getFieldValue(field.handle )}}

                    {% case "craft\\fields\\Categories" %}

                            {{ field.name|t }}

                                {% include 'commerce/_blocks/categoryList' with { categories: product.getFieldValue(field.handle) } %}

                    {% case "craft\\fields\\Dropdown" %}

                            {{ field.name|t }}
                            {{ product.getFieldValue(field.handle).label}}

                    {% case "craft\\fields\\Lightswitch" %}

                            {{ field.name|t }}
                            {% include 'commerce/_blocks/fieldLightswitch' with { data: product.getFieldValue(field.handle) } %}

                    {% case "craft\\fields\\Number" %}

                            {{ field.name|t }}
                            {{ product.getFieldValue(field.handle) }} {{ field.suffix }}

                    {% default %}

                            {{ field.name|t }}
                            {{ field.className() }}

                        {# todo: other non implemented fields #}
                {% endswitch %}
            {% endif %}
        {% endfor %}
    {% endif %}
{% endfor %}


texts:
This is essentially my first project with Craft and my plan is to take a personal photoblog and move it into Craft to learn how everything works before working with clients and craft.

I've got craft installed locally at testing.craft.dev and want to import my existing ExpressionEngine entries.

I've renamed the default "news section" to photography, added a new image upload asset and field to the layout. All of which I can see when Igo to Entries > Photography.

Now to import the entries I found Craft Import. I've installed this, created an xml file on my EE install.

<xml>
<blog>
{exp:channel:entries channel="photoblog" show_future_entries="yes" limit="500"}
<entry>
    <entry_date>{entry_date}</entry_date>
    <title>{title}</title>
    <slug>{url_title}</slug>
    <post><![CDATA[{description}]]></post>
    <images>
    {photos}
        {image}
    {/photos}
    </images>
</entry>
{/exp:channel:entries}
</blog>
</xml>

I've also set the url to this xml file on line 17 of services/craftservice.php. Where I'm stuck is that I now need to Update Lines 64-73 to match your Craft configuration and source nodes. Reference inline comments. Those lines are:

    // Find these in craft/app/models/EntryModel
    $entry->sectionId = $sectionId;
    $entry->typeId = $typeId;
    $entry->authorId = 1; // 1 for Admin
    $entry->enabled = true;
    $entry->postDate = $importEntry->entry_date;
    $entry->slug = $importEntry->slug;
    $entry->getContent()->setAttributes(array(
        'title' => $importEntry->title,
        'post' => $post
    ));

Unfortunately I have no idea what I need to put in here. Any advice would be greatly appreciated.

As it stands if I try to load entry I get an error, no surprise there.

  CDbCommand failed to execute the SQL statement: SQLSTATE[42S02]: Base
  table or view not found: 1146 Table 'crafttest.craft_entries_i18n'
  doesn't exist


texts:
Im trying to get a front end login form to work over ajax and running into issues, it seems to always pass back success and not sure how to actual make sure the cookie gets created and the user is logged in?

here is the gist of what i have right now:
https://gist.github.com/keithmancuso/29e8446ec5fa66fb2b01


texts:
For some reason editing images isn't working for me. Specifically saving/replacing. Nothing happens.

The two errors I get in the console are;

POST http://dev.test/index.php?p=admin/actions/assets/save-image 500 (Internal Server Error)

Uncaught TypeError: Cannot read property 'error' of null
    at s.constructor.<anonymous> (Craft.js:5952)
    at Object.error (Craft.js:361)
    at c (jquery.js:3317)
    at Object.fireWith [as rejectWith] (jquery.js:3447)
    at l (jquery.js:9274)
    at XMLHttpRequest.<anonymous> (jquery.js:9514)


texts:
I'm newish to Craft CMS.

Im building a plugin for a client, one of their forms needs to post inputted data to an api then return a result to a hidden text area before the email if fired off.

I have built the form and plugin with event, only problem is this event fires with every form i have on the site now. is it possible to target a form handle in the event ?

Currently using

craft()->on('amForms_submissions.onBeforeSendEmail', function (Event $event) {
    $params = $event->params();
}

Thanks in advance


texts: Make fields required when using Guest Entries

texts:
This might be a bit of a Noob question but here I go:

Using Guest Entries on a site and cannot figure out how to make certain fields required. Those fields are marked as required in the CP but, when using Guest Entries, entries are submitted even when required fields are not filled in.

I can easily implement a front-end validation but I would like the validation to happen on the back-end before saving the entry as well.

Should this happen automatically, am I missing something ?
Do I have to create a validation "manually" and if so, how ?

EDIT:

After updating the plugin, this is how I displayed validation errors:

{% if entry.errors is defined %}
    {% for errorField, error in entry.errors %}
        {% for errorMessage in error %}

{{ errorField }} - {{ errorMessage }}

        {% endfor %}
    {% endfor %}
{% endif %}


texts:
I have just started to build my first plugin with Craft CMS.

Im at the part where I want to defne my database table.

http://buildwithcraft.com/docs/plugins/database

For the method definedAttributes() what values will the array accept.

It looks like I can define values and types, but how do i add field lengths, primarykeys etc..

Are there some other docs that I can look at?

Thanks for your help.


texts:
I've made a new plugin for Craft 3 using https://pluginfactory.io/, including everything possible just in case I needed it. Now that my project is coming to a close I'm going back through to take out what I didn't end up needing (I now realize this was not the wisest way). I can't seem to take out the Settings and Control Panel sections, even though my composer.json has:

...
"extra": {
  "hasCpSettings": false,
  "hasCpSection": false,
}
...

I'm not redeclaring those as true anywhere else...is there something else I should do to remove those parts?


texts: Update a lightswitch field in Craft CMS 2

texts:
How can I edit a lightswitch field in an entries field layout via PHP? This is my current approach

public function actionSponsoredEntriesPriority() {
    $this->requireAdmin();
    $this->requireAjaxRequest();
    $success = false;
    $message = Craft::t('Any message from controller');

    $newPriority = craft()->request->getPost('newPriority');
    $entryId = craft()->request->getPost('entryId');

    $entries = craft()->entries;

    $entry = $entries->getEntryById($entryId);

    if ($entry != null) {
        $entry->getContent()->setAttributes(array(
            'lightswitchFieldHandle' => 1
        ));

        $success = $entries->saveEntry($entry);
        $success == true;
    } else {
        //return null;
        $success = false;
    }
}

But since there are other required fields that are currently empty for this entry I receive the following response

  message: {featureImage: ["Feature Image cannot be blank."], hero: ["Header cannot be blank."]}

I tried to resave the required fields still stuck at matrix field.
Here is code Reset required field

  Error : Correct the errors listed above.

Do i need to update the required field as well or there is a way to bypass while updating a field ?

  Update : Solution as suggested in answer [Update field directly ]

public function actionSponsoredEntriesPriority() {
        // $this->requireAdmin();
        // $this->requireAjaxRequest();
        $newPriority = craft()->request->getPost('newPriority');
        $entryId = craft()->request->getPost('entryId');
        $success = false;
        $message = Craft::t('Any message from controller');

        // entries object
        $entries = craft()->entries;
        // entries  by id ( $entryId passed by js )
        $entry = $entries->getEntryById($entryId);

        if ($entry != null) {
                $command = craft()->db->createCommand();
                $success = $command->update(
                    'content', // table name
                    array(
                    'field_lightswitchFieldHandle' => 1,
                    'field_sponsoredEntriesPriority' => $newPriority
                    ), // fields
                    'elementId=:id',
                    array(':id'=> $entryId)
                    );
                $message = Craft::t('Priority saved');
                $success == true;
            } else {
            //return null;
            $success = false;
        }
        // send response true/false with message
       if($success == true){
           $this->returnJson(
            array(
                'success' => $success,
                'message' => $message
            ));
       }else{
           $this->returnJson(
            array(
                'success' => $success,
                'message' => $entry->getErrors()
            ));
       }
    }


texts: Form tabs aren't saving in the Sprout Forms plugin

texts:
Strange bug: I'm creating tabs in a new form, but they're not saving. Goes like this:

Create a new tab
Re-name tab
Save form (to add / create a field)
Newly created tab is gone

Same thing happens whether it's my form or one of the default example ones ("basic" and "contact"). The "basic" form has two tabs; I checked the db to see if the tab data (names, number, etc.) is saved anywhere there but I can't see any table that contains it.

So maybe it's stored in a file somewhere? Which means maybe some kind of permissions issue? Much obliged for any guidance.


texts:
So I'm setting up a system with 3 tiers of users.

Admin
Officers
Managers

I want Officers to be able to administer managers. Any of you know if this is doable?

So let's say an Officer could login (not in the CP) and view a list of its managers and change let's say, their password...

Any light on this would be great :)


texts: Is there a name for Craft 3's database model?

texts:
I find Craft 3 to have a very clever database structure which eschews all of the issues I've seen with EAV.
Despite contrasting the differences between Craft 3's model and EAV, I'm having difficulty generating buy-in from the rest of my team who dismisses it as EAV. After so many times around the block, I wonder if it would help to point to a named database structure. I'm not looking for a comparison against EAV, rather a definition to provide my team.
Looked quite a bit and can't seem to pin down a name for Craft 3's database structure, is there one? If so, what?
Anecdote: one particularly snarky team member has taken to calling it "The Junk Drawer" after the content table. I sort of love it!


texts:
I am building a new website using Craft CMS and I have a requirement from the design team that they want to be able to re-use templates across multiple sections. For example define how a product looks like and then be able to add a product from any sections.

I thought implementing this using a Matrix or having a channel/structure section with multiple entry types however I am bit unclear when to use entry types and when to use matrix or maybe there is better way to implement this and I am not aware?


texts: Custom Routes with URL Parameters and Pagination

texts:
I am migrating an old EE site to Craft. The EE site has a filter feature for certain weblogs. It outputs a list of entries for a weblog filtering on year, program, etc... which are passed as URL parameters.

I'd like to continue doing the same on the Craft site. I've setup custom routes to handle the url parameters. The following for example:

With {% paginate %} using something that looks like this (a bit simplified):

{% paginate craft.entries.section('videos').limit(10).order(fSort).date(fYear).relatedTo(fCategory).relatedTo(fProgram) as pageInfo, pageEntries %}

  {{...various pagination links using pageInfo...}}

  {% for entry in pageEntries %}

{{ entry.title }}

  {% endfor %}

The initial page of entries and pagination links outputs fine. But when going to subsequent pages via a pagination link (e.g., adding "p2" at the end of the URL), it can't find the route.

Does native pagination not work with custom routes? I tried different tokens for the pagination segment, but nothing seems to work.


texts: Error 404 When trying to POST to plugin Controller action

texts:
Before I dive into my problem, I do want to mention that I did do my due diligence and spent the last two days researching this problem, to no avail, so here it goes:

So I'm getting the following error when trying to load an action method from the controller: Unable to resolve the request "ecaApi/main/doGeocodeRequest". I get this error if I try and navigate directly to it, e.g. domain.com/actions/ecaApi/main/doGeocodeRequest

The AJAX request below also generates a 404.

File Structure:

- craft/plugins
  - ecaapi
    - controllers
      --EcaApi_MainController.php
    --EcaApiPlugin.php

EcaApi_MainController.php

 namespace Craft;

    class EcaApi_MainController extends BaseController
    {
        protected $allowAnonymous = true;

        public function actionDoGeocodeRequest() {
            //.....
            $this->returnJson($result);
        }
    }

JS ajax call to the action method

    var data = {
        address: "{{ event.event_location }}"
    };
    data[csrfTokenName] = csrfTokenValue;
    data['action'] = 'ecaApi/main/doGeocodeRequest';
    $.ajax({
        method: "POST",
        url: "/",
        data: data
    })
        .done(function (data) {
            console.log(data);
            markers[{{ event.id }}] = new google.maps.Marker({
                position: new google.maps.LatLng(data.results[0].geometry.location.lat, data.results[0].geometry.location.lng),
                map: map,
                {% if mapSettings.mapIcon %}
                icon: mapMarkerIcon,
                {% endif %}
                title: "{{ event.title }}"
            });
            var content = '{{ event.title }}';
            var window = new google.maps.InfoWindow({
                content: content
            });
            markers[{{ event.id }}].addListener('click', function () {
                window.open(map, markers[{{ event.id }}]);
            });

        });

Any help would be appreciated, I've been pulling out my hair for days over this.


texts: Craft Commerce Currency - Email template not showing currency

texts:
Is there something else you have to add to Craft Commerce Email templates to show the amounts in the order currency used? It always shows the default currency (i.e. GBP) when it was ordered in USD.

The email template has been updated to the new tag of commerceCurrency.

Thanks for any help.


texts: Can entries be disabled by default for 2/3 of the languages on my website

texts:
I have a 3 language website that I made for a client.
The website is in Dutch, Japanese and English.

When my clients creates a new entry, most of the time they want to have the Japanese and English version disabled and only show the Dutch version. After they have created the entry they have to manually disable the Japanese and English version.

Is it possible to have the Japanese and English version disabled by default?

Thanks!


texts: How can I sync slugs within sites in the same Group?

texts:
I have a Craft site with approx. 13 Sites. They are grouped by language, e.g. German has Germany and Austria in it. Spanish has Spain and Mexico in it.

I imported all content to the main groups sites as the other fields are all set to be translatable per group. So importing Spain means Mexico will have the same content.

But the slugs are not synced. The slugs still use the original English slugs from when I cerated the sites.

How can I get the slugs to sync. within the group? So Mexico slugs will take Spanish slugs?

Thanks


texts:
I'm just getting started with Craft. My problem is that I'd like the user to be able to change the location of call to action buttons on the site. Instead of allowing them to enter any URL, it would be bit nicer to let them select the related entry.

I can use the entries type, but it won't allow me to select channels. How should I proceed? Create a single section that displays the channel entries so that I can link to it?


texts:
I'm currently trying to call variables called {{entry.title}}, {{entry.latitude}} and so on in an array.

This is what it looks like:

{% set markerArray = [] %}
{% for entry in craft.entries.section('xSpots') %}
    {% set tempMarkerArray = [
    {'name':'{{entry.title}}','url':'{{entry.Url}}','lat':'{{entry.latitude}}','lng':'{{entry.longitude}}'}
    ] %}
    {% set markerArray = markerArray|merge(tempMarkerArray) %}
{% endfor %}

When calling {{markerArray[0].name}} afterwards I am expecting it to return the proper title of the entry in Craft, instead it only returns "{{entry.title}}", as if the variable is not properly recognized while filling the array.

Any help? Am I doing something fundamentally wrong?
Thanks in advance.


texts: How to query entries written in a specific locale? (Craft 3)

texts:
In Craft 2 you used to be able to do something like {% set entries = craft.entries.section('something').locale('de') %} but .locale() has been removed and there's nothing similar in the docs that I see.

I'm aware that the locale automatically gets included based on the url, and I'm aware that "Locales" have been replaced by "Sites", but I want to force a query of entries from a specific locale on the one and only site I have regardless of what's in the URL. How can this be done?


texts:
How can I remove /index from my homepage of Craft CMS?

https://pritirathod.com/index


texts:
I've got the GraphQL code posted below, but I'm not sure how do I count the total of returned products .
Do I need another query just for the products without offset ? I need it for a pagination functionality
query Products($offset: Int, $priceBetween: [QueryArgument]) {
  products(limit: 9999, orderBy: "dateCreated DESC", offset: $offset, defaultPrice: $priceBetween) {
    id
    defaultPrice
    title
    ... on furniture_Product {
      productThumbnail {
        url @transform(width: 300, immediately: true)
      }
    }
  }
}


texts:
When I'm using devmode to dump out a twig variable the site will no longer work saying that entry = NULL.

This only happens when I have some twig logic at the top of my template e.g.

    {% set metaDescription = entry.metaDescription %}
    {% set metaPageTitle = entry.metaPageTitle %}

do I need to move this logic elsewhere in order for devMode to work?


texts: element-api: include a collection with mixed entry types, and nested includes

texts:
Does anyone know how to include a collection of entries, containing multiple entry-type, in such way that:
 1. Each entry type gets transformed by its own custom transformer class (tailord to the entry type's data structure).
 2. Nested include names get passed along  and processed by the custom entry transformers, in order to load their own supported resources.

To try and give a basic example, I am trying to setup an endpoint for a landing page entry, which includes a mixed set of featured entries, which each in turn include some extra data.

The goal is to have an endpoint such as api/pages/my-landing-page.json?include=featured,featured.topic,featured.event return data similar to:

[
  "id" => 12,
  "type" => "landingPage",
  "postDate" => "2019-05-08T12h30",
   ...
  "featured" => [
     // loaded in `LandingPageTransformer::includeFeatured(): CollectionResource`
     "data" => [

      [
        "id" => 123,
        "type" => "article",
          ...
        "topic" => [
          // loaded in `ArticleTransformer::includeTopic(): ItemResource`
          "id" => 234,
          "title" => "Content API",
          "relatedArticles" => [ 3, 5, 10 ],
        ]
      ],

      ...

      [
        "id" => 567,
        "type" => "newsItem",
         ...
        "event" => [
           // loaded in `NewsItemTransformer::includeEvent(): ItemResource`
          "id" => 789,
          "title" => "Introduction to GraphQL",
          "startDate" => "2019-05-22T18h30",
          "endDate" => "2019-05-22T20h00",
          "location" => "London"
        ]
     ]
  ]
]

As far as I know, I need to pass in a single transformer class when creating a new collection resource in LandingPage::includeFeatured(). How do I tell element-api / fractal to use a different transformer for featured article entries than for featured newsItem entries?

I tried to use a "man in the middle" transformer, which would then delegate by picking/instanciating a custom transformer for each entry, but then how do I pass the include names, and how do I make sure nested includes still work?

This seems to be more related to Fractal than to Craft, but if some-one who knows his way around the Craft Element API plugin implementation can help, that'd be great! Many thanks :)


texts: Sprout Forms - Notification Based on Checkbox Value

texts:
I'm using Sprout Forms 3.8.0.2 and Craft CMS 3.4.5. My client wants the email notification to go to different email addresses based on whether or not a form checkbox is checked. My plan is to create a new notification for each checkbox value, with the checkbox logic in a custom rule. I've read through the documentation, but I can't figure out how to write the code that checks whether a checkbox is checked. I think it's something like
{ checkBoxFieldHandle == 'value' } or { checkBoxFieldHandle.valueBeingChecked.selected } but neither of those are sending any notifications after a test message. Any advice on how to do this? Thank you!


texts:
I'm trying to calculate some image sizes for Imager.

This works:

{% set imageSizes = [{ height: imageHeight * 4}, { height: imageHeight * 3}, { height: imageHeight * 2}, { height: imageHeight}] %}

But how do i get halfs?

imageHeight * 2.5, imageHeight * 0.5 or imageHeight / 2 does not work.

Edit:
It was my own fault.
I checked the array and only saw width's. I set the images sizes in the CP and to:

{% if imageHeight is not empty %}
  {% set imageSizes = [{ height: imageHeight * 4}... %}
{% else %}
  {% set imageSizes = [{ width: imageWidth * 4}... %}
{% endif %}

I only wrote the half calculation in "if imageHeight" for testing. But the entry i use for testing has only width's...


texts: Display entries if Field Date is past Now

texts:
I'm trying to make a upcoming and past event page. I can make an if statement for displaying the past or upcoming events but the problem is if I limit the amount of entries to be displayed I realised it is still going through the other entries (obviously) so it wont display anything. So I was looking for any filter of some kind to only display entries based on field value greater then other value.

Something in the range of:

{% for entry in craft.entries.section('event').limit(2).search('eventDate < now') %}
<!-- Past events go here -->
{% endfor %}


texts: Why I can't upload a favicon.ico as an Asset?

texts:
I'm unable to upload the favicon.ico thought Craft because it says:

Upload failed for favicon.ico. The error message was: ”Error uploading the file: This file type is not allowed“

Why does that restriction exists? I just couldn't find a list of forbidden files.
Can I change that restriction?

I know I can use a FTP client to put the file in the folder, but since I'm doing this site for a friend I just wanted to leave her an easy way of managing the icon.


texts: Re- Arrange the Address-Country select field

texts:
I try to increase the usability of my shipping address input form.
The country list is pretty impractical. I'd like to have the most used countries on top.
Dropdown List:
Switzerland
Germany
UK
USA
--- < add a disabled select field as separator
Afghanistan
Albania
… etc etc

Anybody happen to have a script which reorders this behemoth?


texts: Need to populate new field based on existing data

texts:
Say I have a section called "Stores" that has an existing field called "Store Hours". The client has populated the store hours for 1000 some stores. Now, however, it seems what the client really wants is the ability to quickly see which stores are open on Sunday. So now I need to add a new field called "Open Sunday" and correctly filly its value for each store based on its existing hours.
What I've tried:
I've added a new field, and then wrote SQL to update the contents table to fill out the value of "Open Sunday" based on the "Store Hours", however, I need to manually re-save entries in order for my frontend queries to see the new "Open Sunday" value. Editing contents directly doesnt seem to let Craft know that the new field has a new value (possibly its saved in revisions or versions?).
*This example is just that, an example. I do not need twig snippets in how I can derive what stores are open on Sunday from a story hours field.


texts:
I created a plugin settings page following the example shown here but my entries need to include multilines (they are email bodies). My Twig template for the settings page is like this:

{% import "_includes/forms" as forms %}

{{ forms.textField({
    label: "Submitted Subject"|t,
    id: 'submittedSubject',
    name: 'submittedSubject',
    instructions: "Input your setting"|t,
    value: settings.submittedSubject,
    errors: settings.getErrors('submittedSubject'),
    })
}}

(this field is repeated 6 times).
I tried using textAreas instead of textFields, but it doesn't have the same options and I don't think it works (doesn't have a value field). Also it doesn't help that there's barely any documentation for this. Is there a way for me to have multiline text inside the text field?


texts: ElementAPI: How to order and/or limit results?

texts:
Currently collaborating on a site with another developer, which is using ElementAPI pretty heavily for content delivery.

Is there a way to limit the number of returns on any given json feed? Say; only return the 10 most recent entries in any given channel? Or order the returned data by a specified field asc/desc?

A sample code:

'trucks.json' => [
  'elementType' => 'Entry',
  'criteria' => ['section' => 'trucks'],
  'paginate' => false,
  'transformer' => function(EntryModel $entry) {
    return [
      (int)$entry->id,
      $entry->manufacturer,


texts:
Has anyone found a replacement for:

deniedTags: ['p'],
paragraphize: false

I can't find a way to strip the pesky <p> tag anymore, on Redactor II.


texts:
Is it possible to somehow notify the user from a completing task?
I am walking trough a set of .csv files and on completion i would like to notify the user.

// last step
$stepIndex = $step + 1;
if ( $stepIndex == $this->getTotalSteps() )
{
    craft()->userSession->getFlash('notice', 'Reroutes  imported.');
    // craft()->userSession->setNotice(Craft::t('Reroutes   imported.'));
    // craft()->userSession->getFlashes();
}

return true;

I tried with the UserSessionService but i guess that won't work because the task is running separately from the session. If so reloading the page would be a good alternative but how can I let the front-end know of the task being completed.


texts: Sprout Forms Payload Forwarding empty value

texts:
I have a couple of forms that require payload forwarding. The only problem I'm having is that all the content that should be sent through is empty. I can see the form being submitted to the payload lead and is received but it wont share any information.

Now I'm wondering is this from my end or the leads?


texts: 500 Internal Server Error after moving index.php

texts:
Installed using composer. No issues. Installed in /craft directory. Used the command line setup with what seemed like no issues. Moved my files from /craft/web to /public_html. When I try to get the site I get a 500 error. I CAN get http://domain.com/phpinfo.php. What could be the issue?

Edit
I changed file permission of index.php to 644 and now get a different page with the same error. The first page is the standard cpanel 500 error with formatting. The second error page is a less formatted 500 page:

  This page isn’t working
  67.227.155.172 is currently unable to handle this request. HTTP ERROR 500


texts:
Is there an easy way for Importing/Exporting Fields?

I'm just working on a selection of Global fields that I'd like to be able to add for each client site. These would be things like Contact Details, Social Links, etc.

EDIT: I created FieldManager for this!


texts:
I’d like to use Craft as a headless CMS for my mobile app (via the Element API plugin). However, in addition to reading data, I’d also like to write data back to Craft.

It looks like this is typically done using an Entry Form on the front-end. Is writing to Craft possible without using Craft’s front-end though (e.g. native inputs in the app that send data via the API instead of a web view with an entry form)? If not, could this be accomplished by forking the Element API and adding that functionality somehow?


texts: How to automatically set time in a date/time field?

texts: For a specific kind of entry I need the time in a date/time field to either automatically display as 23:00/11pm on the user dashboard, or, permanently set the time on that date/time field to 23:00/11pm.


texts: Struggling to get Entry index number so I can output "X of Total Entries"

texts:
I have a channel which has multiple entries in, I'm trying to output the current entry number, for example "1 out of 20 posts"

Currently this is what I am working with:

{% set total = craft.entries().section('spotlights').count() %}
{% set params = {section: 'spotlights', order: 'postDate desc', limit: null} %}
{% set entry_prev = entry.getPrev(params) %}
{% set entry_next = entry.getNext(params) %}

      {% if entry_prev %}

        Previous

      {% else %}

        Previous

      {% endif %}

ENTRY NUMBER HERE of {{ total }}

      {% if entry_next %}

        Next

      {% else %}

        Next

      {% endif %}

I have my next and previous links working as well as the total entries in the section, I just can't work out how to get the current entry in the section. Any help would be appreciated.

I have tried a few different solutions on here but they all seem to be outdated.

Thanks.


texts:
I'm getting started with the Google Maps plugin. I have experience with the EE version but not understanding some of the Craft version. I'm trying to output a set of markers from entries. Currently nothing outputs at all.

I imported all the addresses and then added a GoogleMap field to the entries. When I check the entries it all looks correct.

I have:

{% set options = {
    id: 'map',
    width: '950px',
    height: '500px',
} %}

{{ craft.googleMaps.map(options) }}
{% for entry in craft.entries.section('maps').limit(10) %}

    {{ craft.googleMaps.data('map', entry.mapData) }}

{% endfor %}

I also tried this for the markers:

{% for entry in craft.entries.section('maps').limit(100).find() %}
    <!-- {{ entry.title }} -->
    {% set marker = {
        address: '{{ entry.mapData }}',
        content: '{{ entry.title }}',
        clustering: true
    } %}
    {{ craft.googleMaps.marker('map', marker) }}

{% endfor %}


texts: Uploading PDFs with Imagick extension enabled seems to rasterize and compress the PDFs

texts:
Uploading PDFs to Craft3 with Imagick extension enabled seems to rasterize and compress the PDFs.

Also, if I manually swap out the files after upload, it works fine until I have to edit something in an article with a pdf uploaded. Then the behavior is repeated when I press save.

Any idea on where to disable this behavior?


texts: Craft queue not being processed, listen not running

texts:
I built a site on a dev server and the Craft queue worked in that with no extra setup needed. In fact I installed Async Queue Manager because Crafts way was too slow. They both worked fine.

I moved the site to its live server, and the queue is not running. It runs if I manually enter ./craft queue/listen on the command line. When I stop that process it wont process the queue anymore.

Does anyone know why it would not work on this other server? Do I need to do anything special to make it work? I suppose I could run ./craft queue/listen and leave it, but I would need to set it to run on boot. I never did this on the old server.

Thanks


texts: Dropdown that shows all months and when selected displays all entries from that month

texts:
This snippet displays every post by postDate, which lists a bunch of “October 2015”. I am trying to filter by month/year, so only one “October 2015” shows then one “November 2015”, then one “December 2015” so on and so forth. So choosing the month, shows all posts from that month.

by date

    <select name="blog-date" id="blog-date" onchange="window.location.href=this.value;">
        <option value="/blog">All Time</option>
        {% cache %}
        {% nav entry in craft.entries({ group: 'blog', order: 'postDate desc', limit: null }) %}
            <option value="{{ entry.postDate | date('F-Y') }}"
                {% if craft.request.getLastSegment() == entry.postDate %}selected{% endif %}>
                {{ entry.postDate | title | date('F Y') }}
            </option>
        {% endnav %}
        {% endcache %}
    </select>


texts:
I'm trying to use a charting library within a Craft template.

The chart expects an array of numbers that I'm building up from a table but I'm getting an array of strings instead.

{% set donutData = [] %}
{% for p in block.donutValues %}
    {% set donutData = donutData|merge([
        p.value
    ]) %}
{% endfor %}

and then if I do {{ donutData|json_encode }} I get an array of strings returned that my chart library can't interpret.

value is set to be a number field in the Craft table column so not sure why I'm getting a string returned.


texts: How do I cycle a class on a Matrix block?

texts:
I am trying to add a class which will cycle through on every iteration of a matrix block type, here is my code:

{% for block in entry.asideNavigation %}

    {% switch block.type %}

        {% case 'textBlock' %}
            <li class="aside__nav__item {{ cycle(['cs-a','cs-b'], loop.index0) }}">
                ...
            </li>

        {% case 'imageBlock' %}
            ...

    {% endswitch %}

{% endfor %}

This cycle function gives me the error "Variable "loop" does not exist" where am I going wrong?


texts: I'm trying to grab a specific image to display that is located in assets. I tried using {% set image = craft.assets.filename('image_filename.jpg') %} but I get the error "An unknown image object was used." I also tried referring to one of the asset sources which I saw as a solution in another post related to my question: {% set image = craft.assets.source('my_images') %} but I'm not sure how that would help me grab a specific image. {% set image = craft.assets.images[0] %} just grabs an image from any of the asset sources if I change the index number. What am I doing wrong here?? Thanks in advance!


texts: Sprout Import: Place entries under a parent in structure section?

texts: When using the Sprout Import plugin, how do you place an imported entry underneath a specific parent entry in a structure section?


texts:
I create a section clientSection which I linked an matrix field like in this image:

The field has two block types : clientImage which has an field clientImage and clientDescription which has an field with same name.
I want to output in twig file but I don't know how exactly

{% set clients = craft.entries.section('clientSection').all() %}

{% for client in clients %}
  {# display content here #}
{% endfor %}

Thank's


texts: Using embedded assets plugin to display youtube or vimeo embed urls on a template

texts:
I'm trying to use the "Embedded Assets" Craft plug-in to embed Youtube and Vimeo videos in a matrix field, but I can't figure it out. I've read through the instructions on the Github page but I can't make sense of it.

I have successfully installed the plug-in, and it seems to be "grabbing" the videos correctly since I can see the video in the assets section and the json files are in the folder on my disk.

I put this twig code from the instructions of the plugin provider in my template:

{% for asset in assets %}
    {% set embed = craft.embeddedAssets.fromAsset(asset) %}
    {% if embed %}
        {{ embed.safeHtml|raw }}
    {% endif %}
{% endfor %}

but it breaks my page.

This is the error message I get, saying the variable "assets" does not exist:

52         <div class="video">
53                 {% for videoEmbed in videoEmbed %}
54                     {% set embed = craft.embeddedAssets.entry.    (videoEmbed) %}
55                     {% if embed %}
56                     {{ embed.safeHtml|raw }}
57                     {% endif %}
58                 {% endfor %}
59                 {% endif %}
60
61         </div>
62
63
64         {% endfor %}

I work locally and have dev mode turned on.

I am trying to use the plugin inside a matrix field with "videoEmbed" as block and field handle.

I created an asset source/ folder called "videos".

And I am on the personal licence.


texts: Get entries which have content like '%findme%'

texts:
I am creating a more robust find and replace plugin which shows what is being replaced and where. I need to query for all entries(or content records?) where content is like '%findme%'.

Should I query for entries or should I query for content records for this find and replace?

I saw that there is an EntryRecord, so I can give it CDBCriteria object to find but there is no ContentRecord so how do I get the content with the string in it?

This is all I have so far.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->limit = $model->limit;
$relaventContent = ContentService::model()->findAll($criteria);


texts: Display a new entry modal when clicking on a relation field

texts:
For a complex website we have nested a relation field inside a matrix.

It makes little sense for us to show the list of already created entries so we would prefer to directly display the new entry modal when clicking on a relation field. Our goal is to facilitate the editors lives and thus avoid multiple modal nesting... (See below).

Thank you in advance for your advice. Peace.


texts:
In the documentation "search form" example you can run a GET request to a specific template and if you use a Plugin you can run a POST request to a specific controller action.

But is it possible to run a POST request directly to a template?


texts: Mail: There was an error testing your email settings

texts: I'm trying to use mailgun to send emails. I'm on my local machine and I get the error: "There was an error testing your email settings." The API key matches up correctly and nothing of significance seems to be showing up in my logs. Can someone suggest another way of debugging this? The error message isn't too helpful on it's own. Thanks.


texts:
I'm doing a big import of users from an EE install using the Import plugin. I can pull in all the details I need except the join date, so I looked at the craft db to see where it needs to be changed.

I successfully managed to change it by updating the craft_elements table, dateCreated column. This changed the join date in the control panel, however it does update the dateCreated column in the craft_users table so I updated there also.

Just wondering if thats correct?


texts: Unable to add data via migration to a new field

texts:
When I am creating a new field (and I've tried plain text, redactor, supertable and matrix field) and associating it with an existing entry type (using the Control Panel to do so), I run into an issue where I can't load data to the field  with a migration.

Here's code from the migration I might try to run to put some data in this field (in this case, it is a redactor).

  foreach ($attorneys as $attorney) { // iterate over json data we are going to import.
    $craft_attorney_id = // lookup attorney id
    $entry = Entry::find()->id($craft_attorney_id)->status(['enabled','disabled'])->one();
    if (!$entry) {
      continue;
    }
    $accolades = 'test text';
    $entry->setFieldValues(array('accolades' => $accolades));
    if(!\Craft::$app->elements->saveElement($entry)) {
        throw new \Exception("Couldn't save entry: " . print_r($entry->getErrors(), true));
    }
  }

When I view one entry in the CP and enter data in the new field, and then rerun the migration (take it down then up), the new data from the migration is saved just fine (for that element. but not for any others).

I've set the redactor field to 'full html', and also stripped the tags from the field to be inserted.

Our content table has 56 columns, but many are text, so I don't think I'm running into an issue with row length ( https://dev.mysql.com/doc/refman/5.6/en/innodb-restrictions.html#innodb-maximums-minimums )

Tried clearing all the caches.

Tried upgrading from 3.0.9 to 3.0.27.

Also tried to refresh fields on the fields service:       \Craft::$app->fields->refreshFields(); at the beginning of the migraiton.

If I try to read from the entry in the same migration, I get this exception

Invalid field handle: accolades (/.../vendor/craftcms/cms/src/base/Element.php:1932)
#0 /../vendor/craftcms/cms/src/base/Element.php(1612): craft\base\Element->normalizeFieldValue('accolades')
#1 /../migrations/m181016_224151_import_accolades_v2.php(59): craft\base\Element->getFieldValue('accolades')
#2 /../vendor/craftcms/cms/src/db/Migration.php(56): craft\contentmigrations\m181016_224151_import_accolades_v2->safeUp()

Except I can find that field using the fieldService. Maybe it is something to do with the normalization?

Am I saving the entry incorrectly? Do I need to do some kind of special call to refresh the element mapping of fields?

Thanks!


texts:
I have one tag for each entry.

 - Entry1
     Tag1
 - Entry2
     Tag2

Now I want to show them in the title of each entry. But it doesn't work.

{% for entry in craft.entries.section('mainEntry').limit(4) %}
{% set tag = entry.mainEntryTag.first() %}
  <h2>{{ tag }} {{ entry.title }}</h2>
{% endfor %}

This results in displaying only the globally first tag:

- Entry1
     Tag1
- Entry2
     Tag1

If I just write: {% set tag = entry.projektart %} I get the error: Object of class Craft\ElementCriteriaModel could not be converted to string

How can I get to current entry tag?


texts: How do I set up Craft to send emails from my local MAMP/Virtual Host X dev environment

texts:
I'm developing a site locally using MAMP + VirtualHostX on Mavericks. I'm at the point in the project where I want to create some user accounts for clients, but I can't seem to get my mail set up properly so Craft can send emails from my local environment.

Has anyone done this same thing? Any advice for getting Craft emails working on a similar local dev environment?

Thanks!


texts:
A similar bug with this plugin has be brought up before.

The issue that I'm having is that the post handle mailchimpSubscribe/list/Subscribe doesn't seems to be working correctly. I'm wondering if this is due to any recent changes to Craft CMS? It has worked in the past but it doesn't seem to want to work now.

<form class="newsletter-form" action="#subscribe" method="POST">
<input type="hidden" name="action" value="mailchimpSubscribe/list/Subscribe">

{% if mailchimpSubscribe is defined %}
  {% if (not mailchimpSubscribe.success) and (mailchimpSubscribe.errorCode!='1000') %}

An error occured. Please try again.

  {% endif %}
{% endif %}

<input type="text" name="email" value="{% if (mailchimpSubscribe is defined) and (not mailchimpSubscribe.success) %}{{ mailchimpSubscribe.values.email }}{% endif %}"/>

After submitting the form I get

Unable to resolve the request "mailchimpSubscribe/list/Subscribe".

I thought maybe it was to do with an incorrect character that should be uppercase/lowercase but i've tried a few different combinations.

Has anyone come across the same issue recently?


texts:
I would like to create a route for the entry types of a specific section, pointing to a single template.

Is it possible to do this automatically? So far I haven't had luck, I'm thinking something like this:

route = /{ mysection.type }
template = type/index.twig

Or would I need to create a route for each entry type and all of them pointing to same template?

route 1 = /entryType1
route 2 = /entryType2
route 3 = /entryType3
shared template = type/index.twig

The reason I would like to do it this way, as opposed to how it has been shown before, here; is because I would like to keep all the URL's with a date format, i.e.: example.com/2014/07/11/slug so that I can then implement an archive template. But I still need a way to filter by entry types (a total of 12 types). So that at the end of the day I end up with URLs like these ones:

example.com/2014/01/01/example-entry - URL for Example Entry
example.com/2014/01/01/ - URL for listing entries from day
example.com/2014/01/ - URL for listing entries from month
example.com/2014/ - URL for listing entries from year
example.com/video/ - URL for Video types of entry
example.com/audio/ - URL for Audio types of entry

Any suggestions on how to solve this?


texts: Math with numeric values derived from a dropdown field

texts:
I had a dropdown field with a handle of hLevel, with only numeric values in it, anticipating that I could do math with the values in my template. But it seems I can't.

{% set dif = subhead.hLevel - subhead.next.hLevel %}

…returns an error message ending in:

  “could not be converted to int”

I found a thread convinced that number_format “converts a string to a number”, so I tried that:

{% set dif = subhead.hLevel|number_format - subhead.next.hLevel|number_format %}

…but that doesn't work either. The error message changes to:

  “could not be converted to double”

Which doesn't surprise me as I did think that number_format is for float to formatted string conversion, not the other way round as well.  ¯\_(ツ)_/¯

When I change the field format to number everything works fine, but…

It would be good if there is an option to have dropdown field values be parsed as numbers, because from a UX perspective I would prefer that the field is a dropdown.

Or is there some workaround I've missed?


texts:
I am currently trying to make it so when I have logged in on my website as a user it redirects to a certain page.

However it is not working.

I have tried adding the following redirect in the configuration file however no luck:

'postLoginRedirect' => 'profile/test'

Any tips or suggestions will be appreciated.


texts: Show entries by a certain category AND certain lightswitch

texts:
Just thinking of an easy way for the user to manage products on a site.

Therefore is it possible to display entries by a category and a lightswitch toggle?

IE. Category selected is Photocopiers and Lightswitch is color?

Then check for those and display the entries? Stuck on the syntax:

{% set category = craft.categories.slug('copier') %}
{% set colortype = craft.entries().section('products').color(true).all() %}
{% set entries = craft.entries.section('products').relatedTo(category).find()

*Stuck on the syntax here to add to the query the lightswitch field*

 %}

    {# If there are any entries, loop through them #}
    {% if entries | length %}

        {# For each entry we find, do this #}
        {% for entry in entries %}
            <p>{{ entry.title }}</p>
        {% endfor %}

{% endif %}

TIA :)


texts:
Reposted from Slack

I have tried to create a migration using console (as per docs) but whilst it created a migrations folder it did not create a migration file. So resorted to creating manually but now getting the following error:

Status: Internal Server Error
Response:
Craft\Exception

Could not validate update handle.

The offending migration file can be viewed at https://gist.github.com/cole007/4bfff23c693ca496ca4929f464df2a05

Looking into the Update Controller that is throwing the error it seems to be down to the _getFixedHandle() method where $data['handle'] is returning empty but no idea why this is.

Any thoughts on debugging or resolving? Site launch is imminent so need to get to the bottom of why this is happening soon!

Thanks,

Cole


texts: Only display the first tier of categories

texts:
I'm looking to only display the top level parent categories on my Template, but unfortunately, everything I try seems to error out and still display all of the children categories as well.

My current code looks like the following:

  {% set categories = craft.categories.group('discounts') %}
        {% for category in categories.all() %}


texts: Is it possible to list all searches with at least one result that were made on a site?

texts:
I want to submit a XML sitemap to Google with frontend searches, in order to boost the SEO for a site.

This is the approach I would take. But then, I might be very naive and there's other techniques for boosting the SEO with predefined searches?!


texts: Default stock levels when importing Commerce products with FeedMe

texts:
I've got a Commerce 3 store where the customer maintains the majority of the product listings by updating a Google Sheet, very few fields are edited via the Control Panel.

However, now they are starting to do pretty simple inventory control for some products we are running into issues.

Right now I set the inventory to unlimited via the Google Sheet for all products, and that works fine, until you want to import a product with inventory control.

The issue is, if you enable inventory control for a product in the sheet, then import it, the import will fail ever time unless you supply a value for Stock on hand.

We don't want to be setting stock on had via the sheet however, so we are a bit stuck.

The question here really, is there any way to import a value from the sheet only if a value doesn't already exist in the entry for stock on hand?

Here's an example of where this breaks down:

Import a new product with Unlimited set to 0, the import will fail because Stock is a required field.

If I include stock in the spreadsheet I'll get bad data as it will overwrite the stock levels with each subsequent import.

I've played around with default field values on this with the intent of setting a value of 0 if there was no preexisting value, however, this will overwrite any value already in Commerce.

Ideal world we would run the import, any new items would have Stock set to 0, which would then be updated manually after the import, but subsequent runs would leave stock levels alone.

My idea is to enable parseTwig and create a simple conditional to set this value if it's null, but I can't find much in the way of documentation on this feature to connect all the dots.

Last resort being a plugin.

Any ideas?


texts: Sprig "Load more" not loading over https

texts:
I've recently added an SSL to the site I'm working on, and it seems to have broken my "load more" buttons via sprig. When I click the button now, I get

Blocked loading mixed active content “http://mydomainname.net/index.php?p=actions/sprig/components/render&offset=6&sprig%3AsiteId=32200a47f3a91660d5c53896017cd9e51baccf7f69c571407279fa99ecbcffb91&sprig%3Atemplate=0fb8ec651fc53258017209d22d4e19b6143ac209993784d01a06801fd13e9cd6_layouts%2F_blog%2F_loadMore&sprig%3Avariables%5Blimit%5D=15a1fe68dab9e8d01fdd3bc84980fa5d354e5c72f0e00d06e0841462638f363d6”

and

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mydomainname.net/index.php?p=actions/sprig/components/render&offset=6&sprig%3AsiteId=32200a47f3a91660d5c53896017cd9e51baccf7f69c571407279fa99ecbcffb91&sprig%3Atemplate=0fb8ec651fc53258017209d22d4e19b6143ac209993784d01a06801fd13e9cd6_layouts%2F_blog%2F_loadMore&sprig%3Avariables%5Blimit%5D=15a1fe68dab9e8d01fdd3bc84980fa5d354e5c72f0e00d06e0841462638f363d6. (Reason: CORS request did not succeed).

errors in my console. I've noticed that the cross origin error is trying to load stuff over https but the mixed active content error is trying to load over http.
How can I get this working again over https?
Here's my sprig code if you need it:
{{ sprig('_layouts/_blog/_loadMore', {'limit': 6}) }}
{{ sprig.script }}

{% set offset = offset ?? 0 %}

{% set entryQuery = craft.entries.section('diggingDeeper').offset(offset).limit(limit) %}
{% set entries = entryQuery.all() %}

{% for entry in entries %}

    ----Entry Stuff----

{% endfor %}

{% if entryQuery.count() > offset + entries|length %}
  <button class="orange-button" sprig s-val:offset="{{ offset + limit }}"
    s-target="this" s-swap="outerHTML">

Load More

  </button>
{% endif %}

Edit:
Added the full errors
Edit 2:
Here is my .htaccess file that forces https and removes www
<IfModule mod_rewrite.c>
    RewriteEngine On

# send would-be 404 requests to craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

# Force https
RewriteCond %{HTTP_HOST} mydomainname\.net [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://mydomainname.net/$1 [R,L]

# Remove the www from the URL
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

</IfModule>

Edit 3:
After resolving the "Blocked loading mixed active content" error these are the current errors in the console when the load more button is clicked

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mydomainname.net/index.php?p=actions/sprig/components/render&offset=6&sprig%3AsiteId=32200a47f3a91660d5c53896017cd9e51baccf7f69c571407279fa99ecbcffb91&sprig%3Atemplate=0fb8ec651fc53258017209d22d4e19b6143ac209993784d01a06801fd13e9cd6_layouts%2F_blog%2F_loadMore&sprig%3Avariables%5Blimit%5D=15a1fe68dab9e8d01fdd3bc84980fa5d354e5c72f0e00d06e0841462638f363d6. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

htmx:afterRequest htmx-1.2.1.js:1368:25

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mydomainname.net/index.php?p=actions/sprig/components/render&offset=6&sprig%3AsiteId=32200a47f3a91660d5c53896017cd9e51baccf7f69c571407279fa99ecbcffb91&sprig%3Atemplate=0fb8ec651fc53258017209d22d4e19b6143ac209993784d01a06801fd13e9cd6_layouts%2F_blog%2F_loadMore&sprig%3Avariables%5Blimit%5D=15a1fe68dab9e8d01fdd3bc84980fa5d354e5c72f0e00d06e0841462638f363d6. (Reason: CORS request did not succeed).

htmx:sendError htmx-1.2.1.js:1368:25


texts:
I recently started learning plugin development for Craft CMS. I'm creating a plugin that deals with video content. For this example I'll use two models: MyPlugin_ChannelModel and MyPlugin_VideoModel. I've also setup two record classes that mirror the model's properties (MyPlugin_ChannelRecord and MyPlugin_VideoRecord).

The two record classes have a many to many relationship with each other. So, a channel can have multiple videos and a video can be in multiple channels.

I can create, delete and modify records. So far, so good. Now, this next part confuses me. I want to use these records in my templates. Ideally, I'd like to do something like:

{% for video in channel.videos %}
    {{ video.someProperty }}
{% endfor %}

However, I think the "rule" is that only services can interact with records. Models should be used in all other parts of a plugin to pass data (like passing data from a service to a template).

Since models do not have the relationship properties, I've written some getter methods on those models to help me get to my channels/videos from the opposite end of the relationship. An example for MyPlugin_ChannelModel:

public function getVideos()
{
    if ($this->_videos === null && $this->id !== null)
    {
        // Helper method that gets the record for this model
        $channelRecord = craft()->myPlugin_helpers->findRecordForModel($this);

        // Convert each related record back to a model
        $videoModels = array();
        foreach ($channelRecord->videos as $videoRecord) {
            $videoModel = new MyPlugin_VideoModel($videoRecord);
            $videoModels[] = $videoModel;
        }

        $this->_videos = $videoModels;
    }

    return $this->_videos;
}

It's nice that these getter methods automatically map to their corresponding property names ($model->getVideos() becomes model.videos in Twig), but this means I have to write each of these helper methods by hand on all my model classes to get the related models. Am I missing something, is there an easier way?


texts: Craft 2: Suspend user results in "Unauthorized You don’t have the proper credentials to access this page."

texts:
This pertains to a Craft v2.9.2 installation.
User X is an admin user. So she has permission for pretty much everything, except accessing site settings, etc.
For an unknown reason, User X is unable to suspend other users.
User X has all permissions assignable under General and Users on the Permissions tab.
Yet when she tries to suspend another user, Craft returns the following error:
Unauthorized
You don’t have the proper credentials to access this page.

I have no idea why. Is there something I am over-looking regarding what's required for a user to suspect another user?
Is there a way to find out what is causing this issue? Such as a log of such issues?
Thank you.


texts: Alternatives to Mamp Pro – which works with Craft CMS

texts: I've been a long time user of Mamp Pro, but I'm getting an error using v3 with Craft3, due to needing to update to Mamp Pro 4, however after some hrs trying to update to Mamp 4, I can't get mySQL to start and therefore wondered what alternatives to Mamp other devs use – which isn't overly complex?


texts: Array expecting string error when fieldtype is used within matrix

texts:
Im getting an expecting string given array error on a variable in my fieldtype. When output / dumped to the template it is a string. This only happens when used within matrix field.

The trim function here is the specific line throwing the error:

$settings['colours'] = explode(',', str_replace(' ', '', trim($settings['colours'])));

getInputHtml() & prepValue()

public function prepValue($value)
{
    $colour = new FruitStyle_PaletteModel();

    if(is_array($value))
    {
        $colour->hex = $value['hex'];
        $colour->opacity = $value['opacity'];
    }

    return $colour;
}

public function getInputHtml($name, $value)
{
    craft()->templates->includeJsResource('fruitstyle/js/FruitPalette.js');
    craft()->templates->includeCssResource('fruitstyle/css/palette.css');
    craft()->templates->includeCssResource('fruitstyle/fonts/fruiticons/style.css');

    $id = craft()->templates->formatInputId($name);
    craft()->templates->includeJs('new FruitPalette("'.craft()->templates->namespaceInputId($id).'");');

    // String or JSON
    $settings = $this->getSettings();
    if(filter_var($settings['colours'], FILTER_VALIDATE_URL))
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $settings['colours']);
        $colours = curl_exec($ch);
        curl_close($ch);
        $settings['colours'] = JsonHelper::decode($colours, true);
    }
    else
    {
        $settings['colours'] = explode(',', str_replace(' ', '', trim($settings['colours'])));
    }

    return craft()->templates->render('fruitstyle/_fieldtype/palette/input', array(
        'id' => $id,
        'name' => $name,
        'value' => $value,
        'settings' => $settings,
        'specialOptions' => $this->_getSpecialOptions(),
    ));
}


texts: Is it possible to import orders into Craft Commerce?

texts:
We have to migrate a CSV dump from a Drupal commerce shop to Craft Commerce.

It is important to import ‘Order Email’ / ‘Username’, ‘Order Date’, ‘Ordered Items’ (Name or ID), ‘Item Price’.
Address etc. are not relevant. An Order Reference could be generated automatically from us.

If these are not enough fields for a Craft Commerce order: Which mandatory fields does an order require in Commerce?

Anyone know if there is a way to do this? We would of course love to do it with the FeedMe plugin, but that does not seem to be applicable to Craft Commerce orders.


texts: How can I output the value of a superTable field within a loop?

texts:
I have a superTable field that I am trying to re-populate on my front-end form.

Everything is working great, I am able to populate a drop-down, but can't seem to find the magic numbers to re-populate a textfield.

<label>{{ field.name }}</label>
<input type="text" name="fields[myField][fields][{{ field.handle }}]" class="form-control" value="{{ entry.myField[0].??? }}">

This works well:

fields[myField][fields][{{ field.handle }}]

But, whatever I enter after that . Example:

value="{{ entry.myField[0].field.handle }}"

I get the error that the model "field doesn't exist". If could make field.handle just be "myField" everything would be great. I can hard-code the field name and it works great. But, I need to be able to access the values within a loop.

Thank you for any suggestions!

EDIT

value="{{ entry.myField[0].field.handle }}"

Is a plainTex field. This is the output I am trying to accomplish.

<input type="text" name="fields[myField][fields][{{ field.handle }}]" value="{{ entry.myField[0].field.handle }}">


texts: How do I use an if/else statement to determine if a field is filled in?

texts:
I know how to add images into my template:

{% set image = entry.featureImage.first() %}

But what if my client doesn't have feature images for all of his entries? I need some function that'll tell the website, if there is no image, omit
.

Perhaps some kind of if/else statement that I can use:

{% if
    //the featureimage for this entry is filled in
%}
    {% set image = entry.featureImage.first() %}

{% endif %}


texts:
it is possible to do like this:

$users = Entry::find()
  ->userLevel('>3')
  ->or group('admin')

So in database level,the sql will go like this:

select * from users
  where users.userLevel > 3 or users.group='admin'

Many many thanks!!


texts:
Is there a mechanism for grouping related fields in an entry besides:

a) putting them in a tab - which I generally reserve to group fields at a higher order (e.g content/data/meta)
b) putting related fields inside a matrix block with a limit of 1, which feels like I'm adding a level of complexity to my content model.

I have various modules in a page, so i've taken to labelling them with a common prefix for each module (as in 'Homepage Hero - Background Image', 'Homepage Hero - Subheading'), but all of the fields visually gel together in the UI in a somewhat indistinguishable list.

I suppose changing my use of tabs would serve my purpose, but could look quite unruly on an entry with many elements.


texts: Error after downgrading from Pro to Personal

texts:
We developed a website under the trail Pro license. But now on the production server, we downgraded Craft to Personal. Since then we can't save entries and get a warning about it.

The logfile gives the next errors:

2016-12-07 15:23:53

Level   error
Category    exception.Craft\HttpException.404
Message Craft\HttpException in /removed-path-for-sec/craft/app/controllers/TemplatesController.php:59
2016-12-07 15:23:47

Level   error
Category    application
Message CDbConnection failed to open the DB connection: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

Upgrading to Pro solves the problem again. Could do that of course, but I'm wondering if there is an other solution :)


texts: How to get the order number of the current entry in a structure

texts:
Is there a way in Craft to get the order property of the current entry when it's in a structure? For example say you have the following structure:

Parent Page

Child One
Child Two
Child Three

Is there a way to get what order property Child Two is in relation to its siblings so in this case it would be 1 (zero based)?

In my templates I am wanting to be able to grab the order property for the current entry by doing something like {{ entry.getOrder() }}.


texts: Display something in the middle of post content

texts:
My entry content is displayed like this:
{% for block in entry.postContent.all() %}

        {% if block.type == 'text' %}
      {{ block.text }}
    {% elseif block.type == 'image' %}
      {% for image in block.image.all() %}

      {% endfor %}
    {% endif %}

{% endfor %}

I want to display some other things in the middle of this content but have no idea how I can do it. Maybe someone have any thoughts?


texts: Create web report able to be exported in pdf

texts:
I'm new in the Craft CMS world, and I'm approaching it because I need to create a web app where I and my colleague can create reports based on what we do for customers and export them in PDF format.

Can I accomplish this task with Craft?

In positive case can anyone give me some hints about what to do to begin (example.. plugins to study etc..)

Thanks so much.


texts: Embedder offers up some cool functionality, but I don't see where it explains how to set video parameters. It says you can, but not seeing how. Anyone successfully done this?


texts: Get and Set existing matrix field data in a plugin

texts:
I have a plugin that wants to set a value for an entries existing matrix field, from a form on the font-end. Think of it like:

Movies (matrix field)
  Movie (matrix block)
    Name (plain text)
    votes (plain text)
  Movie (matrix block)
    Name (plain text)
    votes (plain text)

I want to increment the number of votes when a user clicks a button for a particular movie.

I've tried all sorts of methods, but being pretty novice at php I just can't seem to grasp how Craft is storing everything. I just keep getting back an array of ALL fields on the site, rather than the specific ones I'm searching for.

All existing SE questions seem to relate to adding new rows, I just want to edit an existing one.

Normal fields are (from existing code) along the lines of

$currentVotes = $movie->getFieldValue('votes');
$movie->setFieldValue('votes', $currentVotes + 1);

Which seems rather simple. What is the Matrix version of that?


texts:
I have a single that has 5 banner images. I would like to load a different image each time the page loads. I want to do this with twig not JS, is this possible if so could somone point me in the right direction.

Thanks in advance


texts: Another 'Could not find your craft/ folder' on fresh install

texts:
Even though I repeatedly downloaded the current Craft release, created a new host with a new root folder and a new database, installing Craft runs into the error Could not find your craft/ folder etc ... when I try launch whateverdomain.dev/admin.

Followed the instructions step by step each and every time, applied the right permissions to each folder (and its contents).

None of the earlier posts come up with a fix to this issue. Could this be a MAMP issue?

– Richard


texts:
I have a site that deals exclusively with user generated content.

After a few years, the users table is getting to a stage where it can probably be pruned of folk who have registered but not actually submitted any content.

What query would I run to show the users who have zero posts?

I thought something like select id from craft_users where id not in (select distinct authorId from craft_entries) would do it.

The distinct query certainly returns 1020 rows where we actually have around 1800 users.


texts: How do you password protect a site in progress?

texts:
Im wondering if there is a simple way to password protect  site thats in development using just Craft Personal?

I setup a login page and i got {% requirelogin %} to redirect but it seems with craft personal even the admin cant login via a front end login form?

Do they have to login at /admin and then jump to the front end of the site?

is there an easier way?


texts: Returning ElementCriteriaModel of entries via plugin

texts:
I'm outputting an element criteria model in a Craft 2 plugin of some entries in a channel.  I noticed that when I fetch the entries the standard template way

{% set entries = craft.entries.section('channelHandle') %}

I am then able to do something like the following to refine the number of entries with the lightswitch turned on:

{% set refinedEntries = entries.customLightswitchField(1)|length %}

However, when I fetch my entries in my plugin, output them into the template, then try refining it as above:

// plugin
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'channelHandle';
$entries = $criteria->find();
return $entries;

// template
{% set entries = craft.myPlugin.fetch() %}
{% set refinedEntries = entries.customLightswitchField(1)|length %}

...I then get an Array to string conversion PHP notice.  I'm also not able to use things like .first() like I normally would.

Is this expected behavior?  Am I missing something when returning an element criteria model through a plugin?


texts: Craft 3: with Base URL of site set up using @web alias, how to display the original URL in Twig templates?

texts:
I use the @web alias in the configuration of the base URLs of the sites (following Craft 3 documentation). The @web alias allows a shortcut  to the URL of the folder that contains the index.php file loaded for the request.

However, when I loop through craft.app.sites.getAllSites using Twig, the value of baseUrl still prints @web in the URL, instead of transform it in its original URL.

As a workaround, I could get the original URL using {{ craft.app.sites.currentSite.baseUrl ~ site.uri | replace({ '@web': '' }) }}. But this seems a very dirty solution that will probably not always work.


texts: Feedme plugin - importing users into craft commerce

texts:
I have few questions about importing users into Craft CMS using feedme. These users would be also Craft Commerce customers.

Users will be imported without passwords. Would this provide some kind of security risk, for example, someone being able to log in with empty password?
Setting new passwords for users - would I need to write custom module to send password reset form to each imported user? Would not sending 5000 emails at once choke Craft - maybe I should use tasks for that?
Addresses - do i need to write some custom plugin for importing adddress data along with basic user data like email? I didnt saw any fields for setting up user address when i tested importing users using feedme. Did someone managed to tackle this issue in the past?


texts: Contact Form Plugin P&T redirect issue with locales

texts:
I'm using the standard P&T contact form plugin. I have a website with 3 locales in a folder structure where every locale has its own folder:

Public

-- EN

-- FR

-- NL

The contact form has the following code:

<form method="post" action="" accept-charset="UTF-8" data-abide>
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="contactForm/sendMessage">
        <input type="hidden" name="redirect" value="thanks?from={fromName}">

        // Rest of code: fields, etc.

</form>

The redirect template is called thanks and it works as it should except that the thanks page is always redirecting to the EN locale.
When I manualy navigate my browser to go to the thank you page in another locale it works too. But after submitting the form, it just does not redirect to the current locale.

Update

Removing ?from{fromName} does not resolve the issue

siteUrl is set in the config file:

'*' => array(
'siteUrl' => array(
                'nl' => 'http://cmgg.buthost.com/nl/',
                'fr' => 'http://cmgg.buthost.com/fr/',
                'en' => 'http://cmgg.buthost.com/en/'
            )
)

Sidenote: the whole website is almost final and everything with the locales is working as it should except the contact form redirect.