texts: Charge object not available on first page load

texts:
I have a custom donation form that I'm using that includes some custom Craft fields. Two of those fields are dropdowns which I populated with options from within my Craft admin panel.

Since this is a custom form, it must use Stripe.js, so I have the following lines in my template per the tutorial on the SquareBit site:

{% includeJsResource('charge/js/stripe_v2.min.js') %}
{% includeJsResource('charge/js/jquery.charge.js') %}
{% includejs %}
    $(this).charge();
{% endincludejs %}

Here are my Payment options that are set inside the <form> declaration:

{% set chargePaymentOptions = { 'allowDynamic' : true, 'planCurrency': 'usd', } %}

{{ craft.charge.setPaymentOptions(chargePaymentOptions) }}

I borrowed some code from the Charge plugin examples for initializing the select fields like so:

{{ forms.selectField({
     label: 'Donation Recurrence',
     name: 'donationRecurrence',
     id: 'donationRecurrence',
     options: (charge is defined ? charge.donationRecurrence.options),
     value: (charge is defined ? charge.donationRecurrence),
     errors: (charge is defined ? charge.getErrors('donationRecurrence'))
}) }}

{{ forms.selectField({
     label: 'Would you like to donate to a specific cause?',
     name: 'donationDesignation',
     id: 'donationDesignation',
     options: (charge is defined ? charge.donationDesignation.options),
     value: (charge is defined ? charge.donationDesignation),
     errors: (charge is defined ? charge.getErrors('donationDesignation'))
}) }}

As you can see, the select fields get their options from the aforementioned pre-populated custom Craft fields. Those options do not show up on first page load, but if the form is subsequently submitted and comes back with errors, then the select field options appear.

I figured out that on the first page load, doing a dump(charge) shows that the charge object does not exist until the page has been reloaded after the form was submitted.

Thanks for any help.


texts: Is it possible to modify the input format for dates in front end form?

texts: From other threads and my own tests a date field needs to be input in the format of 10/15/2012 (mm/dd/yyyy). But that's not very "British", is there any way to modify it?


texts:
On my home page template I include a couple of extracts from single entries and I'm not sure which is the best/most efficient way to call them.

{% for entry in craft.entries.section('information').slug('about') %}

{{ entry.title }}

    {{ entry.summary }}
{% endfor %}

or

{% set entry = craft.entries.id(13).first() %}

{{ entry.title }}

{{ entry.summary }}

They both generate the same amount of queries in the Chrome dev tools profile summary report, but I don't understand why, as the second looks like it's more specific and not a loop.


texts: Add or extend attributes (table column) to fields table

texts:
I'm trying to find a way to extend the meta fields inside a custom field definition. To illustrate:

I need a min_vis def_vis and max_vis column for each field (or anytime a new one is added). Preferably these would be right under the name, handle, instructions text fields. So in this illustration below, there would be a select box added for each of these 3 new meta (or columns) after the instructions meta field.

I know it probably isn't a good idea to modify the core stuff, including the fields table, so should I use a plugin to define some a new model and record? Should I extend the form for fields registration to add these additional attributes as select boxes? Should I give the new attributes their own table (via record class) and set BELONGS_TO where they are related to each field?

If there is a better way to approach this, or if I'm pushing to hard for something custom no worries just give me a heads up that I shouldn't be extending the core fields attributes.

I did look at this issue but wasn't sure if it actually pertained to my question?


texts:
I'm building a site that contains a listing of products and distributors. I have a channel for each, and each entry in the distributors channel contains a relationship field to tie it to any number of entries in the products channel. There are about 20 entries in each channel.

I need to set up a page with a table that includes all of the products across the top, and all of the distributors in the left column, with a check box in each cell where there is a relationship between the two.

I know how to just use standard related entries tags to output the distributors and list out the related products for each, but is there a way get it into the table format, without a ridiculous number of queries?


texts:
I wanted to listen to the onSetStatus event of the SetStatusElementAction and used the same code like in the EntryElementType class:

$setStatusAction = craft()->elements->getAction('SetStatus');
$setStatusAction->onSetStatus = function(Event $event) {
  MyPlugin::log('maybe');
}

But it didn't work and I had to hack into the core making following code changes:

in the ElementsService class:

/**
 * Fires an 'onSetStatus' event.
 *
 * @param Event $event
 *
 * @return null
 */
public function onSetStatus(Event $event)
{
    $this->raiseEvent('onSetStatus', $event);
}

in the EntryElementType::getAvailableActions method where the onSetStatus is called:

craft()->elements->onSetStatus($event);

This way I'm able to listen to the event in my plugin:

craft()->on('elements.setStatus', function() { ... });

The problem is that with the next update I have to do the code changes again. Is there a better way to listen to the event or is this worth a push request?


texts:
I'm new to craft development, and I'm on the verge of success in the creation of my plugin, but I have a strange problem.

It's supposed to save a record based on user input data. The problem is that it works on my computer, but not on my mobile phone (-> result in 404).

Here is the form

<form class="ui form" method="POST">

        Activité
             <select name="activity" class="ui fluid dropdown">
                 <option value="3">Third</option>
                 <option value="2">Second</option>
                 <option value="1">First</option>
             </select>

             Nom et prénom
             <input name="nom" type="text">

         <input type="hidden" name="action" value="eventEquipe/event/addParticipant">
         <button class="positive ui fluid button" type="submit">Je viens !</button>
</form>

Here is my controller's code
public function actionAddParticipant() {

$this->requirePostRequest();

    $participant        = new EventEquipe_ParticipantRecord();
    $request            = craft()->request;

    $participant->nom       = $request->getPost('nom');
    $participant->activity  = $request->getPost('activity');

    craft()->eventEquipe_event->saveParticipant($participant);
    $this->redirect('/agenda');
}

The problem is that sometimes, this redirects me to /login (I dont know why, I have no /login route) and thus result in a 404.

Thanks for your help !


texts: Perform inclusive relatedTo query with multiple categories in Craft 2.5+

texts:
I'm trying to to display entries related to "all" the given categories instead of "any" using the updated relatedTo method provided in Craft 2.5.

In a related question, @BrandonKelly explains how to do this in the "Updated" portion of his answer. However, I still seem to be getting "any" behavior instead of entries matching "all" categories.

Here is an example URL if only one category in the Social Services group is selected

http://website.com/technologies/someSocialService

Here is an example URL if additional technology categories are also added:

http://website.com/technologies/someSocialService?type[]=88&type[]=117

So, ideally, I want to first filter the entries by the social service category, determined by segment 2 in the URL.

Then, I want to filter even further if there are types of technology in the URL.

Here is my code:

{% set slug = craft.request.getSegment(2) %}
{% set socialServiceCategory = craft.categories.group('socialServices').slug(slug).first() %}
{% set socialServiceCategoryId = socialServiceCategory.id %}

{% set technologyCategoryIds = [] %}
{% if craft.request.getParam('type') %}
{% set technologyCategoryIds = technologyCategoryIds|merge(craft.request.getParam('type')) %}
{% endif %}

{% set categoryIds = [socialServiceCategoryId]|merge(technologyCategoryIds) %}

{% set entries = craft.entries({
    section: 'solutions',
    relatedTo: {
        targetElement: ['and']|merge(categoryIds)
    }
}).order('listingType desc', 'title asc') %}

When the page loads with only the segment slug, and no query string, I get entries filtered by that category. However, once I add one or more technology IDs to the categoryIds array, I get all entries matching "any" categories in the categoryIds array.

Given a URL such as the 2nd example I displayed above, here is a dump of my categoryIds output:

array(3) { [0]=> string(2) "15" [1]=> string(2) "88" [2]=> string(3) "117" }

...which contains exactly the right categories I'd like to inclusively relate my entries to.

For the time being, I was able to get this working the way I need with pre-Craft 2.5 beta syntax for relatedTo using the following code:

{% set entries = entries.relatedTo(socialServiceCategoryId).order('listingType desc', 'title asc') %}

{% if technologyCategoryIds|length %}
{% set entries = entries.relatedTo(
    'and',
    { targetElement: socialServiceCategoryId },
    { targetElement: technologyCategoryIds|join(',') }
).order('listingType desc', 'title asc') %}
{% endif %}


texts:
I have auto-updating currently disabled using the "allowAutoUpdates" config setting, due to concerns about plugin compatibility and unforeseen breakages, mainly due to experiences with other CMS's.

However, I'm starting to feel that having that button available for clients to update automatically is very tempting, especially as the number of Craft installations to keep up to date increases.

How safe is this mechanic to enable? For example, if a client was to auto-update and there was a breakage, and the database was not able to roll back to a previous version? Surely you can't guarantee that the internal API won't change in the future, and if it ever does, how can the auto-update feature prevent plugin breakages?

And if I was to enable it, would this just be a case of adding the app folder to my .gitignore and not including it in my git repo?


texts:
I'm dumping this var but cant nail down this error:

{% set submissions = craft.tumblr.submissions %}

    {% for key,submits in submissions %}
        // KEY GIVES ERROR 1

{{ dump(submits.key)  }}

        // BLOG_NAME GIVES ERROR 2

{{ dump(submits.blog_name)  }}

    {% endfor %}

Error 1:

  Key "key" for array with keys "blog_name, id, post_url, slug, type, date, timestamp, state, format, reblog_key, short_url, summary, recommended_source, recommended_color, followed, is_anonymous, anonymous_name, anonymous_email, is_submission, liked, note_count, title, url, link_author, excerpt, publisher, can_send_in_message, can_reply" does not exist

Error 2:

  Method "blog_name" for object "Twig_Markup" does not exist

Thoughts?

EDIT: Adding scheme for craft.tumblr.submissions:

array(7) {
  [1]=>
  array(28) {
    ["blog_name"]=>
    array(1) {
      [0]=>
      string(11) ""
    }
    ["id"]=>
    array(1) {
      [0]=>
      int()
    }
    ["post_url"]=>
    array(1) {
      [0]=>
      string(64) ""
    }
    ["slug"]=>
    array(1) {
      [0]=>
      string(23) ""
    }
    ["type"]=>
    array(1) {
      [0]=>
      string(4) ""
    }
    ["date"]=>
    array(1) {
      [0]=>
      string(23) ""
    }
    ["timestamp"]=>
    array(1) {
      [0]=>
      int()
    }
    ["state"]=>
    array(1) {
      [0]=>
      string(10) ""
    }
    ["format"]=>
    array(1) {
      [0]=>
      string(4) ""
    }
    ["reblog_key"]=>
    array(1) {
      [0]=>
      string(8) ""
    }
    ["short_url"]=>
    array(1) {
      [0]=>
      string(30) ""
    }
    ["summary"]=>
    array(1) {
      [0]=>
      string(23) ""
    }
    ["recommended_source"]=>
    array(1) {
      [0]=>
      string(11) ""
    }
    ["recommended_color"]=>
    array(1) {
      [0]=>
      string(11) ""
    }
    ["followed"]=>
    array(1) {
      [0]=>
      bool(false)
    }
    ["is_anonymous"]=>
    array(1) {
      [0]=>
      bool(true)
    }
    ["anonymous_name"]=>
    array(1) {
      [0]=>
      string(13) ""
    }
    ["anonymous_email"]=>
    array(1) {
      [0]=>
      string(30) ""
    }
    ["is_submission"]=>
    array(1) {
      [0]=>
      bool(true)
    }
    ["liked"]=>
    array(1) {
      [0]=>
      bool(false)
    }
    ["note_count"]=>
    array(1) {
      [0]=>
      int(0)
    }
    ["title"]=>
    array(1) {
      [0]=>
      string(23) ""
    }
    ["url"]=>
    array(1) {
      [0]=>
      string(54) ""
    }
    ["link_author"]=>
    array(1) {
      [0]=>
      string(11) ""
    }
    ["excerpt"]=>
    array(1) {
      [0]=>
      string(11) ""
    }
    ["publisher"]=>
    array(1) {
      [0]=>
      string(11) ""
    }
    ["can_send_in_message"]=>
    array(1) {
      [0]=>
      bool(false)
    }
    ["can_reply"]=>
    array(1) {
      [0]=>
      bool(true)
    }
  }
  [2]=>


texts: I'm trying to create a new entry from within the database. The section is defined in craft_sections, and the entries for craft_elements, and craft_entries seem correct after the script is run, but no entries are displayed in the UI.


texts: Can Craft be used with conjunction with other framework (Laravel)?

texts: Can Craft be used with conjunction with other framework (Laravel) or its a standalone solution?


texts:
My search form is returning all of the sites pages, regardless of the search term used.

Even if I search for a load of random letters (dfbdsufbsf) all pages are returned.

This is my search form code.  I've tried changing the button to and  but no joy

      <form class='form form--search' role='search' action="{{ url('search/results') }}">
        <fieldset>

            Search
            <input class='form__input form__input--search' placeholder="Search" name='q' id="q" tabindex='1' type='search'>
            <button class='form--search__button' type="submit"></button>

        </fieldset>
      </form>

And here is my search results page (search/results.html) (markup removed)

{#
 # Search template
 # ---------------
#}

{% extends "_layout" %}
{% block content %}
  {% set query = craft.request.getParam('q') %}
  {% set entries = craft.entries.search(query).order('score') %}

Search Results

    {% if entries|length %}

{{ entries|length }} results:

    {% else %}

Your search for “{{ query }}” didn’t return any results.

    {% endif %}

    {% if entries|length %}
        {% for entry in entries %}
            {{ entry.title }}
        {% endfor %}
    {% endif %}

{% endblock %}

Any ideas why this is happening.  I'm using the latest version of Craft.  This is happening locally and on production.


texts: What is the correct way to include jQuery and jQuery UI in Craft?

texts:
I am wondering what is the correct way to include jQuery and jQuery UI in Craft?

Thank you.


texts: What are the different scenarios to plan for when using $allowAnonymous in a controller?

texts:
Craft 3.2 updates how the allowAnonymous behavior works. I have things working in our plugins but I don't understand the different syntaxes needed across our different allowAnonymous use cases.

For example, Sprout Forms fails to submit unless we update the action to use the new self::ALLOW_ANONYMOUS_LIVE setting. However, Sprout SEO XML Sitemaps work fine without any updates. When I look through Craft I see some methods using the conventions (install controller, preview controller) and others not using any new conventions (generate thumb, live preview controller)

In one case, the Sprout Address Field controller, the prefix action- seems to matter now and removing it alone, gets things updated and working again:

// Failure while logged out
protected $allowAnonymous = [
    'action-update-address-form-html'
];

// Success while logged out
protected $allowAnonymous = [
    'update-address-form-html'
];

// Success while logged out
protected $allowAnonymous = [
    'update-address-form-html' => self::ALLOW_ANONYMOUS_LIVE
];

The general question is: what has been updated with the allowAnonymous behavior in Craft 3.2 and what scenarios does it require that we use the additional configuration settings such as ALLOW_ANONYMOUS_LIVE and ALLOW_ANONYMOUS_OFFLINE?


texts:
I am developing my Craft site locally with MAMP. Today when starting my site on localhost, I got this error:

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

I have replaced the /app folder with a fresh copy, but it didn't help.

Also, I can no longer log into my site: When navigating to my login page, I get the same error as mentioned above.

I have a recent database backup in /craft/storage/backups. Is there a way to get my site up and running again?


texts: Display field content inside a matrix from a different locale

texts:
I am building a site with 2 different languages - English and Chinese. Is it possible to retrieve only one field inside a matrix in English while I am in Chinese site? But the rest of the matrix fields, I want them to be kept in Chinese.
Below is an example snippet from retrieving the field inside the matrix. Is it possible to force translate it directly to English regardless of the current locale the site is in?
{{ globalMatrixTable.globalPresenceItem }}


texts:
All I'm trying to do is put the category title on a category listing page into the title tag.
So I've got the variable set up, but if I add the category title tag:

{% set title = "{{ category.title }}" %}

The end result is this

<title>{{ category.title}}</title>

So do I need to escape the quotes?


texts: How does Craft automatically wrap `fields[]` around name attributes?

texts:
When you use a form macro to generate an input in the CP, you'll end up with something like this...

<input type="text" id="fields-myField" name="fields[myField]">

Oddly, it looks like "myField" is generally passed around the code as a single name value.

What code in Craft core is responsible for automatically appending the fields- to the id attribute, and wrapping fields[] around the name attribute?

I've scoured the Craft core code and just can't find it. That magic doesn't seem to be happening in a Twig macro or JavaScript.


texts: Front-end searching: Automatically redirect when only 1 result

texts:
When performing a search on the front-end, is it possible to have two different behaviors, depending on the number of results?

With more than one result, show the normal "results" page.
With only a single result, automatically redirect to that entry page.


texts: Query Entry Using multiple custom Fields Element API

texts:
I'm trying to return just one entry from Element API based on custom fields created?

return [
    'endpoints' => [
        'students.json' => [
            'elementType' => 'Entry',
                'criteria' => [
                    'studentNumber' => craft()->request->getPost('studentNumber'),
                    'email' => craft()->request->getPost('email'),
                    'section' => 'students',
                ],
                'transformer' => function(EntryModel $entry) {
                return [
                    'studentNumber' => $entry->studentNumber,
                    'email' => $entry->email,
                ];
            }
        ]
    ]
];

The Fields are studentNumber and email but it seems to be returning everything. Even when specifying first => true

Anybody point me in the right direction on this? I'd imagine I'm missing something obvious?

Even hitting the url students.json?studentNumber=001 is returning everything.


texts: Unverified emails blocking user registration

texts:
craft()->users->saveUser seems to check email for uniqueness across ALL users, not just verified ones.

It seems like it should only check against verified ones to me.

Example:

boob@gmail.com registers (only he fat fingered and it was supposed to be bob@gmail.com). Bob never gets his verification email, but that's his fault. Boob gets one, doesn't know what it is and ignores it.
Later, the real boob@gmail.com now tries to register, but he can't because boob@gmail.com is sitting there unverified, squatting on that email.

At this point you could have an option to resend the activation code, however once boob@gmail.com get that and verifies it, his account will now be the account that the other guy actually signed up for, so if you're doing stuff with accounts, it might have data associated with it you don't want.


texts: What would be the best way to build an Ad rotator?

texts:
What would be the best way to build an Ad rotator similar to those we usually see around from http://fusionads.net for example.

WordPress have a plugin/widget for adding ads: https://wordpress.org/plugins/ad-rotator/

Basically it shows random HTML code every time you refresh the page.

I was wondering how we can do that with Craft.


texts:
I have some 'Flip PDF' generated folders that I need only logged in users to be able to access. If I put them in templates I get the problem that the .jpg images 500. Is there a way of allowing .jpg images to be served from within the templates folder? This isn't as simple as using an 'internal assets' plugin and adding them manually as all of the flip pdf JS is created automatically and I don't want to have to edit it every time a new one needs to be uploaded.

I've searched high and low for the answer to this over the last few weeks as well as asking on slack but I've had no luck.

Edit: maybe there's a .htaccess file I can add in the template sub directory that will prevent images being loaded in the normal 'craft' way?

The folder structure looks like this:

craft
templates
    emag
        july-2018
            files
                mobile
                    *.jpg
                mobile-ext
                    *.jpg
                thumb
                    *.jpg
                    etc.
            mag
                javascript
                    *.js (loads fine)
                index.html <--- the 'magazine' that needs the jpg's

The contents inside 'july-2018' is what the software gives me. All works fine, except for the .jpg images.


texts: How can I check if a plugin is installed and enabled?

texts:
As the title suggests, I was wondering how to check if a certain plugin exists (and has been installed).

And secondly, check that the plugin is actually enabled.

Thanks,

Mark


texts: Template extraction of namespace node values from RSS using Feedme plugin

texts:
I'm using the Feed Me plugin in a template to extract data from an RSS feed.

So if the RSS contains the following snippet

<category>Physiology</category>
<pubDate>Mon, 02 Nov 2015 00:00:00 +1100</pubDate>
<dc:creator>Joe Bloggs</dc:creator>

I can extract the data for the first two nodes using {{ node.category }} or {{ node.pubDate }}. But for the third {{ node.creator }} doesn't work and {{ node.dc:creator }} results in an error.

What is the correct way to extract node data that has a namespace defined?


texts: How can I force a slug to update on save

texts:
I'm using the auto generate entry titles from custom fields option, eg

{eventVenue}-{seriesName}-{eventDate}

But sometimes the eventVenue isn't known at the time of creating the entry, so you can end up with a slug of tba-winter-2017-04-15. But when they later update the eventVenue the slug is not right. It's not very easy to explain to users that they can/should change the slug and for them to remember to do so.

I fully understand the thinking that in many cases the slug shouldn't change due to existing links that may exist and will now break, but is there a way to override the default?

In ExpressionEngine I used an addon, "Title Master" that had the option to update url on edit or not.


texts: Total count of entries related to entry from another section (structure), including all levels within that section

texts:
I have two sections: Products (channel) and Accessories (structure).
The Accessories section is a structure and can multiple levels to it, a Product may relate to a child (level 2) but not it's parent (level 1)
I relate a Product to on or many Accessories using the Entries field type in the Product entry section.
What I want to do is list the top level Accessory entries with the total amount of products it relates to, since it could relate to a child of a top level, or even a third level, is it possible to get that count?
{% set accessories = craft.entries().section('accessories') %}

{% for item in accessories.all() %}
    {{ item.title }} (total products that relate to the parent thru a direct relationship or lower level relationship)
{% endfor %}


texts: How to reference domain specific asset path in multi domain multi env setup?

texts:
I have a site setup for Craft 3 like below
.env variables for development
local
staging
production

Folder structure is standard.
My assest volumes are like below.

'@assetBaseUrl/documents/xx'
'@assetBaseUrl/web/assets/documents/xx'

I need to add a new site on separate domain which i have done in Craft control site manager. For the moment its called "awards"

I added domain specific variables to .env like:

CRAFTENV_BASE_URL_AWARDS = "https://awards.com/"
CRAFTENV_BASE_PATH_AWARDS = "/mypath/"
ASSET_BASE_URL_AWARDS="https://awards.com/assets"
ASSET_BASE_PATH_AWARDS="/mypathft3/public_html/assets/awards"

My config file only references asset paths for domain 1 from the .env file.  For example:

    'baseUrl'  => getenv('CRAFTENV_BASE_URL'),
    'basePath' => getenv('CRAFTENV_BASE_PATH'),
    'aliases' => [
        '@assetBaseUrl' => getenv('ASSET_BASE_URL'),
        '@assetBasePath' => getenv('ASSET_BASE_PATH'),
        '@baseUrl' => getenv('CRAFTENV_BASE_URL'),
        '@basePath' => getenv('CRAFTENV_BASE_PATH')
    ],

I am using the same templates folder for domain 2 as domain 1 and craft is finding this OK with my one basic section:

/templates/<sitename2>/

SO my question is how do i achieve separation of assets volumes for domain 2?
Do i use domain 2 specific env variables in asset folder paths that can read my .env domain specific vars then use these in new volumes?

What if I want to share volumes across sites?

Been baking my noodle for hours


texts: How to setup re-usable non-entry specific data in Craft?

texts:
The current CMS I use allows me to create data tables with list data that I can then re-use across different page-types throughout the sites that I build.

The only way I can see to make use of concept in a similar way without developing a custom plugin in Craft is to create specific entry types with tables to input and retrieve data from.

Does anyone have any advice on what the best practice would be with Craft with regards to larger sets of table data?


texts:
As a content strategist, I'm trying to take the memory and guesswork out of my client's experience while updating the site (check out this great article, "Training the CMS"). Field instructions are great for that. But I'm doing some things that aren't intuitive to the user on the back end, and I want to add instructions/explanation on the affected entry types.

I think this could be effective in various places:

Above the Title field
In an Instructions tab
Above or below the right sidebar

Is there a field type that would let me just include text with no user interaction? Or a way to add instructional text to the entry interface? Bonus if I have the option to include images, links, and basic formatting too. I haven't explored plugins yet, because I'm still learning my way around Craft, but I'm open to using them.


texts: Character Limit incorrect for international characters

texts:
I've been running into errors importing specific entries in my custom module. Boils down to an issue with the Character Limit on the Plain Text fieldtype when importing international characters.

It seems like the Character Limit on the field is actually the number of bytes and not characters. The text I'm trying to import has some multi-byte Japanese characters, so it is reporting the length incorrectly.

I've had a poke around the Craft and yii source and found some string validation, but then it gets a bit beyond me.

For now I've just extended the length limit, but would good to work out if I have something setup incorrectly.


texts: Display list of countries in form using a dropdown

texts:
So I'm using this territories plugin to display a list of countries in a dropdown. The issue I'm having is showing these countries within my front-end entry form.

I've used this example but it doesn't work:

{% for option in entry.territoryFieldHandle.options %}

{{ option }}

{% endfor %}

Here's my whole form. The other dropdowns work fine.

             {% set jobTypeDropdown = craft.fields.getFieldbyHandle('jobType') %}
        Job Type
        <select name="fields[jobType]">
            {% for option in jobTypeDropdown.settings.options %}
                <option value="{{ option.value }}">{{ option.label }}</option>
            {% endfor %}
        </select>

        {% set jobCategoryDropdown = craft.fields.getFieldbyHandle('jobCategory') %}
        Job Category
        <select name="fields[jobCategory]">
            {% for option in jobCategoryDropdown.settings.options %}
                <option value="{{ option.value }}">{{ option.label }}</option>
            {% endfor %}
        </select>

        Country
        <select name="fields[country]">
            {% for option in entry.country.options %}
                <option value="{{ option }}">{{ option }}</option>
            {% endfor %}
        </select>


texts: How to set entries to auto-expire after certain # of days from post date?

texts: Is there any way to set entries of an certain entry type to auto-expire after a certain number of days from the original post date?


texts: Choose not to save an element on EVENT_BEFORE_SAVE_ELEMENT

texts:
I want to do some server side checks to see if the entry should be saved or not.

In my plugin I have something like that

Event::on(
    Elements::class,
    Elements::EVENT_BEFORE_SAVE_ELEMENT,
    function(ElementEvent $event) {
        if ($event->element instanceof \craft\elements\Entry) {
            $entry = $event->element;
            if ( $entry->sectionId == 5 ) {
                $entry->enabled = 0;
            }
        }
    });

This works but what I want is for the entry to not be saved rather then be disabled. Something I could achive on the user model with:

$event->isValid = false;

Is there a way to withhold the entry from saving? The only other solution I can think if is to make the tests in the AFTER event and delete it if not passing the condition.


texts:
Does anyone know a proper way to DRY up an entry template so that it can dynamically become an item listing vs. an entry page? For a (non-working) example:

{% if item is defined %}{% else %}{% extends [entry.locale ~ "/layout", "_layout"] %}{% endif %}

Not sure why this isn’t working, but it would allow creating one template per section/type and then conditional output based on how you called it in a template, i.e. {% include "entry" with { "item": "small" }

Instead of having to create a separate template to output a smaller/truncated version of an item in a list.


texts: Odd error message when editing field settings (Variable "targetLocaleFieldHtml" does not exist)

texts:
After upgrading a site from 2.4.x to 2.6.x, I'm experiencing an odd issue where Craft throws the following template error whenever I attempt to edit a field:

Variable "targetLocaleFieldHtml" does not exist

The error message only displays if devMode is set to true, occurs for all fields and fieldtypes (also when attempting to create a new field), and prevents me from actually editing field settings (unless I turn off devMode).

Here's the full stack trace:

Template Error

Variable "targetLocaleFieldHtml" does not exist

/somepath/craft/app/templates/_components/fieldtypes/elementfieldsettings.html(33)

21                     options: sources,
22                     value: settings.source
23                 }) }}
24             {% endif %}
25         {% else %}
26             {{ forms.field({
27                 label: (allowMultipleSources ? "Sources"|t : "Source"|t)
28             }, '
' ~ "No sources exist yet."|t ~ '
') }}
29         {% endif %}
30     {% endblock %}
31
32     {% block targetLocaleField %}
33         {{ targetLocaleFieldHtml|raw }}
34     {% endblock %}
35
36     {% block limitField %}
37         {% if allowLimit %}
38             {{ forms.textField({
39                 label: "Limit"|t,
40                 instructions: "Limit the number of selectable {type}."|t({ type: type|lower }),
41                 id: 'limit',
42                 name: 'limit',
43                 value: settings.limit,
44                 size: 2,
45                 errors: settings.getErrors('limit')
2016-06-06 18:44:40 Apache / Craft 2.6.2789


texts:
I'm having trouble setting entries with multiple relations.
during testing I've hard coded the theme to 1 specific category
{% set themeID = "12309" %}
{% set theme = craft.categories.group('survivorThemes').id(themeID).all() %}

I then set this
{% set survivors = craft.entries.section('authors').includeInRecollection('1').relatedTo({ sourceElement: relatedAssetIds }).orderBy('lastName asc').limit(null).all() %}
and then a for loop
        {% for survivor in survivors %}
            {% set relatedIds = "" %}

{# this should work but doesn't #}
            {% set entries =
                craft.entries.section('survivorAssets')
                .relatedTo('and', { targetElement: themeID },{ targetElement: survivor })
                .orderBy('assetOrder')
                .all()
            %}

{# this should also work but doesn't #}
            {% set testEntries = craft.entries.section('survivorAssets')
                .relatedTo('and', {targetElement: survivor, field: 'relatedSurvivor'}, {targetElement: themeID, field: 'themes'})
                .orderBy('assetOrder')
                .all()  %}

            survivor: {{ survivor.title }}

            theme: {{ themeID }}

            ids: {{ relatedIds}}

            total results: {{ entries|length }}

            test total: {{ testEntries|length }}

                {% if entries|length %}
                    {% set activeClass = " active" %}
                    {% for entry in entries %}
                        {% set relatedIds = relatedIds ~ entry.id %}
                        {% if not loop.last %}
                            {% set relatedIds = relatedIds ~ "," %}
                        {% endif %}

              more code here

                    {% endfor %}
                {% endif %}

        more code here

        {% endfor %}

In the above loop I expect the entries to have results but I get zero results in my test div.

survivor: Judy Abrams
theme: 12309
ids:
total results: 0
test total: 0

Have confirmed that there should be 3 entries that match the entries or testEntries variable by looking at specific entries in the control panel.


texts: I am building a bilingual website using Craft CMS. The english entries are completed and I am now in the process of doing translating the content to french. I would like to know if there is a way clone the english entries to the french entries so I can just change fields that are different?


texts: Bad Request: Post Request Required when saving hyperlink in specific redactor field

texts:
I'm having a strange issue here. I have a site running Craft 3.3.7. I have an entry with a matrix field with several redactor fields in it. In one of those redactor fields, I have a paragraph of text. I can save the entry fine, until I try to add a hyperlink (either via the button or adding it in the html editor) at which point I get a Bad Request: Post Request Required error.

I can add hyper links to the other redactor blocks on the entry and to other entries on the site. I tried simply adding a new block and moving the text to there but I get the same error.

I can save the paragraph without the link, so there doesn't seem to be a strange character throwing it off. And it has nothing to do with the href destination as I tried several and even left it empty and received the error every time.

I found an issue in the Redactor github that looks similar that was related to the HTML Purifier, but that it is switched off for this field.

I've checked with server support and there are no relevant errors displaying on that end.

I've checked the craft error logs and it looks like adding the hyper link is causing the attempt to save to come through as an empty post request, thus the error. Unsure why that is.

2019-12-06 17:38:24 [-][12172][ql7adqo20ana0h4he9iiv3iv30][error][yii\web\HttpException:400] yii\web\BadRequestHttpException: Post request required in /home/[sitename]/vendor/craftcms/cms/src/web/Controller.php:333
Stack trace:
#0 /home/[sitename]/vendor/craftcms/cms/src/controllers/EntriesController.php(311): craft\web\Controller->requirePostRequest()
#1 [internal function]: craft\controllers\EntriesController->actionSaveEntry(false)
#2 /home/[sitename]/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#3 /home/[sitename]/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#4 /home/[sitename]/vendor/craftcms/cms/src/web/Controller.php(187): yii\base\Controller->runAction('save-entry', Array)
#5 /home/[sitename]/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('save-entry', Array)
#6 /home/[sitename]/vendor/craftcms/cms/src/web/Application.php(299): yii\base\Module->runAction('entries/save-en...', Array)
#7 /home/[sitename]/vendor/craftcms/cms/src/web/Application.php(566): craft\web\Application->runAction('entries/save-en...', Array)
#8 /home/[sitename]/vendor/craftcms/cms/src/web/Application.php(278): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#9 /home/[sitename]/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#10 /home/[sitename]/html/index.php(21): yii\base\Application->run()
#11 {main}
2019-12-06 17:38:24 [-][12172][ql7adqo20ana0h4he9iiv3iv30][info][application] $_GET = [
    'p' => '500.shtml'
]

$_POST = []

$_FILES = []


texts:
I am a beginner when it comes to Craft and I have a hard time finding good detailed tutorials when it comes to specific questions. I know that Craft has it's own documentation but for me it's a little hard to find exactly what I want. So what I would like to know is how you can embed the header and the footer in every page with a simple tag.

I know that in Expression Engine all you had to do is was the following:

<html>
  <head>
    <title>News Site</title>
  </head>
  <body>
    {layout:contents}
  </body>
</html>

And on any other page you could add this tag and you were done.

{layout="site/.html-layout"}

{exp:channel:entries channel="news"}
  <h2>{title}</h2>
  {summary}
{/exp:channel:entries}

How can I achieve the same thing in Craft? Thank you for your time and help :)


texts: Prevent Redactor from adding site identifier to entry links

texts:
I have a multi-site setup, and when using Redactor's Link to an entry function, by default, site identifiers are added to the link href:

href="https://mysite/my-page#entry:4223@3:url"

I would like to prevent (or strip out) the @3 site identifier, because I wish to use the current site's base URL, rather than specify a specific site's base URL be used. Is this possible?


texts: File input attachment format for Contact Form plugin

texts:
Is it possible to specify the file formats for an upload field with the Contact Form?

Is it controlled by the extraAllowedFileExtensions setting?


texts: How can I use a session consistently in a service and variable?

texts:
I’m working on a simple cart and trying to utilize the user session id to keep track of things.

The session getting saved to the database doesn't match the session that’s being displayed in templates. I have a template variable set-up to output the session on the front end for comparison.

There’s quite a bit of code with a plugin so I’ll include what’s most relevant.

I have a service setup that included methods for saving an item and loading a session through a variable. In the service constructor the session is set like so:

class EyeCart_CartService extends BaseApplicationComponent
    {
    private $_cartSession;

    public function __construct()
    {
        $session = new  HttpSessionService;
        $session->open();
        $this->_cartSession =  $session->sessionID;
    }
    etc.

I then use _cartSession in the saveItem method. This works fine.

public function saveItem(EyeCart_CartModel $item)
{
    ….
    // Set the cart record attributes
    $cartRecord->session = $this->_cartSession;  // the session saves as bakg59bu9lmbbs50s8meg5jk71
    $cartRecord->itemId = $item->itemId;
    etc…

In the service I also have a cartSession method for outputting the current session in the template via variables (for testing).

public function cartSession()
{
   return $this->_cartSession;
}

This returns a different value than is being saved in the database (9m9g3msjo3v9f8ke7gf4b3qfv0). I tried including the cart variable on different templates and it displays consistently across page states just not when saving to the db.

Any advice?


texts: Replace substring in string with variable named as substring?

texts:
Could you help me with something?

In a frontend template, I'm trying to go through the string, find all substrings between double curly brackets {{ something }} using regular expressions and replace them with field values that have the substring in the name. I want it to work dynamically.

i.e. replace string {{ something }} with value of field {{ entry.something }}, replace string {{ something-else }} with value of field {{ entry.something-else }} ...etc.

I tried the replace filter, and I'm able to find the strings between curly brackets, but I don't know how to replace them with actual fields values.

Thanks


texts: I have nginx and PHP up and running.  phpinfo() shows that mcrypt is installed and enabled.  I was sure to sudo php5enmod mcrypt.  However, Craft is still complaining the mcrypt isn't installed.  What else can I troubleshoot?


texts:
I have an Matrix field and I want to extract data in the following HTML structure:

text1

text2

text3

text4

text5

text6

and this is my twig code for retrieving data from craft:

{% for entry in entries %}
  {% if loop.index is divisible by(3) %}

text4

text5

text6

{% else %}

text4

text5

text6

{% endif %}
{% endfor %}

I want to output multiple browse with free divs
I am new to Craft and I will appreciate any help, thanks!


texts:
What's the best solution for having a 'gallery' block inside of a Matrix? By 'gallery block' I mean an ability to have multiple images, with captions, alt, and link, presented as a gallery on the front-end, but as part of a parent Matrix (the user needs to control the location of the gallery within the page content, so the page content is a Matrix).

What I really need is a Matrix within a Matrix, but that's not possible with Craft at the moment. I'd thought using a Table type inside the Matrix might work, but Craft doesn't offer Asset as a type for use inside a Table (makes sense, this would be a hacky use of 'table').

Another work-around might be to just have 'singular image' blocks and have the Template code notice when multiple Image blocks occur as siblings, and convert those into gallery mark-up - but I've no idea how to code that, if it's even possible.

Do you have better solutions?


texts: Programmatically set a field from the Sprout Fields plugin

texts:
We are building a custom frontend form allowing users to create their own entries. How can we set the sprout fields programmatically in the backend? This is what we have tried so far with the phone field:

$request = Craft::$app->request;

$phone = $request->getBodyParam('phone');

$artist = new Entry();

/** Set other fields... */

$artist->setFieldValue('phone', $phone);

$success = Craft::$app->elements->saveElement($artist);

if (!$success) {
    return $this->sendErrors($artist, $user);
}

return null;

We can query artist.phone in a template, and sure enough, it returns the value. However, in the craft admin panel, the field is blank. Is there a correct way of setting a sprout field?

We need to set the phone and address fields. Thanks for your support!


texts:
Within the config folder there is a general.php file with various vars which are site specific.

how do i get at these from within a plugin?

Thanks for your help.


texts: How do I load composer dependencies for a Yii module that's in my site repo?

texts:
I have a site-specific module in my modules directory that's being loaded in config/app.php. Since it won't be used elsewhere I am not storing the module in an external repository.

When I added a composer.json file to load some dependencies for the module and ran composer update, it created a new vendor directory inside the module directory.

Is there a way I can have a composer.json inside that module directory, but have the dependencies loaded in the main vendor directory?

Or am I doing something totally wrong here?


texts: Set up Craft 3 when the craft folder is above public_html on shared hosting

texts:
I'm trying to setup Craft 3 on a shared host. It succeeds when I place all files in the public directory and then go to /web.

But if I move the craft files to the folder /private_html/craft and the web files in /public_html it won't work (error 500). Do I need to edit the index.php file after all (not mentioned in the installation docs)?

Tried setting the index.php lines to ../private_html/craft/vendor and ../private_html/craft/.env, but no luck. I get the feeling the index.php needs a pointer where the craft folder resides?

<?php

// Set path constants
define('CRAFT_BASE_PATH', dirname(__DIR__));
define('CRAFT_VENDOR_PATH', CRAFT_BASE_PATH.'../private_html/craft/vendor');

// Load Composer's autoloader
require_once CRAFT_VENDOR_PATH.'../private_html/craft/vendor/autoload.php';

// Load dotenv?
if (file_exists(CRAFT_BASE_PATH.'../private_html/craft/.env')) {
    (new Dotenv\Dotenv(CRAFT_BASE_PATH))->load();
}

// Load and run Craft
define('CRAFT_ENVIRONMENT', getenv('ENVIRONMENT') ?: 'production');
$app = require CRAFT_VENDOR_PATH.'../private_html/craft/vendor/craftcms/cms/bootstrap/web.php';
$app->run();


texts: Change date language in a client version of craft

texts:
I've installed a client version of craft. Apparently this is set in my local language (Dutch). First question is if that is something you can set to another language or must I install a Pro version for that? (Dutch is fine, but just would like to know)

Now, while the CP is in Dutch, if I parse the month, it is in English:

{{ entry.postDate.format('F') }}

So how can that be set in Dutch as well?


texts: Making discounts gives error on payment gateway

texts:
When i applied discounts, my payment gateway gives an error. It says that Basket items price must be greater than zero. Here is the section that takes items in cart:

// Add items
    $basketItems = [ ];
    $items       = $this->getItems();

    foreach ($items as $item) {
        $basketItem = new \Iyzipay\Model\BasketItem();
        $basketItem->setId("item:" . $item->getName());
        $basketItem->setName($item->getName());
        $basketItem->setCategory1("Category1");
        $basketItem->setCategory2("Category2");
        $basketItem->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
        $basketItem->setPrice('' . ($item->getPrice() * $item->getQuantity()));

        array_push($basketItems, $basketItem);
    }

    $request->setBasketItems($basketItems);

Without discounts plugin works fine. I can get payments.

One additional thing is; that payment gateway accepts two basket amount as price and paidPrice which is total amount of basket and final amount(tax+discount+sale...) respectively. But when i look at my plugin this amount is set as same:

public function getData ()
{
    $card = $this->getCard();

    $amount = '' . $this->getAmount();

    $email     = $card->getEmail();
    $firstName = $card->getFirstName();
    $lastName  = $card->getLastName();
    $fullName  = $firstName . ' ' . $lastName;

    $billingAddress = $card->getBillingAddress1() . ' ' . $card->getBillingAddress2();
    $billingCity    = $card->getBillingCity();
    $billingCountry = $card->getBillingCountry();

    $shippingAddress = $card->getShippingAddress1() . ' ' . $card->getShippingAddress2();
    $shippingCity    = $card->getShippingCity();
    $shippingCountry = $card->getShippingCountry();

    $request = new \Iyzipay\Request\CreateCheckoutFormInitializeRequest();
    $request->setLocale(\Iyzipay\Model\Locale::TR);
    $request->setPaymentGroup(\Iyzipay\Model\PaymentGroup::PRODUCT);
    $request->setCurrency('TRY');
    $request->setConversationId('' . $this->getTransactionId());
    $request->setPrice($amount);
    $request->setPaidPrice($amount);
    $request->setCallbackUrl($this->getReturnUrl());

Shouldn't be the price and paidPrice be different? May be these two are not related but i want to mention.


texts: Looking to use a tag slug/URI and loop through entries of that tag

texts: It doesn't appear that tags are handled the same way as categories in the sense that categories have a slug (which results to a URI). I'd like to use tags to link to a "tag" page, similar to a category page, but "Really Cool Tag Name" doesn't work/look right as part of a URL. I've used the Slugify plugin to turn the tag in to a slug, however, I'm not sure the best approach to return the relationship of that tag as that slug is not related to the tag at all. Would the best practice be to add an additional slug field to the tag group? Then I'd be able to make that relationship. Thoughts?


texts:
Was just wondering how (or if) you can remove text from redactor:
(there might be a better way to deal with this all together - im option to suggestions)
the use case is I just want to have the video option (youtube links) for a specific field.
I have altered my config.json file for redactor:
 {
  "buttons": ["video"],
  "plugins": ["video"],
  "linkNewTab": true,
  "toolbarFixed": true
}

But this still allows text to added (so maybe this is not possible?):


texts: How to include a section name in the page title?

texts:
I can get Craft to generate page titles for entries and individual pages using:

{% set title = entry.title %}

and

{% set title = "News and Insights" %}

But I need to be able to generate a full page title for an entry, that includes the section name, for example:

News Item | News and Insights | Company Name

Can anyone please explain how...?

Many thanks!


texts: My content within all of my pages has disappeared.  The website is only displaying the header and footer on each page. When I try to restore the internal page to it's previous version to get the content back I get this error: "Internal Server Error: mb_convert_case() expects parameter 1 to be string, array given".  I also cannot add anything to my pages other than Assets.  When can I do to get the content back?  Any ideas on how to fix the Error I'm getting?  Thank you!


texts: Importing Entries from Craft 2 to Craft 3 with Feed Me - find/replace twig filter issues

texts:
I'm migrating content from an old Craft 2 site (2.6.2985) to a new Craft 3 site. Cannot do a strait upgrade for various reasons.

I've started to set up an XML feed to use Feedme with. I am running into one issue where the body redactor field has a lot of images in it and I want do a find and replace to remove the absolute url and replace with a relative url so images will load on the front end.

My code:

<root>
{% for entry in craft.entries.section('articlesAndExcerpts').status('not foo').limit(1) %}
  <entry>

    <title><![CDATA[{{ entry.title }}]]></title>

    {# more fields here #}

    <body><![CDATA[{{ entry.body|replace('src="https://memoirs.azrielifoundation.org/': 'src="/'}) }}]]></body>

  </entry>
{% endfor %}}
</root>

With without the |replace('') filter everything is good. However when I use the replace filter it replaces the url as expected but at the same time creates a lot of html entities, like this:

How can I prevent this from happening and still do a find/replace on the image urls?


texts: redirect to url and set variable in template

texts:
In a plugin, I am trying to redirect to a url, and set some values on the template. It's not working. Here is a simplified (not working) test case:

Template lives at templates/test.twig:

someVar is defined? {{ someVar is defined ? 'yes' : 'no' }}

<form method="post" action="" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="site/test">
  <input type="hidden" name="redirect" value="/test">
  <button type="submit">Submit</button>
</form>

Controller code (which does get called):

public function actionTest() {
    craft()->urlManager->setRouteVariables(array(
        'someVar' => 23
    ));
    $this->redirectToPostedUrl();
}

What I expect, is that when I first visit the page, someVar isn't defined, but when I submit the form and revist the page, someVar will be defined (and equal 23). But it is not defined.


texts: Craft Commerce and Worldpay not marking payments as complete

texts:
I'm working on a Craft Commerce 1.2.1331 site using Worldpay but I'm having problems with Worldpay test transactions not completing the order first-time.

Users are redirected from Worldpay to the Order Thank You template but the order is not being marked as Complete. It remains an active cart. Then, if you checkout again, the order is marked as complete and the cart is emptied. Anyone?

There's nothing in the logs. Actually, there isn't a Commerce log.


texts: Error while trying to use dynamic routing to pass variables to the template and using them

texts:
So i'm trying to pass the variables from a dynamic route to a template and then to use those variables to filter trough entries.
the catch is that the same template is used to display an "organic"(by organic i mean that it is set up from the CP) category as well.

This is the routes.php

'shop/(?P<segmentCategory>(new|used))/(?P<segmentEntryType>[a-z]+)' => 'shop/category',

And this is from the template:

{% if segmentCategory is defined %}
    {% set category = craft.categories(segmentCategory) %}
    {% set games = craft.entries({
        type: segmentEntryType,
        relatedTo: ['and',
            { sourceElement: craft.entries.section(segmentEntryType).status(null) },
            { targetElement: category }
        ]
    }) %}
{% else %}
    {% set entries = craft.entries.relatedTo(category) %}
{% endif %}

The error:

    Object of class Craft\ElementCriteriaModel could not be converted to string

craft/templates/shop/category.html(47)

47 {% extends "_layout" %} ||||||||||||||(Highlighted)||||||||||||||||
48 {% block content %}


texts: How can I get the server's timezone in a Craft plugin?

texts: I'm setting up cron jobs from my plugin and I need to format the date in the server's time zone. It looks like Craft is overriding the timezone set in php.ini because PHP's date_default_timezone_get() always returns UTC. Is there another way to get the actual timezone set on the server?


texts:
After some research surrounding this I can't seem to fix this issue. So for a project I made a simple module with some variables that simply has to make an OAuth1 call and return some data.

The provider of the website advised me to use :

https://github.com/thephpleague/oauth1-client

So in my module I initialised another composer.json and required the package above. It gets correctly installed to the vendor map in my module. However whenever I call the new OAuth() or new OAuth1() it can't be found.

I've tried adding it while using the packagepath in the top of my module.php as well as my moduleVariable.php but to no avail. I was wondering if I'm doing something wrong? Or forgetting something? What's the best way to add composer libraries to your own custom module?

Best regards!


texts:
On the property development website I'm building for an agency client it has a section on the individual property page that shows the floorplans for the building. Which has different amounts of levels depending on the property. So for example one property might have a basement, a ground floor, and a first floor. Whereas another might have a Ground, First and Second Floor etc.

Each floor has an image of the floorplan as well as text showing the dimensions on the left of it.

On the design visual the floors are switched between using the dropdown button, which lists the available floors.

So I'm not sure how to approach this. Should it be a matrix, or set fields etc, and how will it link up to the dropdown.

Need some guidance on the best approach that's going to make it as simple as possible for the client?

Kind regards

David


texts:
I'm starting to dive deeper w/Vue + Apollo + CraftQL but I'm not getting any data on my http://localhost:8080/ but it is mostly working on my Laravel Valet host of https://hybridinteractive.test/test.html (which is where Craft CMS is served from). I'm trying to simulate having my content served up from one location and consuming the data directly thru my Vue app.

So I'm wondering if it's a weird CORS issue? I have my access token working under the CraftQL settings and verified that it's working.

At any rate, I hope I'm missing something simple here and thanks for reading!

Here's my main.js:

import Vue from 'vue'
import App from './App.vue'
import ApolloClient from "apollo-client";
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from "vue-apollo";

Vue.config.productionTip = false;

// HTTP connection to the API
const httpLink = new HttpLink({
    uri: 'https://hybridinteractive.io/api',
    fetchOptions: {
        mode: 'no-cors',
    },
})

// Cache implementation
const cache = new InMemoryCache();

// Create the apollo client
const client = new ApolloClient({
    link: httpLink,
    opts: {
        headers: {
            Authorization:
                "Bearer REDACTED",
        }
    },
    cache,
    connectToDevTools: true
});

const apolloProvider = new VueApollo({
    defaultClient: client,
});

Vue.use(VueApollo);

/* eslint-disable no-new */
new Vue({
    render: h => h(App),
    components: { App },
    provider: apolloProvider,
}).$mount('#app');

App.vue

<template>

Testing

        <GetNavigation></GetNavigation>

</template>

/src/components/GetNavigation.vue:

<template>

Loading...

Navigation List

                {{ entry.title }}

</template>

Finally, my src/queries.js:

import { gql } from 'apollo-boost';

export const GET_NAVIGATION = gql`
query getNavigation($section: [SectionsEnum], $limit: Int) {
  entries(section: $section, level: 1, hideFromNavigation: false, limit: $limit) {
    id
    title
    url
  }
}
`;

export const HELLO = gql`
query {
  helloWorld
}
`;

export const ENTRIES_QUERY = gql`
query GetBlogEntries($section: [SectionsEnum], $limit: Int) {
  entries(section: $section, limit: $limit) {
    uri
    title
  }
}
`;


texts: How can I populate a user field via a plugin?

texts:
I have a plugin that listens for the users.onSaveUser. So when users register, an account is created, and I am creating an entry that will contain extended profile information. I am attempting to create a user field on that newly created entry to relate the entry back to the user account.

MyPlugin.php

$entry = new EntryModel();
$entry->sectionId = 16;
$entry->typeId = 1;
$entry->enabled = false;
$entry->authorId = $user->id;

$entry->getContent()->title = craft()->request->getPost('firstName') . ' ' . craft()->request->getPost('lastName');

// userAccount is the handle of the user field.
$entry->setContent(['fields' => ['userAccount' => $user->id]]);  // nope.
$entry->setContentFromPost(['userAccount' => $user->id]);        // nope.

...

craft()->entries->saveEntry($entry);

Everything is coming across except the user field. I'm not sure what the field needs/is looking for to set it's value.


texts: Commerce: Is shippingZone available as a variable on the shipping method selection template?

texts:
On the template for choosing shipping method, I need to be able to remove/hide some shipping methods from being shown, based on the shipping zone that has been set by Craft, which is based on the address entered, etc.

I'm using Postie for live Fedex rates, along with a couple of custom shipping methods, but Postie adds its live rates to the array of shipping methods regardless of the shipping zone, so I end up with my custom method, plus the Fedex methods, when I just want the custom one.

I'd like to evaluate shippingZone that is set for this cart, and if it is zone A or B, not how any Fedex methods, else, show them. I just need access to the shippingZone to do this.

Like so: https://d.pr/i/JCmTiT

Any way to get it?


texts:
What could be the reason for this error when I’m targeting a global field?:

Impossible to access an attribute ("footer") on a boolean variable ("").

I created a global set Footer with a matrix field also named Footer, I'm trying to get its content via:

{% for block in footer.footer %}
  {% if block.type == "column" %}

{{ block.headline }}

{{ block.columnContent }}

  {% endif %}
{% endfor %}


texts: How to delete Matrix fields in front end

texts: I created a user profile page with Matrix field with assets, I found this thread and this thread about adding and updating Matrix field in the frontend. Does anyone know how to delete the Matrix field? Moreover, I found that if I update Matrix field through the front end, it doesn't update the S3 bucket. Files are still stored in S3. Does anyone has a solution or give me a hint on delete/modify Matrix asset field? Thanks


texts: How can I add field content to an asset in code?

texts:
I'm trying to upload an asset based on this code https://gist.github.com/sathoro/8178981
which works fine, but how can I add additional content fields during the upload? I would like to set the caption an additional fields like credit during the upload?


texts: Craft cacheMethod setting is being overridden

texts:
I am trying to setup Craft to use a memcached (yes it is memcached, not memcache) cluster in AWS ElastiCache to handle sessions. I originally went the route of updating my php.ini file in Apache2 to override the PHP session save handler and session save path. That worked at first, but I found that sometimes memcached would seem to return null if a session object was being accessed around the same time. After running into that error a bunch and not being able to resolve it, I decided to try setting up memcached through Craft.

My question is does Craft default to local file storage if it can't connect to my memcached cluster? The reason I think this is happening is because if I use the overridePhpSessionLocation, I can tell that it isn't working because I am getting timed out on my site since we store the timeout in the session. However, when I set overridePhpSessionLocation to 'auto', and then put all the proper information in my memcache.php file, the site seems to work. But if I screw up the hostname in the memcache.php file, the site still works. So what is going on? Is Craft defaulting to local file storage when there is a connection issue or is there something else happening?


texts:
Is the following possible:

{% set issue = craft.entries(section: 'issues', slug: 'october-2014').first() %}

{% set categoryOne = craft.categories({ group: 'articles', slug: 'category-slug-one'}) %}
{% set categoryTwo = craft.categories({ group: 'articles', slug: 'category-slug-two'}) %}
{% set categoryThree = craft.categories({ group: 'articles', slug: 'category-slug-three'}) %}

{% for entry in craft.entries({
    section: 'articles',
    relatedTo: ['and',
        ['or',
            { targetElement: categoryOne },
            { targetElement: categoryTwo },
            { targetElement: categoryThree }
        ],
        { targetElement: issue }
    ]
}) %}

    {{ entry.title }}

{% endfor %}

Attempting to return articles associated with a specific issue from within one of three specific categories.

It appears the parseRelationParam function looks at the first array element to determine the operator but I'm hoping someone has a solution.


texts: How do I get just the first entry with a 'for' loop?

texts:
I have this this code -

{% for entry in craft.entries.section('news').first() %}

{{ entry.title }}

{{ entry.postDate.format('F d, Y') }}

                {{ entry.body }}

            READ FULL STORY...

{% endfor %}

I thought the .first() would pick up just the first news story, however it is returning the same container several times.

I then want to return all other entries elsewhere, so what should I include in my code below to do this -

        {% for entry in craft.entries.section('news').find() %}

{{ entry.title }}{{ entry.postDate.format('F d, Y') }}

        {% endfor %}


texts:
Running Craft version 2.3, build 2644, schema version 2.3.4... we clicked "update" and got an error screen that looks like the install screen that simply says "oops".

How can I restore my site from the files that are in the (automatically generated) folder "app.bak"?


texts: Showing a generic image when no image is chosen

texts:
I'm trying to do this:

{% for image in entry.illustration %}
    {% if image | length %}

    {% else %}

No image.

    {% endif %}
{% endfor %}

Without any luck. What would be a good way of telling craft to do something else if entry.illustration does not have an image defined?


texts: Database Request with entry variable as argument

texts:
I am new to Craft CMS and although it is quite simple to use I am stuck on this one. I have 3 sections ('books', 'games', 'movies') and want to do the following:

{% for sub_entry in craft.entries('{{ entry.sectionName }}').find() %}

The problem is that it gives me all sub_entries not just the ones within a specific section i.e. entry.sectionName? If I print out {{ entry.sectionName }} on my website it gives me the correct sectionNames but somehow I can not pass it on to the for loop?

How do I solve this?
Kind regards,
Pete


texts: Make getSerializedFieldValues include fields from related entries

texts:
I am looking for a way to make getSerializedFieldValues (or simiular) include fields from related elements.
Today I use the code from Craft-Scout's default ElementTransformer, which gives a decent result, but does not include related elements.
Take this example: bodyPerson is a related elements field. The IDs 40166, 40175 and 40170 represent people entries - which have their own fields. I want to include the people entires' fields too.

I realize I could loop the neo field handles and handle the related fields accordingly, but I wonder - is there a quick way to get all the text from related entries?


texts: Looking to create a dropdown field to select an icon

texts:
I use the same icons across most of my projects, and typically just list them in Dropdown fields. However, this quickly becomes difficult to manage, so I'm looking to create a simple plugin that I can easily reuse.
I've started with pluginfactory.io to scaffold it out, selecting the Field Types component and installed via Composer but struggling from there.

How do I define the list of icons that should show in the dropdown field?
How do I get that to then reference the correct SVG file?
How do I output that properly in my templates with {{ entry.icon }}?

I realise that's literally asking how to build this thing  but I would appreciate some guidance!


texts: Display entries related to a category (only bottom level)

texts:
I have a 2 level category system. Some have children, some do not.
How can I display entries related to the last level only?

If a category has no children, it should show the entries related to the 1st level. And if there are children, it should show entries related to that child category only.

The code below currently shows both levels, which I don't want. How can I tell Craft to look for the last (bottom) level only?

{% set entries = craft.entries.relatedTo(category).order('dateYear','comp_opus','title').limit(0) %}
{% for category in craft.categories.group('compositions').relatedTo(entries) %}
    {% for entry in entries.relatedTo(category).limit(7) %}
        {# Do stuff #}
    {% endfor %}
{% endfor %}


texts: Display related entries on entry page using ElementAPI

texts:
By following the ElementAPI plugin documentation I was able to set up pagination of entries from the ingredients section on an entry page. Entries from the ingredients section have a relation field called relatedEntries.

Sections structures involved - set as an example:

ingredients
drinks

Desired output would be to show entries related to currently loaded entry from drinks section.

So when I'm at site.com/drink-entry-alfa I'd like to display all related entries from section ingredients to that current entry.

Using Twig I'd request current entry.id and use the .relatedTo() parameter to get related entries.

Here is the example from ElementAPI's documentation:

<?php
namespace Craft;

return [
  'endpoints' => [
    'ingredients.json' => [
      'criteria' => ['section' => 'ingredients'],
      'elementsPerPage' => 10,
      'transformer' => function(EntryModel $entry) {
        return [
          'title' => $entry->title
        ];
      },
    ],
  ],
];


texts:
I have quite a simple registration form, something like this:

    <form id="registerUser" method="post" accept-charset="UTF-8" class="flex-stack" novalidate @submit.prevent="userFormValidation()">
                        <input type="hidden" name="action" value="users/saveUser">
                        <input type="hidden" name="redirect" value="user/registration-success">

                        {{ "Username (no spaces)"|t }} *
                        <input id="username" type="text" name="username" v-model.lazy.trim="user.userDetails.userName" :class="{ 'error-field': usernameHasError }" required>
    </form>

It gets passed to VueJS (which works). There I have the default code I find in every AJAX post on Craft StackExchange:

var data = $('#registerUser').serializeArray();

            //--- Add CSRF token to data
            data[window.csrfTokenName] = window.csrfTokenValue;

            $.ajax({
                type: "POST",
                data: data,
                url: "",
                success: function(data, response){
                    console.log("success", response, data);
                },
                error: function(response) {
                    console.log("error", response);
                }
            });

This works when the CSRF is disabled in the config, but when enabled, I always get a bad request, CSRF token invalid error.

What am I doing wrong here? There's no Craft caching going on.


texts: Ignoring "The " and "A " when sorting entries

texts:
I have this code which used to work with 2.x versions:

{% set foobars = craft.entries({ section: "foobars"}).order("(CASE WHEN title LIKE 'The %' THEN SUBSTRING(title, 5) WHEN title LIKE 'A %' THEN SUBSTRING(title, 3) ELSE title END) asc") %}

The idea is sort the entries ignoring the possible "The " and "A " prefix in the entry title, so that the order is more natural and what my client expects.

However the code is giving a SQL error message:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '`subquery` INNER JOIN `entries` `entries` ON `entries`.`id` = `subquery`.`elemen' at line 9

How to achieve the same functionality on Craft 3?

SOLVED (thanks to Brad):

{% set foobars = craft.entries({ section: "foobars" }).orderBy("(CASE WHEN `title` LIKE 'The %' THEN SUBSTRING(`title`, 5) WHEN `title` LIKE 'A %' THEN SUBSTRING(`title`, 3) ELSE `title` END) asc").all() %}

This is still unsolved:

In addition I have to get the previous and next entry in this channel based on the entry title, while excluding "The " and "A " in the beginning.

In Craft 2 this was done with:

{% set foobars = craft.entries({ section: "foobars" }).order("(CASE WHEN title LIKE 'The %' THEN SUBSTRING(title, 5) WHEN title LIKE 'A %' THEN SUBSTRING(title, 3) ELSE title END) asc") %}

{% set prev = entry.getPrev(foobars) %}
{% set next = entry.getNext(foobars) %}

In Craft 3 this seems to be a bit more complicated than that. According to what I've discovered this would almost work:

{% set query = craft.entries.section("foobars").id("not " ~ entry.id).limit(1) %}
{% set prev = clone(query).title("<= " ~ entry.title).orderBy("title desc").all() %}
{% set next = clone(query).title(">= " ~ entry.title).orderBy("title asc").all() %}

But I would have to be able to set the orderBy-clause to use the "(CASE WHEN title LIKE 'The %' THEN SUBSTRING(title, 5) WHEN title LIKE 'A %' THEN SUBSTRING(title, 3) ELSE title END) asc", which does not work in Craft 3.

Now I've tried using this:

{% set query = craft.entries.section("foobars").id("not " ~ entry.id).limit(1) %}

{% set prev = clone(query).title("< " ~ entry.title).orderBy("(CASE WHEN `title` LIKE 'The %' THEN SUBSTRING(`title`, 5) WHEN `title` LIKE 'A %' THEN SUBSTRING(`title`, 3) ELSE `title` END) desc").one() %}

{% set next = clone(query).title("> " ~ entry.title).orderBy("(CASE WHEN `title` LIKE 'The %' THEN SUBSTRING(`title`, 5) WHEN `title` LIKE 'A %' THEN SUBSTRING(`title`, 3) ELSE `title` END) asc").one() %}

But the problem is that if I'm on an entry titled "The Foobar", I would need to search for entries around "Foobar" and not "The Foobar".

How would you modify the query, so that it would include the MySQL "(CASE WHEN...)" logic?

{% set prev = clone(query).search("(CASE WHEN `title` LIKE 'The %' THEN SUBSTRING(`title`, 5) WHEN `title` LIKE 'A %' THEN SUBSTRING(`title`, 3) ELSE `title` END) < 'Foobar'").orderBy("(CASE WHEN `title` LIKE 'The %' THEN SUBSTRING(`title`, 5) WHEN `title` LIKE 'A %' THEN SUBSTRING(`title`, 3) ELSE `title` END) desc").one() %} ?


texts:
I need to get the field type in my templates like I used to do: field.getField.type but that does not seem to be working in Craft 3 anymore. The result is always null. It also seems that the »type« column is gone completely from the craft_fields table.
How do I get the field type in Craft 3?


texts: Save or efficiently query a count from a related table

texts:
I have two custom element types, Event and Booking.

They are related via the eventId column on the Booking record which is a FK to the Event record.

The Booking record also has a seats column.

A usage scenario is that someone may come along and make a booking for two people (seats) at an event. Another person may then make a separate booking for the same event for 4 people.

For each event I'm going to need to know the total seats booked (in our example that would be 6).

Option 1

I could just have a totalSeatsBooked property on the EventModel with something like this:

$totalBookedSeats = 0;
$criteria = craft()->elements->getCriteria('Booking');
$criteria->occurrenceId = $this->id;
$eventBookings = $criteria->find();

if ($eventBookings)
{
    foreach ($eventBookings as $booking)
    {
        $totalSeatsBooked += $booking->seats;
    }
}

return $totalSeatsBooked;

But that's going to get inefficient if I start having to list multiple events at the same time.

Option 2

I could have a column on the EventRecord called totalSeatsBooked and use an onSaveBooking event to recalculate and save the total when ever a booking is saved.

This could work but it might be prone to becoming out-of-sync. I'd also only want to save the total when the booking is created, or when the seats value changes. Which adds complexity.

Option 3

This is the one I'm unsure about.

Could I extend the event's element query some how to join the two tables and run a sub-query to get the seats count? If it was possible and relatively efficient this would be my choice I think.

Any help appreciated!


texts:
Okay, I am here because I would like to have a site in the following structure:

https://site.com  (default english version)
https://site.com/ko (korean)
https://site.com/pt (portuguese)

I would like to use ONE uploads folder to store all of the assets for all 3 languages(plus any additional languages added after), use all of the same templates, and use all of the same css and js files.

My current directory structure is the craft 3 default(I used the cli installer, which is great). Here is the important pieces of what my directory looks like:

-templates
- web
   - dist
      - js
      - css
   - uploads
   - ko
   - pt

Lets say I have the following templates:

- home.html
- newsroom.html
- whitepapers.html
- help.html

I would expect to be able to visit each in the following manner:

(Home)
- https://site.com
- https:///site.com/ko
- https://site.com/pt

(Newsroom)
- https://site.com/newsroom
- https:///site.com/ko/newsroom
- https://site.com/pt/newsroom

...etc hopefully you get the picture.

Is this at all possible with Craft 3? I keep running into issues where each languages site is trying to pull in the uploads or css/js assets from within their respective folders:

Also, here is the sites config in general.php:

'dev' => [
        'siteUrl' => [
          'default' => 'https://site.test',
          'korean' => 'https://site.test/ko',
          'brazil' => 'https://site.test/pt'
        ],
        'devMode' => true,
 ]

SOLUTION
For anyone visiting this in the future, here are the updates to my config that solved the problem. Please refer to this after you have read Robin and Jolle's answers, they are both very helpful.

'dev' => [
        'siteUrl' => [
          'default' => 'http://site.test',
          'korean' => 'http://site.test/ko',
          'brazil' => 'http://site.test/bz'
        ],
        'aliases' => [
            'basePath' => '/Users/dzuz/localhost/site/web',
            'baseUrl'  => 'http://site.test/',
        ],
        'devMode' => true,
    ],


texts: Freeform: Remove default styling injection

texts: I seem to be stuck with a simple -- but quite annoying -- question. I'm setting my own styling for a form and keep running into issues where I'm fighting with Freeform's default styling. I'm not including this anywhere in the template, at least that I know of, yet Freeform still seems to be injecting it's own styling onto the page. Am I missing something here where i can turn that off? Any help here would be greatly appreciated. I have attached an image showing what gets injected that I'd like removed.


texts:
I'm in the process of developing a custom login for a website. Users will not be website users with logins, but rather will be authenticated via an email and a custom token. The process should be as follows:

User arrives at protected page and must enter an email address ending
with @acme.com
If user's email address ends with @acme.com, then generate
a token and send them and email with link including the token.

I am trying to figure out the best way to do this in craft. My initial plan was to create a separate php script which handled the email send and token generation via AJAX, but I figured it's not best practice because it is outwith the CMS, so I should maybe develop this as a plugin.

I wondered if any of you could make some suggestions or perhaps if you'd experience such a process before might shed some light on it.

Thanks


texts: Cache invalidation to automatically update all cached template content?

texts:
I am using the cache tag in my templates. How can I assure that a site visitor always gets the data directly from the cache and never has to wait for it to be generated?

My cache gets invalidated quiet often, as this happens each time new content is created or edits are made.

Any idea on how to trigger the recreation of all cached template content automatically?

.

Edit:

To better explain my use case: some of my craft.assets and craft.entries calls result in a lot of DB queries. Without the template being cached this leads to 3+ seconds delay in page-load. Using Craft cache this is solved for all but one site visitors, because there is still the first visitor, that has to trigger the caches to be created.

I think you shouldn't ignore this single user and hope someone comes up with a solution as additional 3+ seconds in page-load can easily cause customer loss. Further I'd appreciate a solution feasible with core functions, as I consider performance being a key component to every site.

.

2nd Edit:

The reason I started a bounty on this question was to get more attention on it from the community and also from P&T. This seems to work out so far, so thank you all for your thoughts on this and for having this interesting discussion, which is sometimes a little too technical for me (who's not a php/server developer). I actually don't know what to do which the bounty points, but for me it was already worth spending them (who cares for pts anyway?)!


texts: Add user to entry user field [RSVP to Event]

texts:
I'm trying to add an RSVP button for users to register their attendance at my events. Once they click the button, I would like them to be added to a field called eventAttendees on the event entry.

My guess is this could be done as a form submission, and this is as far as I've gotten before getting a bit lost. I'm not sure how to pass the user ID to the entry.

<form method="post" accept-charset="UTF-8">
  {{ csrfInput() }}
  {{ hiddenInput('entryId', event.id) }}
  {{ hiddenInput('userId', currentUser.id) }}
  <input type="hidden" name="fields[eventAttendees][]">
  <button type="submit" class="btn btn-primary">RSVP</button>
</form>

Would appreciate any help!


texts: Creating forms that save to the database & can be viewed in the admin

texts:
is it possible to create forms that save to the DB & a new screen in admin to see the submissions?

Is there a user created forms module (like gravity forms) for Craft?


texts: Pass params to transform function of Transformer class in split Transformer class

texts:
I have transformer like down below in the element API.

'transformer' => 'MyTransformerClassName',

Or

'transformer' => new MyTransformerClassName(),

I am going to pass a param like $user through MyTransformerClassName to use in separate Class Like here.

class MyTransformerClassName extends TransformerAbstract
{
    public function transform(Entry $entry)
    {
        return [
            // ... here want to use $user coming from element api
        ];
    }
}

How can I pass the $user variable to the separate transformer class to use it in transform method?


texts: User defined crop / crop modal for image assets

texts:
Is it possible to have "user defined" crop areas (drag and crop) for upload assets of type image? What I had in mind is something exactly like craft has in the Admin > Settings > General Settings > Logo

Thanks in advance!


texts: background-image CSS property: how to do it right with Craft?

texts:
My current code is:

#header { background-image: url('{{ sitePath }}/assets/toxicomental/header.png'); height: 150px; }

Still, I don't get the image showing.

What do I do wrong?


texts: No live preview & SEO plugin cannot find content on page

texts:
When I try to live preview my craft site the content of the live preview is blank:

This is happening for all pages.
I have set the template file for the page to use:

I am running Craft Solo 3.6.12
Something that is also kinda odd is that the SEO plugin I am using cannot seem to detect the content on the page, my suspicion is that these two things are linked:
SEO plugin:

I get an odd error when trying to use the SEO plugin for key words:

I have looked at some of the issue on github but have not been very successful finding a solution so if anyone has come across this before and could offer some dev wisdom that would be great.
Please ask any questions you might have,
all the best - W


texts: How can I search for entries that are enabled OR disabled?

texts:
Within a plugin I am fetching existing entries using the CriteriaModel class as documented here http://buildwithcraft.com/docs/plugins/working-with-elements#fetching-elements, specifically like this:

$existing = craft()->elements->getCriteria($this->entry->elementType)->first(array(
    'someHandle' => 'someValue'
))

However I am finding this only returns a result if an ENABLED entry is found. I can see that I can search for ONE particular enabled state as follows:

$existing = craft()->elements->getCriteria($this->entry->elementType)->first(array(
    'someHandle' => 'someValue',
    'enabled' => 1
))

Or...

$existing = craft()->elements->getCriteria($this->entry->elementType)->first(array(
    'someHandle' => 'someValue',
    'enabled' => 0
))

But how can I search for ALL entries regardless of the enabled state?

And also, what is the difference between the status and enabled properties on the model? I can see constants for ENABLED, DISABLED and ARCHIVED. I'm not clear on how this differs from the boolean value that the enabled property has.


texts:
I am not a developer and I hope someone can help me. I had purchased a Mailchimp Commerce plugin via the plugin store but I don't know how to install it or find any documents on how to.

I do see the license on my ID but it says "Craft License Not attached to a CMS license."

Do I need a developer to install the plugin? any instructions I can look over?

Any help is really apprecited


texts: Is the "registerSiteRoutes" hook screwing up my template path?

texts:
This may be a bug...
I have a controller action which has been working great. It's a simple action with a single purpose... load a template with an internal value.
public function actionMyAction()
{
    $this->renderTemplate('myplugin/_mytemplate', array(
        'internalVar' => craft()->myPlugin->internalVar
    ));
}

When I call that action via a simple URL, everything loads flawlessly:

mywebsite.com/actions/myPlugin/myAction

Here's where it gets interesting...
So I just discovered the registerSiteRoutes hook. It looks awesome, and would make accessing my special page that much easier for a front-end user!
Here's how I implemented it in my MyPluginPlugin.php file:
public function registerSiteRoutes()
{
    return array(
        'myroute' => array('action' => 'myPlugin/myAction')
    );
}

The good news is, the route is properly followed, and my controller action gets loaded.
The bad news is, suddenly the template that's supposed to be loaded can't be found. :(

Template Error
Unable to find the template "myplugin/_mytemplate".

So does anyone know, what's going on here? I know that the renderTemplate method does some minor rewriting of the template path, but why would it be different when accessing via a front-end route?


texts:
All assets on my website work properly, however I cannot resolve an issue with Imager plugin on a single page template.

My template:

    {% set profileImage = entry.user.photoUrl('original') %}
    {% set transform = {width: 90, height: 90, effects: { grayscale: true, gamma: 1.2 } } %}
    {% set transformedImage = craft.imager.transformImage(profileImage, transform|merge({width: 180, height: 180})).getUrl() %}

        {% if profileImage %}

        {% endif %}

When I try to open a page which uses this template I got the Craft Exception:

  cURL error “7” encountered while attempting to download
  “http://127.0.0.1:8001/cpresources/[...]/myImage.jpg/?d=1553875482”.
  The error was: “Failed to connect to 127.0.0.1 port 8001: Connection
  refused”

But when I open the image link directly it works normally. Checked permissions many times. What can be an issue here?

Thanks


texts:
I know questions similar to this have been asked in the past. But I still don't feel like I am getting a full picture so feel there is benefit in asking it again.

I want to add extra data to a post after that post is saved. In Wordpress world this is called meta data. And can be achieved by simply calling update_post_meta($post_id, $meta_key, $meta_value);  (I'm not saying Wordpress is better I'm just giving context of where I am coming from.)

I know how to hook into the 'entries.saveEntry' event in my plugin but I am unclear where to save this extra data or how.

The extra data is not to be seen by the user and will likely be removed and updated each time the post is updated.


texts: For performance is using a macro better than using include with the 'with' statement?

texts:
Which is better for performance? Using a macro for output in a for loop or calling an include using the 'with' params to pass data? Both are loading a file. But is stacking up a bunch of code in a macro file faster than using an small include file?

{% for item in entries %}
    {% include "/components/_item" with { item: item } %}
{% endfor %}

OR

{% for item in entries %}
    {{ helpers.item(item) }}
{% endfor %}


texts: Retrieving entry just after saving it returns null

texts:
I'm having this issue where when I save an Entry and try to fetch right away I get a null.
Example:
$entry = new Entry([stuff here]);
$entry->title = 'foo';

if (!Craft::$app->elements->saveElement($entry)) {
    dd($entry->getErrors());
}

$existingEntry = Entry::find()
            ->noCache()
            ->section('handle')
            ->title('foo')
            ->one();

//null

This is just to simplify the issue I'm having.
My use case is actually a loop that checks if the entry already exists (according to the title), if so it adds data to it, if not, creates it and adds the data. What is happening is that I get multiple entries created with the same title because when I check if it exists, I get a null.
I thought it could be cache, hence the noCache() but nope.
And I can also confirm that the entry is saved/created. If I go to the dashboard I can see it there.
Clarification:
The snippet above is just to explain it in a simple way what the problem is. It's not actual code I'm using. I am aware that I do have the entry object and it doesn't make sense to fetch it right after saving it.
My question is solely about why I cannot get an entry that was previously saved. I find this behaviour weird and was not expecting it.


texts:
This probably has a very simple answer but cannot seem to get it working.

I have a 404.html template in craft/templates and it works fine within a section (such as https://shanehudson.net/articles/dfs) but not at all for non-existant pages in the root (such as https://shanehudson.net/404). Any ideas?


texts: Change author of entry within Craft Client licence

texts:
I created some sample blog posts during development, and now want to change the author of those posts to the client. Yet, only I'm listed in the dropdown box when I try and change an entry's author.

Any ideas? Besides editing it in the database.


texts: Update search index after assets.onSaveAsset Event

texts:
I use an assets.onSaveAsset Event in my plugin to update a field with the IPTC-Data of the image.

  $asset->getContent()->keywords = $this->get_iptc_keywords($imgPath);
  craft()->elements->saveElement($asset);

It updates the field values of the asset, but it does not update the search index. When i resave the asset, the searchindex table is updatet and works. Is this a craft bug and is there a craft way to update the search index for a single element (not the full index). Otherwise do i need to update the index by writing plain sql update/insert statements? Thanks for any help...


texts: Adding a mailing list subscribe to contact form

texts: Is there an existing plugin or a built-in way of adding an "add me to mailing list" button to a contact form? Not just that it gets stored in the database as a lightswitch, but so it actually subscribes them (or at least sends them a sign-up confirmation email)?


texts: Craft 3 to webserver (with only access to public_html )

texts:
I just wanted to deploy, my site live, but I was running to some issues.
I read that I should put only the web folder to public_html and all the other folders and files above that.

But on my server provider I have only access to the public_html folder itself, and I cannot go above that.

I found this guide: https://craftcms.com/guides/moving-craft-files , but when I apply this, I myself wont have access to the folder, so I cannot open the admin dashboard.

Is there a way to set an exception for myself, or I am doing something completely wrong?


texts: I'm using solspace's freeform with the mailchimp mailing list plugin. All is working OK except I don't want to see the checkbox on the form. Can this be hidden with with an 'override' in the form tag?


texts: Combined searches and filters with a Matrix

texts:
I am fairly new to Craft but have managed to build a combined search feature that users can filter from dropdowns. I used this as a guide and it works great:
https://webstoemp.com/blog/combined-searches-and-filters-craft-cms/ implemented here (still rough but working): http://resources.sttrcancer.org/resources-connect

I am now building out another search feature for an additional section ('members') but members has a MatrixBlock called ('position'), which contains a category field ('institution'). I am struggle with getting the institution list to show in my dropdown. I understand it is nested within the MatrixBlock and I am obviously missing a part of the syntax. Here is my working category dropdown that does not included the nested category:

{# get all entries to display only the categories related to entries #}
{% set memberAllEntries = craft.entries.section('member').limit(null).find() %}

{# disease categories #}
{% set memberDisease = craft.categories.group('disease').relatedTo(memberAllEntries).order('title asc').find() %}

    Disease

        {% for category in memberDisease %}

            {% set diseaseCategory = craft.request.getParam('disease') %}
            {% set diseaseActive = (diseaseCategory == category.slug) ? 'selected' : '' %}

<input type="checkbox" class="cbxDisease" value="{{ category.slug }}" {{ diseaseTypeActive }}>&nbsp;{{ category.title }}

        {% endfor %}

I think I need on additional set command before here: {% set memberDisease = craft.categories.group('disease').relatedTo(memberAllEntries).order('title asc').find() %} to first select the matrix, then the previous code should select the 'institution' field within it. I have tried everything, I would LOVE any suggestions.


texts: How to exclude child elements when looping through categories?

texts:
I've got a few categories set up with a few child categories for each. Each one has assets (PDFs) assigned to them, by going into the assets, double clicking, and setting the category field there. So for example:

Category 1
-- asset 1
- Sub Category 1
-- asset 2
-- asset 3

Category 2
-- asset 4
- Sub Category 1
-- asset 5
-- asset 6

But when I'm looping through the related assets, using:

 {% for category in craft.categories.group('categoryGroup').level(1) %}
    {% set resources = craft.assets.relatedTo(category).find() %}
      {% for resource in resources %}
        {{ resources.title }}
      {% endfor %}
 {% endfor %

I get:

Category 1
- asset 1
- asset 2
- asset 3
- Sub Category 1
-- asset 1
-- asset 2
-- asset 3

Category 2
- asset 4
- asset 5
- asset 6
- Sub Category 1
-- asset 4
-- asset 5
-- asset 6

Which logically makes sense, that it's returning all assets related to the children categories, since those are also related to the parent. But how can I exclude them from the loop, so I only get back the assets that are directly related?


texts: Solspace Calendar: Export a single event

texts:
I'm trying to add an export function to my calendar that will export a single event.

When I use the example code, it exports my entire calendar.

I tried passing a single event using this code:

{% set events = craft.calendar.event(craft.request.getSegment(3), ({
    loadOccurrences: false
})) %}

{{ craft.calendar.export(events) }}

and I get this error:

  Argument 1 passed to Calendar\Library\Export\AbstractExportCalendar::__construct() must be an instance of Calendar\Library\Events\EventList, instance of Calendar\Library\Events\Event given, called in /craft/plugins/calendar/variables/CalendarVariable.php on line 128 and defined

Is there a way to export only individual events?


texts: I am using XAMPP with Craft CMS 3. I am doing the tutorial with craftquest. I have moved the stylesheets folder into my web folder but craft cant seem to find my folder? How do i make craft find the stylesheets folder?


texts: Can you get the baseUrl for site by handle or id?

texts:
I am making a super simple language switcher. And I was wondering if there is a way to get the baseUrl for a site by id or handle, something like this:

DEDeutsch

What I'm trying to avoid doing is:

DEDeutsch

Or is that just how to you do?


texts: Build a language switcher for a one page website?

texts:
I'm building a site with two languages, and I need a language switcher so wherever you enter the website you can switch the language easily. The website is a onepager, so i can't direct to a specific language URL. Instead i'm thinking of adding a segment (/de /fr) to the URL.

I don't know how to display the language fields and language globals.


texts: Subdomain database configuration picking up root domain config

texts:
So I have this example database config setup

$customDbConfig = array(

    '*' => array(
        'tablePrefix' => 'craft',
    ),

    'test1.foo.com' => array(
        'server' => 'localhost',
        'user' => 'test1user',
        'password' => '',
        'database' => '',
    ),

    'test2.foo.com' => array(
        'server' => 'localhost',
        'user' => 'test2user',
        'password' => '',
        'database' => '',
    ),

    'foo.com' => array(
        'server' => 'localhost',
        'user' => 'produser',
        'password' => '',
        'database' => '',
    ),

);

It appears that when accessing test1.foo.com, the foo.com environment is being loaded.

Looking at the docs again

  When Craft is comparing your config keys with $_SERVER['SERVER_NAME'],
  it’s only looking for a partial match. So the environment key
  'example.com' will also work if you’re accessing your site via
  www.example.com or any other subdomain. You could even just use the
  TLD if you’re feeling adventurous:

What's the best way to get around this issue, where we want subdomains for dev and test, when they are subdomains of the production domain.

Thanks.