Will craft attempt to reconnect to MySQL if the connection drops?

If a MySQL connection drops in the middle of a request, then that will either cause a PHP fatal error (that will end the request entirely) or cause an exception to be thrown.

If the exception isn't handled, then the request will end as well.  If it is caught, it can be gracefully handled and the request can continue. The remaining part of the request might attempt a new database connection, but it will not attempt to re-execute the SQL on the previously dropped MySQL connection. It has moved on.


Using ADLDAP plugin in Craft 2.6 - can't bind to LDAP

In more testing, I was able to eliminate the "Can't bind to LDAP server!" error message from Craft by removing both: Account Suffix and Admin Account Suffix settings from the ADLDAP parameter control panel.
In my particular setup, I left all parameters empty in the 'optional' section of the parameter control panel, with the exception of the port ('389') and 'Follow Referrals.'


Why is the Algolia index population process with Search Plus timing out?

Trying to get property of non-object on line 519 of /craft/plugins/searchplus/services/SearchPlus_AlgoliaService.php

That sounds suspiciously like a bug in the plugin to me.  I'd recommend contacting the plugin's author and reporting it to them for further debugging:

https://transition.topshelfcraft.com/software/craft/searchplus/faq/how-can-i-get-support


Unable to set planAmount for Charge 2 - Stripe

Developer of Charge here.

This error is because you're passing an invalid currency code.

You're passing aus as the planCurrency, but need to be passing aud for Australian Dollars.

Under the hood, Charge is seeing that currency code as invalid, and unsetting the amount from the request, which is why that error is showing up on the planAmount.

(Charge unsets the amount as a safety mechanism to prevent the request falling back and processing in the default currency)

I'll update the language of the error to make it clearer the currency code is the invalid value in an upcoming release.


User registration: How do implement "Confirm password" and "Confirm email"?

If anyone is interested in confirming passwords still, I have wrote a plugin which does just this, it doesn't rely on it's own controller either so there is no bypassing of Crafts own workings :)

https://github.com/alecritson/Craft-Password-Confirm

All you need to do is add a passwordConfirm field to your existing form:

<input type="password" name="passwordConfirm">
{% if account is defined %}
  {{ account.getErrors('passwordConfirm') }}
{% endif %}

It doesn't confirm emails though..sorry


Save a selected category for a user (using a plugin)

I had to do something similar to this in a plugin recently, Inserting Relationship Into Entries Field - Plugin Not Saving Relation, I know it's users to an entry field but I would assume the methods are similar.

So you will need 3 things in order to save a users categories

1. The Craft\FieldModel of the field which has the associations

$field = craft()->fields->getFieldByHandle('propertyPreference');

2. The source, in this case the matrix block that has the field

$source = craft()->matrix->getBlockById(<someId>);

3. An array of element id's you wish to relate to the field

$relations = $user->propertyPreference->ids();

Once you have those you can edit the $relations array however you see fit and then simply save the relations back

craft()->relations->saveRelations($field , $source, $relations);

You can find out more about the save relations function in the class reference

As for which table, I would assume they are in craft_relations


Has anyone come up with a solution where matrix blocks can be scheduled and expire?

Yes you can definitely do this. The huge advantage of Craft is it's ability to customize nearly everything.

You can create a date field in your matrix block and check if the current date {{ now|date }} is lower than the date specified in the field.

If the condition is true, you'll display the matrix block if not you can either just hide it or you could create a plugin with a template variable  to delete the block.

craft()->matrix->deleteBlockType($yourBlock);


Pass Craft Field String to Javascript Function

Craft 3

According to the craft 3 js docs

We'll need to adjust some things as follows:

Twig

We no longer need to tell craft which File we're editing as it
now simply inserts a <script> tag with the contents at the end of the <body> tag. (Can be adjusted, see position docs.)

{% js %}
// define our vars
var dziFilesUrl = "http://localhost:3000/openseadragon/highres/{{ entry.kelimImageData }}/";
var dziData = "{{ entry.kelimImageData }}";
//Call our function
tileSourceFromData(dziData, dziFilesUrl);
{% endjs %}

JS

Remove the dziFilesUrl declaration from openseadragon-custom-dzi.js & and other files you declare this variable in.

And that about sums it up, if any error does occur, please inform me of whatever error your browser console spews out or otherwise any error craft presents.

Craft 2

I'm gonna guess that you're using craft cms v2 as I only found includeJS in the craft 2 docs.

Adjust your twig as follows:

{%includeJsFile "" %}

{% set myJs %}
  // here you're setting the vars which use the twig variables for them to be available later on in the JS
  var dziFilesUrl = "http://localhost:3000/openseadragon/highres/{{ entry.kelimImageData }}/";
  var dziData = "{{ entry.kelimImageData }}";

  // you could even still call your `tileSourceFromData` function here
  tileSourceFromData(dziData, dziFilesUrl);
{% endset %}

{% includeJs myJs %}`

And then remove the setting of those vars in your openseadragon-custom-dzi.js.

This should:

Set the vars with the backend data in the Footer (see docs)
Call the tileSources function in the footer as you did before.
Allow you to use the dziFilesUrl and the dziData variables anywhere else in your JS with the backend data as their values.

Beware: This JS is getting executed in the footer according to the docs so you need to either start your function call from within the twig myJs or when the full page is loaded, otherwise you'll run into undefined variables.

Sidenote: you were calling your tileSourceFromData function in the twig with only one arg, instead of the required two before, this is also adjusted in my answer.


Config for devMode not showing when true

The solution was ENVIRONMENT="local" in .env
via andrew.welch


DB back-up gives syntax errors on import in new DB

As Brad replied as a comment, the issue was indeed PhPMyAdmin. Using NaviCat or updating my PhPMyAdmin resolved the issue.

Answer points go to Brad!


Craft Commerce: Custom Rounding (for taxes and discounts)

The rounding you are talking about is for cash. The rounding is to nearest 5c because it is likely the smallest denomination in circulation.

Online, with electronic transactions, the base will always be whole cents (or localised equivalent.) Credit Card and electronic purchases can always transaction in these minor units.

Craft Commerce doesn't have the ability to round to cash-based values (likely to be used in POS), but you are welcome to make a feature request here: http://feedback.craftcms.com/


Change date language in a client version of craft

Found the solution in the twig docs, this appears to work:

{{ entry.postDate|date("F") }}

This uses the local date setup instead of the US setup

Still odd, that the standard language from the CP is not used?


Is it possible to target a fieldtype by it's Type name, rather than the handle name?

I am not sure if I am understanding your question correctly, so here is my understanding before I give my solution:

You want to be able to access a field on an asset by it's field type rather than it's handle.

Given this understanding, here is my solution:

I have not been able to accomplish this using Craft relations. However, you can loop through the fields attached to the asset, and check their type. It is a little bit confusing as Craft stores the data for fields and field layouts across several tables.

An element has a field layout (FieldLayoutModel), and the layout then has fields (FieldLayoutFieldModels). Then each of those FieldLayoutFieldModels has fields (FieldModel) which are the actual fields we are looking for. Putting this together, we can loop through and check the field type like so:

    // get the fieldLayoutModel
    $fieldLayoutModel = $image->fieldLayout;

    // get array of FieldLayoutFieldModel
    $fieldLayoutFields = $fieldLayoutModel->fields;

    foreach($fieldLayoutFields as $fieldLayoutField){

        // get the field associated with the layout
        $field = $fieldLayoutField->field;
        if($field->type == 'myFieldType'){
            // do whatever
            break;
        }
    }

Hopefully this is what you were looking for!


Use Asset field as a Global Set Variable?

If companyInfo if your global and logo if your Asset field, then you'd use it just like you would anywhere else keeping in mind that all relation fields (Assets, Users, Entries, Tags, Categories, etc.) always return a collection of results.

So, companyInfo.logo.first() will return the first asset and if you want to loop through them all:

{% for image in companyInfo.logo %}
    {{ image.getUrl() }}<br />
{% endfor %}


Is it possible to add to cart with a radio input rather than a select?

The name for your input needs to be purchasableId:

{% for digitalProduct in entry.exampleProducts.all() %}

      <input
        type="radio"
        name="purchasableId"
        value="{{digitalProduct.purchasableId}}" />

{% endfor %}


Download images uploaded in backend with Sprout Form Plugin

Here's a plugin that will add Download (well, open in new tab) links to files in the Assets fields when editing entries.

AssetLinks


Your script probably chokes because you're interacting with an undeclared variable $params – i.e. change

if($params['isNewEntry']) {

to

if($event->params['isNewEntry']) {


No template found when accessing action method per route

I ended up using Jon's function renderPluginTemplate I found at https://craftcms.stackexchange.com/a/7132/6062 which basically implements what's written here: https://craftcms.com/docs/plugins/templates#plugin-template-paths-explained

I wonder why there is no easier function included into craft by default.


You'd need to write a super-simple plugin that exposes a controller's action URL your deploy hook could hit.  That action would basically just mimic what the ClearCachesTool does for clearing the various caches in Craft.

E.g. Template caches, Asset Transform Index caches, Asset Index caches, general data caches, etc.


User make assets subfolder in the frontend

No idea if it lets users create subfolders on the front-end, but this is the closest plugin I could find: https://straightupcraft.com/craft-plugins/assets-browser

If that doesn't do it, most likely you'd need to do some custom plugin work to do what you're looking for.


There are two main approaches in general to updating your page in response to changes in the cart.

The first is just an ajax load in of a partial template.

This is really just as simple as something like:

$cart.load("/_ajax-injects/cart.html").fadeIn('fast');

....which (assuming $cart points at a div holding your displayed cart) - would load in over the old cart a new cart (assuming templates/_ajax-injects/cart.html has such a partial template in it)

This is very easy to implement, but does not look wonderfully finessed as there will be a visible result of replacing a large section of the page at one go.

The second approach is using the json response.cart object to update just the appropriate fields within your already displayed cart.

This is considerably trickier.  Each of the fields, such as your item quantities, subtotals, tax, shipping etc must have an identifying class or id on them, and then you parse through the response.cart object grabbing the appropriate values from that and inserting them into those fields.  You also need to deal with e.g. removing lineItem rows if the qty is zero and so forth.

A lot more work, however once implemented this is a visually much more finessed approach as just the fields that need updating get updated.


How do you not output table field if there are no values?

When you define a table field, it comes with one row by default. I'm not sure why this is. You can remove this row by clicking on the - icon:

To filter out those rows in twig, try:

{% for row in entry.discography if row.releaseName %}


Craft 3: Image transformation - grayscale

Craft 3 currently doesn't have image filter support, but it is on the list and you can track the Github issue here: https://github.com/craftcms/cms/issues/1492


You'll need to save the new user before you can activate them. This code should do the trick:

if (craft()->users->saveUser($newUser)) {
    craft()->users->activateUser($newUser);
}


From my experience, I try to strip out as much formatting options as I can from any wysiwyg editor. Otherwise you'll end up with large, purple text with a red background (or some other crazy style the client thinks looks good).

I understand the client wants to construct a table - then alter the table along with the graphics etc.

What if...

Create a matrix field, then within that have a block for the rich text area, then another block that is of type table? I'm not 100% on what capabilities that the table field type has. That should allow them to create the table and work with it.

I would then have some sort of pre-defined css that took over for them, rather than giving the client free reign on the design.


How do you create two grid columns like the Entry Edit page within a plugin?

templates/layouts/_cp.html has

nested inside the {% block main %} (line  207) and templates/entries/_edit.html is overriding that block main, so those grid,item,pane divs get overridden too.


How to get a Super Table relation in PHP?

$element = Craft::$app->getUser()->getIdentity()->priceTable->relatedTo([
    'targetElement' => $product->id,
    'field' => 'product'
])->one()

But to be honest your code in Twig should not work as expected since you only grab the query and modify it. Your output is your search criteria, not the value of an element.


Stub out the global craft() object for PHPUnit tests

Whew...this seems to do the trick!
Hopefully this is an appropriate way to handle things.

I created a new Craft class file in the 'tests' dir.  There I can stub out any \Craft\craft() methods the class under test depends on.

stub class \tests\Craft

<?php

class Craft {

    public function __construct()
    {
    }

    public function jobs()
    {
        return 'xxx';
    }
    public function getJobs()
    {
        return 'xxx';
    }

    public function craft()
    {
        return $this;
    }
}

in the test class

<?php

namespace Craft;

require_once '/www/craftcms/plugins/jobs/variables/JobsVariable.php';
require_once '/www/craftcms/tests/Craft.php';

class JobsVariableTest extends \PHPUnit_Framework_TestCase
{

    public function testJobs()
    {
        $jobs = new \Craft\JobsVariable();
        $this->assertEquals('xxx', $jobs->jobs());

    }
}
function craft()
{
    return new \Craft;
}

allows me to test this function...

public function jobs()
{
    return craft()->jobs();
}


Content Modeling for Site Architecture Recommendations

It sounds like you have 3 different general buckets of entries to consider:

Streams of similar entries (News section, blogs, etc.)
General content pages (100+ of them)
Unique/one-off pages (Contact Us, application forms, etc.)

Streams

First, the easy ones: the streams of similar content (news, blogs, etc.) should each get their own Channel sections. A News channel, Bill’s Blog, Sally’s Blog, etc.

General content pages

For the 100+ general pages, I think putting them all in a single “Pages” section makes sense. Find out what different types of pages there will be, and give the section different Entry Types based on those, so authors have the flexibility of choosing what type of page they want to create.

URL format-wise, you can either require that these entries follow a particular slug-based URL format (e.g. every page will have a url such as http://example.com/some-slug), or give them a custom “Page URL” field where authors can choose what the entry URL would be. For the former, the section’s Entry URL Format setting would get set to {slug}; for the latter, it would be {pageUrlFieldHandle}.

As for the type of section Pages should be (a Structure or a Channel), here’s a good rule of thumb: Do you want all of the pages in this section to be shown in the navigation, or just certain ones? If you want them all in the nav, then use a Structure, and use the built-in Structure View on the Entries index to sort out the navigation. Otherwise make it a Channel, and manage the navigation separately (a&m nav and Craft Nav are your two navigation options at the moment).

Unique pages

Finally, the unique pages like Contact Us and application forms. If you have any pages that are truly unique, which you would never conceive needing two of (e.g. a Contact Us page that has a bunch of custom fields that really only apply to that specific page), create Single sections for those pages. Otherwise you may just prefer to lump these in with the Pages section, with the help of a new entry type(s) (e.g. “Application Form”).


This is a bug that's been fixed in the next (post 2.3.2635) release of Craft.


Here's the approach that work for me. Using Infinite Scroll jQuery plugin.

In the header, I'm checking whether this is AJAX request or not and use different layout based on that. This is optional though.

{% if craft.request.isAjax %}
{% set layout = "_ajaxLayout" %}
  {% else %}
{% set layout = "_layout" %}
  {% endif %}

{% extends layout %}

In the content area, I have:

{% paginate craft.entries.section('news').limit(3) as entriesOnPage %}
    {% for entry in entriesOnPage %}

{{ entry.title }}

{{ entry.postDate|date("M d, Y") }}

                {{ entry.body }}

    {% endfor %}

    {% if paginate.nextUrl %}

        Next Page

    {% endif %}

{% endpaginate %}

Then, somewhere in the footer (note the If, I put it to make sure the infinite scroll fors only on first page)

{% if craft.request.pageNum==1 %}

{% paginate craft.entries.section('news').limit(3) as entriesOnPage %}
{% if paginate.nextUrl %}

{% endif %}
{% endpaginate %}

{% endif %}


Filtering entries by multiple URL parameters on the front end

You need to get each parameter from the URL separately and repeat the steps you already did for "collection":

Get search parameters from the URL query string
Find categories that match the slugs in your query string
And merge them into the relationParam array.


Target a certain entry type on the entries fieldtype

This is not possible by default in Craft. Check out the Entries Subset plugin, though, I think it can do what you want.


Updating all entries URIs after changing entry URL format

The entries won't immediately get updated, as it could take a little while to go through all of them, but you should see a little progress bar in your CP header immediately after updating your section's settings, and if you click on it, it will give you more details -- saying that a "Resave Elements" background task is running. Once that has completed, your entries will have new URLs.

In my case, it was not working as indented with localised entries but thankfully that was fixed on build 2562.


Try setting 'usePathInfo' => true and 'omitScriptNameInUrls' => true in your craft/config/general.php file.


How do you programatically add a user to a user entry field

You will need a custom plugin to do this.

I'll assume that you're familiar with that process.

You can build a form in your template like this, passing in the entry ID you want to add the user to and the user ID you want to add.

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="myPlugin/save">
    <input type="hidden" name="redirect" value="/success">

    <input type="hidden" name="elementId" value="{{ entry.id }}">

    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    <button type="submit" >Submit</button>
</form>

Then, you'll need a controller action in your plugin to which you submit a POST request from a form.

public function actionSave()
{
    $this->requirePostRequest();

    // get all the post variables
    $elementId = craft()->request->getPost('elementId');
    $userId = craft()->request->getPost('userId');

    // set the name of the field you want to update
    $fieldHandle = 'myUserField';

    // based on the element and field vars, get the models for each
    // using the elements and fields services
    $element = craft()->elements->getElementById($elementId);
    $field = craft()->fields->getFieldByHandle($fieldHandle);

    // store the current ids into a variable
    $currentIds = $element->{$field->handle}->ids();

    // merge the new id into the current ids
    $newIds = array_merge($currentIds, (array) $userId);

    // save the new array of ids, using the relations service
    craft()->relations->saveRelations($field, $element, $newIds);

    // redirect to the redirect url
    $this->redirectToPostedUrl();

}

EDIT:

It's very important that you follow the naming conventions in the docs.

You controller class should be named MyPluginController, which would then make the action in the form myPlugin/save (controller and action get removed from the exposed plugin and action names).

Also the redirect should be a page on the side where you want the user to go after being added, not pointing to your plugin.


Twig combined conditionals to set variable

It's probably better if you set variables to reference, so your if statements make more sense.

{% set asset = story.storyImage.first() %}
{% set videoUrl = story.videoStoryUrl %}
{% set icon = "text" %}

{% if asset | length %}
    {% if videoUrl is empty %}
        {% set icon = "video" %}
     {% else %}
        {% set icon = "image" %}
    {% endif %}
{% endif %}

{{ icon }}


The good news is, 2.4 isn't that old. The bad news is, 2.5 was one of the most significant updates Craft has ever seen. For that reason, you'll want to exercise a little more caution than you typically would need to.

To begin with, backup your database! I can't emphasize this enough... you want to make sure that you have captured a "moment in time" for your site to roll back to, in the unlikely event that it's necessary.

After that, you'll want to perform a manual update. The vast majority of times (99%), an auto-update is a clean and easy way to update your Craft site. In fact, it's one of the things that makes Craft so amazing to begin with! However, upgrading from 2.4 -> 2.5 involves a lot of file changes, so this is one of those rare instances where you'd be wise to upgrade manually.

Lastly, you'll want to update all of your plugins after you update Craft itself. The arrival of 2.5 brought a few breaking changes for some plugins, and several awesome new features for plugins to take advantage of. Besides, it's always best to be running the latest versions of your plugins anyway. :)

In short, set aside 1-2 hours. If you're cautious and follow these tips, you'll almost certainly have a smooth transition. And if something goes horribly wrong, just roll back to your backup, and reach out to the community on the Craft Slack channel.

Good luck!


How do I check if a lightswitch field is false?

You have to use 'not 1' instead of '0':

{% set resources = craft.entries.relatedTo({ targetElement: category }).order('title').archivedResource('not 1') %}


What's the best way to create a multiple account architecture?

Not exactly the fine control you're looking for, or ideal by any means, but one direction might be to create an "Account" channel with a related user field for 'User' (required; limit to 1; from userGroup 'Regular User') — or vice-versa (related "Account" entry in "Users").

You can then restrict your Account Admins to only edit 'Accounts' (and Products) entries that belong to them, with all the custom fields that are required.

The problem here is that you wouldn't also want the Account Admin to be able to edit or assign permissions to users (thus defeating the purpose). And there is no way to automatically assign a new user (created through the CP) to a userGroup (as far as I know). Users can however automatically be assigned through the front-end through "allow public registration" and "default user group" settings. So, an Account Admin could technically create a new user through the front-end. And then (back in the CP) create a new 'Account' entry, and relate that account to the user they just created.

They would still require an admin to edit or delete the user, but maybe that's ok.

You would also need checks in place to ensure that only one account was assigned to any one user, somehow. If you reverse the relationship (i.e. related 'Account' entries field in 'Users'; limit 1), then you could ensure the 1-to-1, but this would require an admin to relate the two together.

Admins, of course, could do all of this through the CP and assign the "Account" to the Account Admin, by just setting the author.

Not ideal of course, but perhaps a step in the right direction.


How to set a URL for the top level of a Structure section?

If I understand what you're asking—it sounds like you can just disable URLs for that section, and create a template that will get loaded at the URL you want.

For example, if you had a Section called “Plants,” and you wanted to list all plants at mywebsite.com/plants, you could just create craft/templates/plants.twig:

{% set plants = craft.entries({ section: 'plants', limit: null }).find %}

  {% for plant in plants %}

{{ plant.title }}

  {% endear %}

If you need to edit anything on that page, you'll need to create another entry (probably a Single) to manage that content.


Does the cache tag behave differently for Mobile vs Tablet vs Desktop?

Craft makes no distinction whether it's caching for mobile, tablet, desktop, etc., so it'll need to be taken care of on the template end.

You can easily do that with the "using key" parameter of the {% cache %} tag, though.

{% if craft.request.isMobileBrowser %}
    {% set cacheKeyType = 'mobile' %}
{% else %}
    {% set cacheKeyType = 'desktop' %}
{% endif %}

{% cache using key "page-header-" ~ cacheKeyType %}
    ....
{% endcache %}


There is a currentUser global variable that is available to all Twig templates.

If there is a currently logged in user, it will return that user's UserModel class.

From there, it's just a matter of:

{% if currentUser %}
    form=http://formsite.com/formname?email={{ currentUser.email }}
{% endif %}

Of course, what's inside the if block will look different depending on how you're generating the embedded code URL.


How to suppress display of expired entries in Solspace month calendar?

The solution is to wrap the event output in a conditional that compares the event startdate to now. I've updated the question to reflect this.


So it sounds to me like either the plugin isn't installed (which doesn't make a ton of sense, because you'd be getting other errors, too), or if it is installed, pieces of it are missing.

extractSummary is a Twig filter/function and has been available since the start; I'd try making sure there's nothing wrong with your install/deploy, or try re-downloading a fresh copy of the SEOmatic plugin.


Element API: Entry field inside a Channel entry being passed into JSON file

I figured it out. Turned out I had entered the criteria incorrectly, as channel instead of section.

'criteria' => ['section' => 'movies'],

not

'criteria' => ['channel' => 'movies'],


List Categories AND their associated entries

Something along the line of this should do that:

    {% for category in craft.categories.group('categoryGroupHandle') %}

        {{ category.title }}
        {% for entry in craft.entries.section('sectionHandle').relatedTo(category) %}
            {% if loop.first %}
{% endif %}

{{ entry.title }}

            {% if loop.last %}
{% endif %}
        {% endfor %}

    {% endfor %}

Probably some bugs in here, but should be enough to get you started.

Also probably smart to wrap this in {% cache %} tags, as it probably will trigger a lot of database queries.


How call PHP native function in Model/Service/Controller scope

You need to backslash the class to tell it to look in the global namespace like so:

public function validateVatNumber()
{
    $client = new \SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
}

You can read on the basics of PHP namespacing here: http://php.net/manual/en/language.namespaces.basics.php


Previous and next entries nav – within a categeory

When you are within your nav tag context, category definitely exists, even if you're using include for the first snippet you posted. If you're talking about the automatically pre-assigned variable for a single category's page, make sure the category group settings are still correct and that you are requesting the right URLs.


Customizing Stripe payment form for Craft Commerce 2

The following code allows the customisation of the fields using Stripe Elements. This code will replace the payment form with gateway.getPaymentFormHtml({}).

The thing to note here is this is provided unsupported as it is custom code and does not use the payment form template or javascript file that is in the Commerce Stripe plugin. This also means that it will not benefit from any updates to the plugin that change those files.

{% set cart = craft.commerce.carts.cart %}
{% set gateway = cart.gateway %}
{% set scenario = 'payment' %}
{% set billingAddress = cart.billingAddress ?? null %}

<form method="POST" id="payment-form">
  <input type="hidden" name="action" value="commerce/payments/pay"/>
  {{ redirectInput('/shop/customer/order?number='~cart.number) }}
  <input type="hidden" name="cancelUrl" value="{{ '/shop/checkout/payment'|hash }}"/>
  <input type="hidden" name="orderEmail" value="{{ cart.email }}"/>
  <input type="hidden" name="gatewayId" value="{{ cart.gatewayId }}"/>
  {{ csrfInput() }}

      <input type="text"
             name='firstName'
             maxlength="70"
             placeholder="{{'First Name'|t('commerce')}}"
             autocomplete="false"
             class="card-holder-first-name{{(paymentForm is defined and paymentForm.getErrors('firstName') ? ' error')}}"
             value="{{paymentForm is defined and paymentForm ? paymentForm.firstName : ''}}"
      >
      <input type="text"
             name="lastName"
             maxlength=70",
             placeholder="{{'Last Name'|t('commerce')}}"
             autocomplete="false"
             class="card-holder-last-name{{ (paymentForm is defined and paymentForm.getErrors('lastName') ? ' error') }}"
             value="{{paymentForm is defined and paymentForm ? paymentForm.lastName : ''}}"
      >

    {% set errors = paymentForm is defined and paymentForm ? paymentForm.getErrors() : [] %}
    {% if errors|length %}

        {% for error in errors %}

{{ error|join('
')|raw }}

        {% endfor %}

    {% endif %}

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

{% do view.registerJsFile('https://js.stripe.com/v3/') %}
{% js %}
// Create a Stripe client.
var stripe = Stripe('{{ gateway.publishableKey ?? '' }}');

  // Create an instance of Elements.
  var elements = stripe.elements();

  // Custom styling can be passed to options when creating an Element.
  // (Note that this demo uses a wider set of styles than the guide below.)
  var style = {
    base: {
      color: '#000000',
      fontSize: '16px',
      '::placeholder': {
        color: '#CCCCCC'
      }
    },
    invalid: {
      color: '#fa755a',
      iconColor: '#fa755a'
    }
  };

  var classes = {
    base: 'StripeElement',
    complete: 'StripeElement--complete',
    empty: 'StripeElement--empty',
    focus: 'StripeElement--focus',
    invalid: 'StripeElement--invalid',
    webkitAutoFill: 'StripeElement--webkit-autofill'
  };

  var card = elements.create('cardNumber', {
    style: style,
    classes: classes
  });
  card.mount('#card-number');

  var expiry = elements.create('cardExpiry', {
    style: style,
    classes: classes
  });
  expiry.mount('#card-expiry');

  var cvc = elements.create('cardCvc', {
    style: style,
    classes: classes
  });
  cvc.mount('#card-cvc');

  // Handle real-time validation errors from the card Element.
  function cardErrors(event) {
    var displayError = document.getElementById('card-errors');
    if (event.error) {
      displayError.textContent = event.error.message;
    } else {
      displayError.textContent = '';
    }
  };

  card.addEventListener('change', cardErrors);
  expiry.addEventListener('change', cardErrors);
  cvc.addEventListener('change', cardErrors);

  // Handle form submission.
  var form = document.getElementById('payment-form');
  form.addEventListener('submit', function(event) {
    event.preventDefault();
    var firstName = document.querySelector('.card-holder-first-name');
    var lastName = document.querySelector('.card-holder-last-name');

    var paymentData = {
      billing_details: {
        name: firstName.value + ' ' + lastName.value,
        email: '{{ cart.email }}',
        address: {
          line1: '{{ billingAddress.address1 ?? '' }}',
          city: '{{ billingAddress.city ?? '' }}',
          state: '{{ billingAddress.state ?? '' }}',
          postal_code: '{{ billingAddress.zipCode ?? '' }}',
          country: '{{ billingAddress.country.iso ?? '' }}'
        }
      }
    };

    stripe.createPaymentMethod('card', card, paymentData).then(function(result) {
      if (result.error) {
      // Inform the user if there was an error.
      var errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;
      } else {
          var form = document.getElementById('payment-form');
          var hiddenInput = document.createElement('input');
          hiddenInput.setAttribute('type', 'hidden');
          hiddenInput.setAttribute('name', 'paymentMethodId');
          hiddenInput.setAttribute('value', result.paymentMethod.id);
          form.appendChild(hiddenInput);

          // Submit the form
          form.submit();
      }
    });
  });

{% endjs %}


Revolution Slider and Craft CMS conflict on placeholders

You can stop Craft from parsing curly brace tags in your template code by using the Twig Verbatim tag. Here's an example:

{% verbatim %}{{ this.wont.be.touched }}{% endverbatim %}

You can use it to stop a single tag from being parsed, or encapulate an entire block of code on your page for multiple tags. Useful for languages like AngularJS that use the same double curly brace format.

More info at http://twig.sensiolabs.org/doc/tags/verbatim.html


Is there a very very basic example of simply outputting PHP with a plugin to Twig?

Have a look at plugin template variables. You can simply create a method in your plugins variable file that returns anything you want to the template, which would be accessible via {{ craft.myplugin.customVariable }}.

<?php
namespace Craft;

class MypluginVariable
{
    public function customVariable($someProperty = 'defaultValueIfNotDefined')
    {
        return 'Whatever you want!';
    };
}


This is exactly what caching is supposed to do... flatten the Twig code down to basic HTML, and serve that up instead of dynamically rendering it. Using globally means that the HTML would be identical on every page, which is not really what you want here.

Get rid of globally, so it can cache separately for each page. Since the URL is supposed to affect how that snippet is rendered, you don't want to cache globally.


Avoid saving $_POST in Craft logs for certain URLs

As Oli commented, those will only be logged if devMode is enabled, which should never be the case in production.

Outside of that, Craft does have a sensitiveKeywords propery in the Security class: https://github.com/craftcms/cms/blob/develop/src/services/Security.php#L29 that defaults to these keywords: https://github.com/craftcms/cms/blob/develop/src/services/Security.php#L29 and will redact those from places like log files.

If you need to modify that list, you can do so from by extending the application config like so:

<?php
return [
    'components' => [
        'security' => [
            'class' => craft\services\Security::class,
            'sensitiveKeywords' => [
                'key1',
                'key2',
            ],
        ],
    ],
];


Why is /blog not displaying /blog/index.html?

Check for a blog.html file in the root of templates, craft would go to that first then check for a subfolder.

You can read more about the process that Craft follows when deciding how to handle a request.


Loop through assets field on detail/product page

product.gallery returns an ElementCriteriaModel, which you can think of as a list of elements. product.gallery.first() will return the first element in this list.

What you want is to loop over all the elements:

{% for asset in product.gallery %}
  <img src="{{ asset.url }}">
{% endfor %}

(Note that this will work if there are no elements in the list (because the for loop will never be entered). One thing you should avoid doing is product.gallery.first().url, because it is never possible to be certain without checking that there is a first element in the list.)


Can I call a dynamically named variable through twig?

Unless I'm misunderstanding, the title of your question is a bit misleading as you're not trying to call a Craft function in Twig, you're trying to output a dynamically named variable (a variable variable).

You can generally do that using the array syntax: e.g. categories[catOption].


I'm not seeing any obvious ways to access groups directly in Twig. There may be a more direct way, idk — but this should work.

{% set categoryGroupNames = [] %}
{% for category in craft.categories %}
    {% set groupName = category.getGroup.name %}
    {% if groupName not in categoryGroupNames %}
        {% set categoryGroupNames = categoryGroupNames|merge([groupName]) %}
    {% endif %}
{% endfor %}

{% for groupName in categoryGroupNames %}
    {{ groupName }}
{% endfor %}


How do I fix PHP Notice - Undefined index: releaseDate?

I've run into this issue myself with Craft version: 2.6.2962.

The line in question is expecting a column from the database called "releaseDate".
In my case, that column no longer exists. It might have gotten dropped or lost with one of the updates, I am not sure.

A short-term solution would be to edit that line of code and pass in some different value.

In my case, I changed the line to:

$row['releaseDate'] = DateTime::createFromString($row['dateUpdated'], null, false);

And to clarify, looking at the changelog, it seems they are in the process of tweaking the craft()->releaseDate() function call.

Update 03/06/2017:
It appears that my code-base was outdated with the version in my database. I updated to the latest version of craft and that line that I edited above is now gone.

My question to you: Is your craft version up to date?


User activation email markdown not (correctly) parsed, no link etc

Ok, i found the Email "Message" settings where the wrong markers where ("craft_link" instead of "link" etc.) located.


Converting existing content to a different locale

Currently it's not possible to edit a locale from the CP, which means you have to edit it directly in your db.

Edit locale:

UPDATE craft_locales SET locale = 'en' WHERE locale = 'en_us';

Edit elements:

Each element (entries, assets, users, etc.) which can be translated has a locale-column:

UPDATE craft_categorygroups_i18n SET locale = 'en' WHERE locale = 'en_us';
UPDATE craft_content             SET locale = 'en' WHERE locale = 'en_us';
UPDATE craft_elements_i18n       SET locale = 'en' WHERE locale = 'en_us';
UPDATE craft_entryversions       SET locale = 'en' WHERE locale = 'en_us';
UPDATE craft_sections_i18n       SET locale = 'en' WHERE locale = 'en_us';

Edit permissions:

UPDATE craft_userpermissions SET name = 'editlocale:en' WHERE name = 'editlocale:en_us';

Check:

To be sure you've got them all do a sql search for en_us.


How do I group matrix blocks into batches of 4?

You could use your own variable to count the matrix blocks in your loop. The code could look like this:

{% set rows = 0 %}

    {% for event in events %} {# loop through all events #}
        {% if event.startDate|date('Y') == now|date('Y') %} {#check to see if the event's start date is happening this year #}
            {% for row in event.authors %}
                    {% for block in row %}
                        {% switch block.type %}
                            {% case "author" %}

                                {% if rows == 4 %}

                                    {% set rows = 0 %}
                                {% endif %}

                                    {% set image = block.image.first() %}
                                        {% if image|length %}

                                         {% endif %}

{{ block.authorName }}

                                    {% if block.twitterHandle|length %}

@{{ block.twitterHandle }}

                                    {% endif %}
                                     {{ event.startDate|date('m/d/y') }} @ {{ event.startDate|date('g:ia') }}

{{ block.bio }}

                               {% set rows = rows + 1 %}

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

It's important to set the variable outside the for loop, otherwise it does not work.


Creating an onSaveEntry event in Guest Entries Plugin

It probably would be better to just write your own plugin to do this, so that you don't have to worry about patching in your changes every time the guestEntries plugin is updated — and it could technically be just one file, although the recommended craft method would be to create a service method to handle the events.

In your plugins main class file, just create an init method that listens for the entries.saveEntry event for the section in question:

public function init()
{
    parent::init();

    craft()->on('entries.saveEntry', function(Event $event)
    {
        $entry = $event->params['entry'];
        if ($entry->section == 'MySection')
        {
            if ($event->params['isNewEntry'])
            {
                craft()->myplugin->handleNewSectionEntry($entry);
                // or do something directly
            }
            else
            {
                craft()->myplugin->handleUpdateSectionEntry($entry);
                // or do something directly
            }
        }
    }); // edited
}

If you need to test whether it is a 'guest' entry from the front-end vs the CP you can add:

if (!$currentUser) { ... }


If you really, really want to create an entry from within the database (you must have a VERY good reason to do so), then you should create a row in:

entries
elements
elements_sites
content

If you'd like the easier path, use Content migrations. Create a migration, and then add something like:

// Create the entry
$myNewEntry = new craft\elements\Entry();
$myNewEntry->setFieldValues([
    'title' => 'My new entry',
    'myCustomFieldHandle' => 'Look, I can even set a custom field!',
    'myCustomCategoryFieldHandle' => [$categoryILookedUp->id],
]);

// Save the entry. Everything else will be handled for you by Craft's API.
Craft::$app->getElements()->saveElement($myNewEntry);


Unable able to update Freeform Pro from 2.2 to 2.5

Solution: Instead of using the Craft updater, execute a composer require composer require solspace/craft3-freeform-pro


Extend order methods to sort numbers naturally

It's possible to pass MySQL functions to the order parameter. Using the MySQL LENGTH function, I believe the following should do the trick (assuming your "model number" field's handle is modelNumber):

{% set entries = craft.entries.section('yourSection').order('LENGTH(modelNumber) asc, modelNumber asc') %}


How to redirect an entry's URL to a specific URL?

Instead of using a redirect, what about using the saved URLs directly with your links?

Let's say it's a channel with the handle myExternalLinks where you collect the links. The actual URL is entered into a field with the handle myLinkUrl.

This is the template code to list the links:

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

{% for link in links %}

    {#
     # Link to the URL entered into `myLinkUrl` instead of
     # linking to `entry.getUrl()` and then using a redirect on that entry template
     #}
    {{ link.title }}

{% endfor %}


Migrated site - now dashboard keeps logging out

Just a question; are you on a Nginx server?
I had a similar issue before with a client site. the Nginx configuration was removing the cookies when it cached the page, which redirected to the login page after logging in.


How do I wrap my Youtube video from a Redactor field with Bootstrap's responsive classes?

In order to add multiple classes to a video added through Redactor, I'm using the Retcon plugin. This is my solution:

{{ entry.body | retconWrap('iframe', 'div.embed-responsive') | retconAttr( 'div.embed-responsive', { 'class' : 'embed-responsive-16by9' }, false ) }}

There are two Retcon filters applied here. The first filter retconWrap wraps matching selectors in whatever you want. In this case, I'm looking for an iframe and wrapping it in 'div.embed-reponsive':

retconWrap('iframe', 'div.embed-responsive')

The second filter, retconAttr, looks for 'div.embed-responsive' (the wrapper you just applied) and applies any additional classes. The "false" indicates that you do not want to destroy any existing classes, just concatenate them:

retconAttr( 'div.embed-responsive', { 'class' : 'embed-responsive-16by9' }, false )

This may not be the most elegant solution, but it works. Frankly, I feel like we should be able to pass multiple classes through the retconWrap filter, but I've tried and it doesn't work.


Craft Commerce - Purchasables and multiple gateway accounts

You wouldn't need to dynamically change the Stripe credentials on the Stripe payment method, rather it is more likely you would set up a seperate Stripe payment method for each Stripe account.

It is a little known feature that you can set up more than one payment method per gateway with different credentials.

You could then hard code the payment method ID to the relevant teams payment screen (or set it on the cart before they get to the payment page). You could even store the payment method ID in that teams entry.

Hope that helps for the initial question.


Revoke user permissions but not change the usergroup

A user inherits the permissions of any user groups they belong to additively.

If you want to remove specific permissions for that user, you'd need to remove them from the user group(s) they're currently in and either create a new user group for them with their specific permission or add the permissions directly to the user.


Reuse chosen dropdown field value on frontend

i've got now a working approach to my question above:

{% set field = craft.fields.getFieldByHandle('jahrgang') %}

<form action="tourdefrance.html" method="post">
   <select class="dropdown" name="modelljahr" size="1" onchange="this.form.submit();">
     {% for opt in field.settings.options %}
        <option name="fields[myFieldHandle][]" value="{{ opt.value }}">{{ opt.value }}</option>
     {% endfor %}
   </select>

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

{% set modelljahr = craft.request.getParam('modelljahr') %}

<form action="tourdefrance.html" method="post">
  <select class="dropdown" name="modell" size="1" onchange="this.form.submit();">
    {% for entry in entries %}
      {% if entry.jahrgang == modelljahr %}
        <option value="{{ entry.title }}">{{ entry.title }}</option>
      {% endif %}
    {% endfor %}
  </select>

{{ craft.request.getParam('modell') }}


You can do that like so:

{% set params = { group: 'and, not groupX, not groupY' } %}


Updating answer as question was updated

As I see it, you want to find any and all entries where the field weken2017 has either the value 42 or 43.

Assuming that I have understood this much correctly, {% set entries = craft.entries.search(['OR', 'weken2017:42', 'weken2017:43']) %}


How to store class variable inside a Craft controller

In addition to passing the value along through a cookie, you could also do it through PHP's session support.

Adding:

craft()->httpSession->add('sessionId', '123456');

Retrieving:

$sessionId = craft()->httpSession->get('sessionId');

Deleting:

craft()->httpSession->remove('sessionId');


The plugin is only showing the playlists in the CP, in the Videos explorer, to help you pick a video to be used in a video field. It is not currently possible to list playlists and their videos from the templates, but it’s on our list of things to explore for Videos 2.0.


Cache/ColdCache & checking for ungenerated image transforms

Set generateTransformsBeforePageLoad in your config/general.php file.

'generateTransformsBeforePageLoad' => true,

  Configures Craft to generate new image transforms right when getUrl() is called, rather than when the browser first requests the image.


Craft 3 Plugins - Setting Template Path To Site Templates

Ok I've made sense of this - if you set the view template mode/context to site, then use the view renderTemplate() method (not render) it works.

So this is how you achieve the same thing in Craft 3.

# Set the template context to the site mode.
Craft::$app->getView()->setTemplateMode(View::TEMPLATE_MODE_SITE);

# Now using the renderTemplate() method, it will work.
$html = Craft::$app->getView()->renderTemplate("/path/to/particular/site/template");

Edit: Lenka commented pointing out there is actually some official documentation on this.


When using getCriteria() along with buildElementsQuery() raw html gets displayed by the template

$query->queryAll() returns raw arrays of data from the database, this is why you're needing to prepend field_ to each attribute, to get the column name.

You need to populate some EntryModels before you can use them properly in the templates, with something along the lines of:

$query = craft()->elements->buildElementsQuery($criteria);

// modify the query here

$results = $query->queryAll();

return EntryModel::populateModels($results);


Craft doesn't care what the individual slug of an entry is on its own, it looks at the whole path to see if there are duplicates.

Therefore having shop.com/candy and shop.com/about-us/candy shouldn't be a problem, provided the Entry URI Format has been setup correctly for your Sections.

It should take into account the slug of parent entries in generating their own. I use this:

{parent.uri ?? ''}/{slug}


Commerce 3 is not a major change from Commerce 2 - you can see what you need to do to update here:

https://docs.craftcms.com/commerce/v3/upgrading.html

Stripe works with Commerce 3 without any update needed: https://github.com/craftcms/commerce-stripe/blob/develop/composer.json#L28


You'll need to create a template, and add the path to that template to the Entry Template field in your "Services" section's settings.

For instance, if you create a template called /craft/templates/services/_entry.html, you'd use the path services/_entry for your section's Entry Template field.

With this setup, you could also add an index.html file to the /craft/templates/services folder. That template would render when the user visits the URL domain.com/services, enabling you to create a listing/index view for your "Services" section.

For more info, I'd suggest looking at the excellent official docs on templating in Craft.


If you're in the Craft 2 control panel, and you click on Backup Database, it should always store a .sql file in craft/storage/backups.

If you have the Download Backup box checked, then also your browser should download a .zip file containing that .sql file.

Other notes:
It appears to work the same in Craft 3
If you do Clear Caches first, you may get a significantly smaller file.


Is there a tag to get the parents url like {{entry.url}}?

The shortest way, still checking if the parent exists, is to use (not tested):

{{ entry.parent ? entry.parent.link }}

entry.link, or entry.getLink() gives you the {{ entry.title }} part.


Get entries which have content like '%findme%'

It's up to you what you prefer to use. Usually people use the ElementCriteriaModel. You could achieve your goal with the record itself too but it requires more code.

The ElementCriteriaModel provides more ready-to-use options and returns populated entries, Records provide only records, so no populated entries with all relations and such

I'm not sure what that $model->limit is supposed to do, maybe this is a setting in your globals, but you would normally search for entries that contains something (you can find the rules here) with this code

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->search = 'yourKeyWord';
$relaventContent = $criteria->find();

If you just want to have all entries you would do

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->limit = null;
$relaventContent = $criteria->find();


getCriteria not working as expected with boolean field types

I believe this should work (not tested):

$criteria->setAttribute('denied', 'not 1');

As when using the ElementCriteriaModel in Twig, you can't directly check for "falsey" values.


Don't use Redactor / a Rich Text field for code blocks is probably the only answer one can give right now.

Instead you could use a Plain Text field for your article and get the formatting done with markdown. Or you could use Matrix and keep using Redactor for the text parts of your article and have a separate block type for code.


Try to add your alias array within one of your environment array such as:
<?php

return [
    // Global settings
    '*' => [
        'aliases' => [
            '@rootUrl' => getenv('ROOT_URL'),
        ],
    ],

    // Dev environment settings
    'dev' => [
        // ...
    ],

    // Staging environment settings
    'staging' => [
        // ...
    ],

    // Production environment settings
    'production' => [
        // ...
    ],
];


Editing a custom user field onBeforeSave

Solution:

Instead of:

$user->fields['notificationAlreadySent'] = '1';

Use

$user->getContent()->setAttributes(array(
    'notificationAlreadySent' => 1
));

Of note: I find this sort of thing extremely hard to research. I know what I want to do (edit the value of a field in an event via the onBefore listener) but documentation on how to do that seems non-existent. I keep finding this sort of problem with developing Craft plugins - that unless you know the internals, you're really hard pressed to even articulate what you're wanting to search for in order to find a solution.


Assets fields always return ElementCriteriaModel’s in templates. To get the actual related asset, do this:

{% set asset = work.mediakit.first() %}

You can’t be sure that there’s actually a related asset, so it’s worth making sure work.mediakit.first() actually returned something before accessing its properties:

{% if asset %}
    {{ asset.url }}
{% endif %}


Grouping entries by a custom date conditional

You could fetch your entries then split them in three arrays which would give you the ability to then add headings manually and display as you need to.

{# Define today and three arrays to hold your grouped entries #}
{% set today = now|atom %}
{% set futureBids = [] %}
{% set currentBids = [] %}
{% set pastBids = [] %}

{# Fetch your entries #}
{% set entries = craft.entries().section('bids').all() %}

{# Populate your groups #}
{% for entry in entries %}
    {% set starts = entry.biddingStartDate | atom %}
    {% set ends = entry.biddingEndDate | atom %}

    {# future #}
    {% if starts > today %}
        {% set futureBids = futureBids | merge([entry]) %}

    {# current #}
    {% elseif starts <= today and ends > today %}
        {% set currentBids = currentBids | merge([entry]) %}

    {# past #}
    {% elseif ends < today %}
        {% set pastBids = pastBids | merge([entry]) %}
    {% endif %}
{% endfor %}

{# Display as you need... #}

Current Bids

{% for entry in currentBids %}
    {{ entry.title }}

{% endfor %}

Future Bids

{% for entry in futureBids %}
    {{ entry.title }}

{% endfor %}

Past Bids

{% for entry in pastBids %}
    {{ entry.title }}

{% endfor %}


Apparently this is the right way to do it:

$user = User::find()->username($username)->one();
Craft::$app->users->assignUserToGroups($user->id, [1]);

It's unclear how setGroups is supposed to work.


Is Redactor's default config saved as a .json file anywhere?

As @Brandon said, the defaults are hardcoded in redactor.js so there isn't a default.json file, but if there was, this is what it would be (from Craft 2.3.2615):

{
    buttons: ['html', 'formatting', 'bold', 'italic', 'deleted',
    'unorderedlist', 'orderedlist', 'outdent', 'indent',
    'image', 'link', 'alignment', 'horizontalrule'],

    formatting: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5']
}

Since the above code could change on occasion consider checking directly over at the Redactor site:

Buttons defaults

Formatting defaults


Combined entries from sections across locales

The paginate tag requires a criteria model, which means you have to come up with your own pagination solution.

See an example here:
Paginate entries when I do not have a criteria model?


In Craft 3, (how) can I disable a category on a per site basis?

I guess it is either a bug or the developers don't want us to do it via cp request. In my plugin (phpCode) I can activate and deactivate categories per site easily but the cp template is missing the required input. When you compare the route of a category and an entry you'll notice it easily

Take a look at entries/_edit.html

        {% set parentIdParam = craft.app.request.getParam('parentId.0') ?: craft.app.request.getParam('parentId') %}
        {% for siteId in siteIds %}
            {% set site = craft.app.sites.getSiteById(siteId) %}

                {%- if siteId == entry.siteId -%}
                    {{ site.name|t('site') }}
                    {{ forms.lightswitch({
                        name: 'enabledForSite',
                        on:   entry.enabledForSite,
                        small: true,
                        disabled: isVersion
                    }) }}
                {%- else -%}
                    {% set siteEntryUrl = url(
                        'entries/'~sectionHandle~'/'~craft.app.request.getSegment(3)~'/'~site.handle,
                        (parentIdParam ? { parentId: parentIdParam })
                    ) -%}
                    {{ site.name|t('site') }}

                {%- endif -%}

        {% endfor %}

and the categories/_edit.html

        {% set parentIdParam = craft.app.request.getParam('parentId.0') ?: craft.app.request.getParam('parentId') %}
        {% for siteId in siteIds %}
            {% set site = craft.app.sites.getSiteById(siteId) %}

                {%- if siteId == category.siteId -%}
                    {{ site.name|t('site') }}
                {%- else -%}
                    {% set siteCategoryUrl = url(
                        'categories/'~groupHandle~'/'~craft.app.request.getSegment(3)~'/'~site.handle,
                        (parentIdParam ? { parentId: parentIdParam })
                    ) -%}
                    {{ site.name|t('site') }}
                {%- endif -%}

        {% endfor %}

It's missing the

{{ forms.lightswitch({
     name: 'enabledForSite',
     on:   entry.enabledForSite,
     small: true,
     disabled: isVersion
 }) }}

even though when I include the input to the template it does not work since it's not populated correctly. The _populateCategoryModel method does not recognize the field.

To compare it: EntriesController:

private function _populateEntryModel(Entry $entry)
{
    // Set the entry attributes, defaulting to the existing values for whatever is missing from the post data
    $entry->typeId = Craft::$app->getRequest()->getBodyParam('typeId', $entry->typeId);
    $entry->slug = Craft::$app->getRequest()->getBodyParam('slug', $entry->slug);
    $entry->postDate = (($postDate = Craft::$app->getRequest()->getBodyParam('postDate')) !== false ? (DateTimeHelper::toDateTime($postDate) ?: null) : $entry->postDate);
    $entry->expiryDate = (($expiryDate = Craft::$app->getRequest()->getBodyParam('expiryDate')) !== false ? (DateTimeHelper::toDateTime($expiryDate) ?: null) : null);
    $entry->enabled = (bool)Craft::$app->getRequest()->getBodyParam('enabled', $entry->enabled);
    $entry->enabledForSite = (bool)Craft::$app->getRequest()->getBodyParam('enabledForSite', $entry->enabledForSite);
    $entry->title = Craft::$app->getRequest()->getBodyParam('title', $entry->title);

has the $entry->enabledForSite but the CategoryController

 private function _populateCategoryModel(Category $category)
{
    // Set the category attributes, defaulting to the existing values for whatever is missing from the post data
    $category->slug = Craft::$app->getRequest()->getBodyParam('slug', $category->slug);
    $category->enabled = (bool)Craft::$app->getRequest()->getBodyParam('enabled', $category->enabled);

    $category->title = Craft::$app->getRequest()->getBodyParam('title', $category->title);

does not have it

If you want you could create a plugin to fix this issue, it's actually not that complicated since you can change everything in craft now, so you could overwrite the function. But It would be easier to create a ticket with a feature request or something. Maybe Brad could make it clearer

To Resume
If you want to enable categories per site, you have to include the field to the template and to the controller in _populateCategoryModel then it works


Need to create dynamic CSS names for buttons

I would use the slugify twig filter:

{{ block.contactLinkName | slugify }}

It will handle apostrophies, spaces, and anything else that might come along.


You want:

{% if craft.request.firstSegment == 'This' or craft.request.firstSegment == 'That' %}

or this would work:

{% if craft.request.firstSegment in ['This', 'That'] %}


Why isn't relatedTo not working (anymore)?

You are so close! All you need to do is to remove the ’.slug’, because that is what the param is expecting.


Best Approach to all unique groups of users to edit unique groups of entries in 1 channel

If you're not using Craft's user groups for permissions, the solution you suggest is more or less exactly what sprung to my mind. You could create a Category Group called Permissions (just to keep it distinct from Craft's internal user groups), add the initial permission categories that are needed, then create a new field named Permissions that can be added to the User field layout and the field layout for the sections that are being managed.
Each entry can have one or more Permissions categories selected in the Permissions field, and every User can have one or more Permissions categories assigned to them in their profile.
To work out whether the user can edit a particular entry, just check that their permissions match the permissions that are set for that entry. This is probably easiest with IDs:
{% set entryPermissionIds = entry.permissions.ids() %}
{% set userPermissionIds = currentUser.permissions.ids() %}
{% set canEdit = false %}

{#
    If the result of intersecting the user's permission IDs array with the
    entry's permission IDs array is equal to the length of the entry's
    permission IDs array, the user has all the correct permissions to edit
    this entry
#}
{% if userPermissionIds|intersect(entryPermissionIds)|length == entryPermissionIds|length %}
    {% set canEdit = true %}
{% endif %}

{% if canEdit %}
    {# Show edit form #}
{% endif %}

Note: I've not tested this code, but I think the principle is sound!


cannot update Craft CMS - composer errors

composer update vendor/package by design does not update the dependencies of vendor/package. Instead, use

composer require --update-with-dependencies craftcms/cms:3.0.41.1

Per the docs, --update-with-dependencies will

  Also update dependencies of the newly required packages, except those that are root requirements

That will update Craft to 3.0.41.1 and, because 3.0.41.1 has a new Twig requirement (~2.6.2, where 3.0.41 used ^2.5.0), it will update Twig as well.


What is the correct way to update a production site with composer?

Updating Craft on the production server
Assuming the up-to-date composer file was committed and pushed to the repository:
cd /path/to/repo

# Removes any changes that would block the pull and then pulls from master (or your branch name of choice)
git reset HEAD --hard
git pull origin master

composer install --no-dev --no-interaction --prefer-dist --optimize-autoloader

# Depending on the actual server, reload the PHP FPM service to clear the cache
service php7.4-fpm reload

# This one does a backup by default
./craft migrate/all

./craft project-config/apply

# Watch out here, because probably not all caches should be cleared: Imagine all image transforms are gone, not great.
./craft clear-caches/all

Updating Craft in the development environment
This part is covered by the docs: Updating from the terminal
To queue or not to queue
In most cases it is not necessary to touch the queue system, since it relies on Control Panel visits. Here is some more info: Queues


ERROR 1370 (42000) alter routine command denied to user

Most likely your Craft install has some custom stored procedures in it.  I say custom because Craft doesn't use them by default and therefore doesn't require the necessary privileges to use them.

You'd need to make sure the MySQL user account Craft is running as and the one you're using to import the database backup has the
ALTER ROUTINE and CREATE ROUTINE privileges to properly use them.


Grabbing the existing address data to use with Smart Map

I'd recommend migrating all of your map data into a Smart Map Address field. Once you've got everything contained within Smart Map, it will be much easier to render maps and conduct proximity searches.

The best way to migrate would be to use something like Feed Me...

Create a simple JSON or RSS feed which contains only (A) the entry ID, and (B) the VZ Address data.
Pull that feed right back into the same site, putting the address data into your Smart Map field.

Once you’ve migrated to Smart Map, it opens up a lot more possibilities for using that data!


Schedule plugin not working for Feed Me plugin

Guessing you didn't do step #4 in the readme? https://github.com/panlatent/schedule/blob/master/README.md

Add a record to system crontab:

* * * * * php /path/to/craft schedules/run 1>> /dev/null 2>&1


You can make address fields required in two ways - at the front end using your own js form validation or html techniques (and note that the Commerce example templates are not at all intended  for use with live stores, they're just examples to get you going with your own development).

The second approach is in a plugin -

Craft Commerce: Validation on Address Fields

...the ideal approach is probably to use both methods.

Currently (Dec 16) there isn't another way.  I presume this is to give maximum flexibility with checkout and perhaps (and hopefully) pending the time when addresses become proper element types with custom field support.  That would be nice.


Getting an asset Url from an entry loop into a meta tag

I didn't have a full understanding of how blocks work, but I've solved my problem. I think because I was trying to set the variable in my template outside of the block (and I was trying to bring it into my _layout.twig file without referencing the block I was calling) nothing was getting properly passed from one file to the other. The solution I'm now using looks like this:
_layout.twig:
<meta property="og:image" content="{% block ogImage %}{% endblock %}" />

template.twig:
{% block ogImage %}
    {% for image in entry.eventImage.all() %}
        {{ image.url() }}
    {% endfor %}
{% endblock %}


How do you return an instance of a variable class from within a different variable class?

Boom!

So I just needed to put an underscore between the plugin handle and variable name so PluginAnotherVariable.php becomes Plugin_AnotherVariable.php and the classname Plugin_AnotherVariable and things are now working :)


How does one achieve drop-left or drop-right image position?

Generally, I'll have a div that picks up on the position's value.

For example:

That renders something like:

Then I'll have a css rule like this:

.image-left img {
    float:left;
}

It's also important to note where you place this element in relation to your text. You many need to put the image call before or after your text.


Using a Lightswitch to insert a class on a body's tag

Lightswitch fields save an integer to the database:

This integer can be checked just like a boolean, with Twigs if-tag:

<body class='{% if lightswitch_field_handle %}class_name{% endif %}'>

  1 = true  = on
  0 = false = off

.

Twig has also a ternary operator which is similar to php's ternary operator:

<body class="{{ lightswitch_field_handle ? 'class_name' }}">

<body class="{{ lightswitch_field_handle ? 'class_name' : 'alt_class_name' }}">

Answer to Edit 1:

Your example doesn't work because you aren't comparing: if value == 1, you are checking a function: if function(param) == true. Check out the Twig if documentation for more examples.

If entry.whiteText doesn't work, your section doesn't have such a field. If you added it to your main template, you should check if the field is defined.


Something like this should work:

% for category in craft.categories.level(1).enabled(true) %}
    # only enabled categories
{% endfor %}


The example templates work with PayPal express out of the box, there is nothing special you need to do.

You can only add PayPal Express as a Payment method when you have bought and registered Craft Commerce.

Paypal Express is an 'offsite' gateway, and it uses the exact same form as the dummy payment form but posts the form without the credit card inputs - that form then redirects you to PayPal.


Serialization of 'Closure' is not allowed when upload image

I found the problem which is because of a package called "Scout". I just update it and everything seems to be fine now.


Can the HTTP status be set with the redirect tag

That should work fine.  I just did a test in a simple template with:

{% redirect "http://google.com" 301 %}

And I can see it's a proper 301 redirect.  Try clearing your browser's cache?


What is the best way to format a button macro?

You could factor out that repeated class=... like so:

{% macro _btnClass(type, colour, size, fullWidth) %}
    class="btn {{ type }} {{ colour }} {{ size }}{% if fullWidth %} btn-block{% endif %}"
{% endmacro %}

{% macro span(type, text, colour, size, fullWidth, url) -%}
{% import _self as self %}
    <span {{ self._btnClass(type, colour, size, fullWidth) }}>{{ text }}</span>
{% endmacro -%}

It is not clear from your question how you decide which buttons macro to call. Perhaps that code needs to be made DRYer.


Can't seem to get variables set in controllers

Close!  You want to redirect on success and let the request continue as normal on validation failure.

public function actionMyPluginAction
{
    $post = craft()->request->getPost();
    $requestModel = Micros_AuthModel::populateModel($post);

    if ($requestModel->validate())
    {
        // Yay! What I did works!

        $this->redirectToPostedUrl();
    }

    craft()->urlManager->setRouteVariables(array(
        'requestModel' => $requestModel
    ));
}


I overlooked the settings in composer.json to enable a settings page.


You can include a property to your form called $templatePath and users can insert whatever they want in this path with a default value to your own template.

When someone executed your render() function you check if the template file exists in the public template path, if so render it, it not render one of your plugin templates.

If the validation fails, you want to include the validated data with errors to the url manager, so you can access it later. During your render() function you can check if there is data and if it matches your current form element, if so render the data in your url manager instead of the element to display errors.


Is it possible to create a new multisite site via a Craft Plugin/Module?

You have access to the same APIs that Craft itself has; so sure, you could programmatically create new sites via a plugin or module.


Adding these 2 lines worked for me:

linebreaks: true,
enterKey: false

So the entire config is now:

{
    buttons: ['bold', 'italic', 'link'],
    minHeight: 50,
    paragraphize: false,
    replaceDivs: false,
    linebreaks: true,
    enterKey: false
}


Posting from controller to controllers with parameter gives an error

You receive this error because actionMyPluginActionController expects a variable in it's parameters. You'll have to declare a default value

public function actionMyPluginActionController($myVariable = null)

or you need to declare something in your actionMyPluginActionControllerIndex

public function actionMyPluginActionControllerIndex(){
    $myVariable = 'foo';
    $this->myPluginActionController($myVariable);
    return something;
}

Unless you deactivated error messages/warnings on global level (via web config, dev mode off or something else), there is no way this would work in Craft 2 by default


Getting a single, random, related entry within a plug in

$matrixRow->relationshipField returns an ElementCriteriaModel pre-configured to query for the related elements. You can add / override additional criteria and then query for a matching element using the first() method.

$randomEntry = $matrixRow->relationshipField->order('RAND()')->first();

This is basically the same as what you’ve tried with your custom ElementCriteriaModel. It should also work once you have fixed the mistake in the relatedTo param, as the entry that holds the field is the “sourceElement” of a relation.


I ended up using the Ad Hoc Validation method of Yii2, here is the link for documentation:
https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation

My code for validation:
Plugin.php

class Plugin extends \craft\base\Plugin

{
    public function init()
{
    parent::init();

    $this->setComponents([
        'form1Validator' => Form1Validator::class,
        ...
    ]);

    Event::on(
        SaveController::class,
        SaveController::EVENT_BEFORE_SAVE_ENTRY,
        function(SaveEvent $event) {
            try {
                $response = null;
                switch($event->entry->section->handle) {
                    case 'form1':
                        $response = Plugin::getInstance()->form1Validator->validate($event->entry);
                        break;
                    ...
                        }
                }
                if(!isset($response) || !$response['success']){
                    $event->isValid = false;
                    $event->entry->addErrors($response['errors']);
                }
            } catch (\Exception $e) {
                $event->isValid = false;
                $event->entry->addError('exception', $e->getMessage());
                return;
            }
        }
    );
}

}

Form1Validator.php

class Form1Validator
{
 public function validate(Entry $entry)
{
    $model = new DynamicModel(
        [
            'formGender' => $entry->formGender,
            'formFirstName' => $entry->formFirstName,
            'formLastName' => $entry->formLastName,
            'formEmailAddress' => $entry->formEmailAddress,
            'formPhoneNumber' => $entry->formPhoneNumber,
        ]
    );

    if(!$model
        ->addRule(['formGender', 'formFirstName', 'formLastName', 'formEmailAddress'], 'required')
        ->addRule('formGender', 'in', ['range' => ['male', 'female']])
        ->addRule('formEmailAddress', 'email')
        ->addRule('formPhoneNumber', 'match', ['pattern' => '/^[0-9]+$/'])
        ->validate()
    ) {
        return [
            'success' => false,
            'errors' => $model->getErrors(),
        ];
    }

    return [
        'success' => true,
        'errors' => [],
    ];
    }
}


Inside of the <form action="{{ url('search/results') }}"> You define which page should be redirected to when the search form is submitted.

"search/results" would go to the search folder looking for the results.(html / twig).

If you want to redirect to another page you should name the folder (which is "search" now) then the template name. This can be static without creating a "Single" for that page.

If you did create a single that uses that template and you want to go through your single you can just put the slug of the created Single inside your form action.

Example:

You made a folder in craft/templates/ named: search, inside that folder you make a file named: results.

So the file structure would be craft/templates/search/results.twig and the form action would be: <form action="{{ url('search/results') }}">

This way you can just use the preset search template the craft docs offer you. You could also change "results.twig/html" to index.html and then your form action wouldn't need the /results so your action would look like:
<form action="{{ url('search') }}">

But I see you get redirect to /index.php/ aswell so I should try rmeoving that by changing your .htaccess file and maybe your general.php.

You can find instructions on how to do that here:
https://craftcms.com/support/remove-index.php


Is MariaDB required with Craft CMS or can MySQL be used?

Both MySQL and Mariadb are fine to use https://docs.craftcms.com/v3/requirements.html#required-php-extensions


Dealing with existing data in a separate database

I haven't tested, but I'm about 90% confident that Yii's CActiveRecord is directly coupled to the underlying craft()->db connection and there isn't a way to change that at runtime.

You're going to be better off going with the method in the answer you linked to and use QueryBuilder.


A big thanks to Michael Rog (@rog) for the answer on Slack. You can create a catch-all error template with the name error (using whatever file ext works for you). That template also has access to a variable called code that tells you what kind of error it is. In my case, I'm using it to display HTTP Cats.


Let me show you the quickest solution I could think of.
If you put it in {% cache %} tags, you should be fine. You could also create a little plugin that returns the required data from one big-ass query, if you're into building plugins. If you have any plugin experience, then building a plugin is what I would do.

{% set distributors = craft.entries.section('distributors').limit(null) %}
{% set allRelatedProducts = craft.entries.section('products').relatedTo(distributors).limit(null) %}

            Distributor
            {% for product in allRelatedProducts %}
                {{ product.title }}
            {% endfor %}

        {% for distributor in distributors %}
            {# Get ids for all products related to distributor #}
            {% set productsForDistributor = craft.entries.section('products').relatedTo(distributor).limit(null).ids() %}

                {{ distributor.title }}
                {% for product in allRelatedProducts %}
                    {#
                     # Check if product ID is in array containing this distributor's products
                     # and display value accordingly
                     #}
                    {{ product.id in productsForDistributor ? 'yes' : 'no' }}
                {% endfor %}

       {% endfor %}


Image transforms return cpresources URL in Craft Pro 2.5.2754

Turns out this had to do with imagemagick (or one of its subpackages) not being compiled in a way that Craft 2.5 thinks fondly of, which we discovered after editing the bootstrap to turn off all custom error-logging.


\ns\prefix\Plugin::getInstance() returns null from another plugin in Craft 3

I also noticed that Contact Form Tuner seems to be loading before my plugin when testing with die statements in both plugins. Is this the reason?

This.

You're probably doing this from your plugin's init() function.  If you listen to the EVENT_AFTER_LOAD_PLUGINS event and do your logic there, it should work.


Craft 3 Multi Site - Entries/categories/assets fields aren't translatable?

If we want different tutors assigned per site (country) to this course, we can't as an entries field (pulling from teachers section) is not translatable/multi site capable.

  …

  Same for images etc.

All relational field types (Assets, Categories, Entries, Tags, and Users) have a “Manage relations on a per-site basis” setting (under Advanced). If you check it, each site will get its own set of relations.

  But matrix fields aren't translatable either.

Same - Matrix fields have a “Manage blocks on a per-site basis” setting, right below the big Configuration setting.


How can I group a list of tags into ranges of first letters (A–E, F–J, etc.)?

You can do this with the twigPCRE filter. Once you have your allTags, group them like this:

{% set allTagsGrouped = allTags|group('name|first|upper|preg_replace("/[A-M]/", "A-M", 1)|preg_replace("/[N-Z]/", "N-Z", 1)') %}

This takes the tag name, gets the first character, converts it to uppercase (so 'a' and 'A' are grouped together), and then maps all characters in the range A-M to the string "A-M", and all characters in the range N-Z to the string "N-Z". So allTagsGrouped will have two keys: "A-M", and "N-Z" (assuming all tag names start with letters). Obviously you could use more ranges.

Ordering allTags by name appears to be a case insensitive sort, so allTagsGrouped should still be in the right order.


Hook into Entry::EVENT_AFTER_SAVE when user saves it

Your code is pretty close. You want to make sure it's a new entry and not a draft or a revision so you could use:
Event::on(
    Entry::class,
    Entry::EVENT_AFTER_SAVE, static function (ModelEvent $event) {

    /** Entry @entry */
    $entry = $event->sender;

    /** @var User $user */
    $user = Craft::$app->getUser();

    if (
        $event->isNew // Makes sure it's a new entry
        $user->identity->isInGroup('cook') && // Makes sure your user is in the cook group
        !ElementHelper::isDraftOrRevision($entry) && // Makes it's not a draft or a revision
    ) {
            $cpUrl = $entry->cpEditUrl;
            $bodyText = "Dear Admin. /n $userName has created $entry.";
    }
});


How can I access environment variables from a javascript file in Craft 3?

The .env file is on the server and javascript is running in the client so you need to pass it through to javascript in your twig template inside a script tag.

{% set env = getenv('ENVIRONMENT') %}
<script>
    var myVariable = '{{ env|e('js') }}'
</script>

You probably don't need to escape it like in my example above, but good practice anyway. If you are then using the variable in that script you are good to go. From elsewhere on the page you can get the variable using:

document.addEventListener('DOMContentLoaded', () => {
    const myVar = window.myVariable;
});

Great article about this and more https://cruftlesscraft.com/passing-data-from-twig-to-javascript


System language, can I change it after installation?

If you go to Settings->Locales in the control panel, you can add "English - en" as a new locale/language to Craft.

From there, you can can what language the Control Panel will display on a per user basis by going to the user's account and setting the "Preferring Language" setting.

As J. Baptiste pointed out, you can also set what the default Control Panel language should be for all users by setting the defaultCpLanguage config setting.


Loop through all entry types, separate each group type by line rule (hr)

You can use the group filter

{% set allEntries = craft.entries.section('pets').all() %}
{% set allEntriesByType = allEntries|group('type') %}
{% for type, pets in allEntriesByType %}

     All Pets of Type {{ type }}

     {% for pet in pets %}
         {% include '_partials/animalOrgChart' with {
             title: pet.title,
             subTitle: pet.jobTitle,
             img: pet.headshot|length ? pet.headshot[0],
             url: pet.url,
             portrait: true
         } %}
    {% endfor %}

    <hr class="line" />
{% endfor %}


How do I enable editing of entries with a front-end form?

Add another hidden input field "entryId" to your form. There's nice example code in the Docs:

You can modify the form to save existing entries by adding an “entryId” hidden input to the form:
<input type="hidden" name="entryId" value="{{ entry.id }}">


{% paginate myUserQuery as users  %}

{% for user in users %}

{% endfor %}

This should help you also.


I don't believe that there is a recommended way to do this, so I'll attempt to answer this question as best I can.

By using an element type, you will be able to use the element index layout for free, with very little setup. That will give you access to native sorting and searching (filtering), along with a bunch of other things such as grouping, statuses, table and thumbnail views, etc. Creating your element type template is as simple as including the following 3 lines:

{% extends "_layouts/elementindex" %}
{% set title = "ElementName"|t %}
{% set elementType = 'PluginName_ElementName' %}

There is not way that I know of to natively allow sorting of a table without using an element type and it doesn't look like Garnish offers this functionality.

So I guess the only way at present to make this work with JavaScript is to use an external library such as tablesorter or as you mentioned DataTables.


Server requirements for uploading large images

Where do I have to place the php.ini so the upload script knows about it?

In the same folder that Craft's public index.php lives in should be the only place it's required.

You can put a phpinfo.php in that same folder with the contents <?php phpinfo(); and load that page in the browser to see if your php.ini changes have taken affect.

  Also it doesn't depend on the file size but on the image resolution.

That's because there isn't a 1:1 correlation because an images size on disk and how much RAM is required to load that image into memory.

post_max_size, memory_limit and max_execution_time and upload_max_filesize are usually the common culprits when dealing with uploading large files in PHP.


Error on upload: "Impossible to create the root directory..."

I understand now within the context of you are using docker. Since docker creates a new file system separate from your computer's file system, you will want to run these commands on the docker instance.

I do not use docker regularly, but I believe you can use docker attach while the droplet is running to access the droplet's file system.

You will want to set the parent folder to have higher privileges. Try this command:

chmod 774 craftcms-assets

Privileges are composed of three numbers: self, group, and world. There are also three access levels: read, write, and execute. 7 will give access to read, write, and execute. You will want to use 7 for your own commands (self) and for craft's commands (group), but not for the general public (world).

Hope this helps!


When determining the maximum upload file size, Craft first takes the php.ini file upload_max_filesize, post_max_size and memory_limit into account by getting the minimum value and only then applying the Craft maxUploadFileSize config setting.


Call plugin controller from frontend with ajax

I found the solution by making an application of Front end login form with ajax and Posting to controller actions.

Here is what is really important to understand with Craft controller call:

  Most of the time, you’ll want to access controller actions via HTML forms over POST. To do this, we recommend that you leave your form’s ‘action’ attribute blank, and specify your action via a hidden input named “action” instead:

<form method="post" action="" accept-charset="UTF-8">
    <input type="hidden" name="action" value="cocktailRecipes/ingredients/saveIngredient">

  When you leave your form’s ‘action’ attribute blank, browsers will default to the current request’s URL. Which is great in the event that your controller needs to reload the previous page without a redirect. A common example of this is when the user’s input didn’t validate, and you want to pass the errors back to your template (ideally tucked away within a model).

So my solution here with the correct HTML with the form to submit:

<form id="call-support-form" action="" class="form" method="post" accept-charset="UTF-8">
    <input type="hidden" name="action" value="/unep/toolBox/requestBrandingHelp">
    <input class="button" type="submit" value="Support adhérents">
</form>

And the ajax form submit to call the controller:
(and do whatever you want after)

// member support button click
$("#call-support-form").submit( function(e) {

    e.preventDefault();

    var data = $(this).serialize();

    $.ajax({
        method: 'POST',
        url: '/',
        data: data,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
        .success(function(data) {
            console.log('success', data);
        })
        .error(function(data) {
            console.log('error', data);
        });

});


To do this, copy index.php and .htaccess from a.com’s webroot into b.com’s, and make sure the $craftPath variable is correct.

Then, around where $craftPath is getting defined, override $_GET['p'] to make Craft think that the URI actually started with subpath:

$craftPath = '../craft';

$_GET['p'] = 'subpath/' . (isset($_GET['p']) ? $_GET['p'] : '');

// ...

Now when you go to b.com/*, it will be the same as going to a.com/subpath/*.

If you want traffic going to b.com to stay on b.com, you will also need to make sure a.com/subpath is replaced with b.com in any Craft-generated URLs:

{{ url('foo')|replace('a.com/subpath', 'b.com') }}

That will also affect links on a.com, though. If you still want traffic on a.com/subpath to remain on a.com, then it’s slightly more complicated. In your craft/config/general.php file, add a custom domain config setting that varies depending on the requested domain:

return array(
    '*' => array(
        // ...
    ),
    'a.com' => array(
        // ...
        'domain' => 'a',
    ),
    'b.com' => array(
        // ...
        'domain' => 'b',
    ),
);

Then in your templates, only run that str_replace filter when the domain is b:

{% set url = url('foo') %}
{{ craft.config.domain == 'b' ? url|replace('a.com/subpath', 'b.com') : url }}


Custom translation file (Not using Locales/Multisite)

You are looking for Static Translations.

You can add a translation file for English to English (or whatever language you are using) to override default translations. In your case, you'll want to override the app translation category:

In your project folder:

website.com/
└── translations/
    └── en/
        └── app.php

And in app.php:

<?php

return [
    'Invalid username or password.' => 'Something new'
];


It sounds like you've got your home page setup as a Single. Which is a great way to go, and that's what is automatically setting the entry variable.

Here's a great walkthrough on creating an "edit entry" form...

  http://buildwithcraft.com/docs/templating/entry-form

Keep in mind, that example uses entry to represent the entry being edited. That won't work for you, however, since entry is being automatically set as your home page Single.

So when you're attempting to modify another entry, I'd recommend setting it to a different variable name. Obviously you can't have your home page and other entry both be represented by a variable named entry.

{% set entryToEdit = craft.entries.slug('my-entry-to-edit').first %}

Then entryToEdit would replace any instances of entry in the documented example.


Extra margin in Default System on subpages like news

Unlike some other CMS systems, Craft doesn't specify what your front-end templates should look like in any way (you could output your content as .txt files if you wanted to). It also doesn't add anything to your rendered page output that you didn't specify (with the exception of error info if 'devMode' is set to true). The default templates are really just there as placeholders so that you can confirm the system is working properly.

I can't say specifically what is causing your rendering/margin issue, but I would just ignore it and start with your own clean templates. All of the browsers that you mention also have some form of web inspector/development tools. If you really want to know you can 'inspect element' with the browser tools and see what css if any is causing the problem.


How to include search results where keyword input exists only as a category title?

It's hard to say how you could include it since we don't know the rest of your search. Generally the best idea to search is with php and not with twig but you could grab all categories with the title (or whatever field it should be) with

{% set categoryIds = craft.categories.title("Your search term").ids() %}

Then you can fetch all entries that are related to these categories with

{% set entries = craft.entries.relatedTo(categoryIds).find() %}

However: if you just follow this example category titles are included in your search.


How to display multiple entry loops on the homepage (Single section type)

You can do this in a Single without too much trouble. Your homepage will presumably have its own template, so the simplest solution is to content-manage the fields for your Hero, Intro and Image Slider in the homepage Single, and then in the homepage template, hardcode the channels which will form the source of your main entry loop. That way, your homepage Single is responsible for managing content that is specific to that page only, and then outputs other content from elsewhere below.

Here's a quick example of how that might look in your homepage template Twig file:

{% set myHeroField = entry.myHeroField %}
{% set myIntroField = entry.myHeroField %}
{% set sliderImages = entry.sliderImagesField %}

{{ myHeroField.heading

{{ myHeroField.strapline

Read more

{{ myIntroField.textContent }}

See more

{% for sliderImage in sliderImages.all() %}

{% endfor %}

{% set myContentEntries = craft.entries.section('myContentSection').all() %}

{% for contentEntry in myContentEntries %}

{% endfor %}

If you want to get more advanced and flexible, you could use a dropdown or similar in your homepage fields to define which Sections you want to be included in the main entry loop. Sadly, there isn't a first-party Section fieldtype, though there is a third-party plugin (now deprecated, unfortunately). Alternatively, depending on how complex and changeable your content model is, you could use a Dropdown fieldtype and just hardcode your section handles into the values.

In your homepage template, you'd then do something like this to fetch entries to show in the main entry content:

{% set myContentEntries = craft.entries.section(entry.sectionsToShow).all() %}


How do set multiple entry relations using checkboxes on a front end form?

I'm pretty sure you can do this much simpler and without javascript. I've setup a front-end form using the doc's example and added checkboxes to choose entries that will be stored in a relational field simply by using name="fields[fieldName][]" in the input type="checkbox". For example:

<input id="" class="" type="checkbox" name="fields[kitIcons][]" value="{{ entry.id }}" checked>{{ entry.title }}<br/>

In the above example, "kitIcons" is the name of my relationship field, and I have this going through a loop to populate the entry.id and entry.title. Seems to be working without any glitches in my system.


Order entries by a category field alphabetically then paginate

In order to sort your entries by a related field you need to join the relations and the content table and sort your entries by the column you want. The it doesn't change the behavior of your paginate

{# the field ID of your relation field, you can as well grab it via #}
{# set field = craft.app.getFields().getFieldByHandle('carCategory').id #}
{% set fieldId = >> number << %}
{% set entries = craft
    .entries
    .section('cars')
    .leftJoin('{{%relations}} as myrelations', '[[myrelations.sourceId]] = [[elements.id]] and [[myrelations.fieldId]] = ' ~ fieldId)
    .leftJoin('{{%content}} as mycontent', '[[myrelations.targetId]] = [[mycontent.elementId]]')
    .groupBy('elements.id')
    .orderBy({'mycontent.title': SORT_ASC})
    .all()
%}


There's "Upvote" by Lindsey DiLoreto, which allows anonymous voting. Not sure though, if it makes use of cookies and/or logging of IP addresses to forbid people (read: make it harder for them) to vote multiple times.


No, I don't think there's a better way, you need to add that conditional to each select option.
But what you could do is to refactor a bit and move that logic to a Twig macro.

{% macro stateOption(id, name, selectedId) %}
    <option value="{{ id }}"{{ id == selectedId ? ' selected="selected"' }}>{{ name }}</option>
{% endmacro %}
{% import _self as forms %}

{% set selectedId = craft.request.getParam('state') %}

{% set states = {
    'AL': 'Alabama',
    'AK': 'Alaska',
    'AZ': 'Arizona',
} %}

<select id="state" name="state">
    <option value="">Select</option>

    {# Go through states and use the custom macro to generate the select options #}
    {% for id, name in states %}
        {{ forms.stateOption(id, name, selectedId) }}
    {% endfor %}
</select>


You can pass an array instead of the image-transform handle to the getUrl() function

{% set transform = {
    'width' => 600,
    'height' => (asset.getWidth() <= 800)? asset.getWidth() : 800
} %}
{{ asset.getUrl(transform) }}


This question is not really Craft related. Since you just don't send a valid request. You can't send one key multiple times unless you do it in an array.

The php $_GET is a simple array with all your values and you overwrite them again and again.

https://stackoverflow.com/questions/5098397/how-to-pass-an-array-in-get-in-php


Disabled entries don't show up in the Linked entries field when displayed in the CP entry list

Yeah, I agree it's a bit awkward UI-wise in this scenario, but that's currently expected behavior.

You'd probably be able to pull off what you're looking for with a custom plugin by listening to the getEntryTableAttributeHtml hook, though.

In there, you'd check if the passed in attribute is the one for your entries field type, grab the current status and modify the HTML that gets returned based on the status.