You can just use:

{% for entry in craft.entries.section('downloads').relatedTo(currentUser) %}
    {{ entry.title }}
{% endif %}

This is essentially returning an ElementCriteriaModel of reverse related entries sorted by entry date by default. You can also access the related entries through the field itself:

{% for entry in currentUser.selectDownloads %}
    {{ entry.title }}
{% endif %}

This will loop through the related entries in the order they are sorted in the CP.

But to answer your other questions. sourceElement and targetElement can be elements of any element type: entry, category, asset, user, globalSet, tag, etc are all elements. sourceElement simply refers to which is the source of the relationship; and targetElement is what it's related to. field further specifies that you only want to match a specific field rather than using any relationship defined in any field (if you have 2 or more entries fields defined in a channel that are used for different purposes for example).


You can do this entirely from the order param using MySQL’s CASE syntax:

{% set newsItems = craft.entries({
    section: 'news',
    order:   '(CASE field_myLightswitchField
                  WHEN 1 THEN elements.dateUpdated
                  ELSE elements.dateCreated
              END) DESC'
}) %}

Note that you’ll need to include that “field_” prefix before your Lightswitch field’s handle since this is a more complex condition and Craft won’t be sure if it should add that automatically.


How to add two variables into one conditional

It looks like according to your code this (and Aran's) solution should work except for one small difference... if you are testing for this:

entry.title ~ category.title

The value parameter (what is getting stored in the database) should match by removing the space, so from this:

{{ entry.title }} {{ category.entryAlternativeTitle }}

To this:

{{ entry.title }}{{ category.entryAlternativeTitle }}

Or you could also test for the space if you want:

{% if requestTeam.value == entry.title ~ ' ' ~ category.title %}

Update: Also want to note that you may need to test for the "entryAlternativeTitle" variable. Can't know for sure without seeing all of your code but if this is all being executed in the same chunk it should most likely be:

{% if requestTeam.value == entry.title ~ ' ' ~ category.entryAlternativeTitle %}


Error accessing entry when title has special characters

I've never used that plugin, but it looks like they do respect Craft's limitAutoSlugsToAscii config setting, which should prevent a % from getting into the slug.
https://github.com/internetztube/craft-slug-equals-title/blob/master/src/SlugEqualsTitle.php#L45-L47
But that setting only applies to new entries and newly created slugs, and I'm guessing you enabled the Craft limitAutoSlugsToAscii config setting after the entry in question was already created.
You should be good going forward, though.


How can I send email notification to different addresses using Sprout Forms

This can be done with Sprout Forms and the Sprout Fields Email Select Field.

The Email Select field allows you to create a dropdown list of email addresses, hides those email addresses on the front-end so they can't be seen or harvested for spam (the user will only see the Name of each department or discipline you wish to have associated with each email address), and makes the selected email address available after the user submits the form so that you can use that value to trigger an email address using Sprout Forms default notifications or Sprout Email Notifications.

Legacy Answer:

As of Sprout Forms v1.1.0 and the current public plugins available (none that I know of for this use case), you can do this with a Dropdown Field.

Let's say you have a dropdown field with the handle departmentEmailDropdown. In the settings, you can create a list of People/Departments and the emails you'd like them to be sent to:

Label    Value
Support  support@mysite.com
Other    other@mysite.com

When a user submits your form, all the values in the form are available for you to reference in your notification settings using shorthand syntax.

In the Email Recipients field of your Notifications tab, you can reference your dropdown field using the syntax {departmentEmailDropdown}.

The downsides to this approach are that the email addresses in your dropdown will be visible to in your page template, so robots can swoop in and gobble them up.

We've got this on our radar and in the next couple weeks should have an update for you that will allow you to handle this as well as obfuscate the email addresses on the front-end. I'll update this answer when we have that ready.


Create entry from template / UI without a form

The only way to do this is asynchronously with javascript. If you already have an interactive event on the page I'm guessing you are using JS already? If so you just need to submit a hidden front end form alongside the CSRF token.


For the garbled CSS, you need to disable zlib.output_compression in your php.ini file.

Seems to be a PHP bug.


Craft 3: Update database after CMS upgrade via console command

You can use Yii's migrate console command.

Triggered in Craft 3 via craft migrate --type=app.


How can I relate PDFs and Files using an Element Select field in my custom plugin?

I believe you're looking for something like the example posted here which goes into detail on several items necessary to create a working Asset Relations Field in a custom plugin:
https://craftcms.stackexchange.com/a/456/115


The only JS library that ships with Craft (besides the Craft-specific Garnish) is jQuery. Of course, jQuery is a helpful JS library, but by no means a full-fledged framework. Fortunately, adding a separate JS library is painfully easy!

How to CDN from a Twig template...

{% includeJsFile '//full/path/to/cdn.js' %}

How to CDN from PHP...

craft()->templates->includeJsFile('//full/path/to/cdn.js');

When you use includeJsFile, it wraps your path in a standard <script> tag... It doesn't matter where the file is, as long as the path is valid.

Keep in mind, a PHP call will take effect in both the back-end and front-end of your site. So to keep the file loaded only in your CP, make sure to wrap a conditional around it:

if (craft()->request->isCpRequest()) {
    craft()->templates->includeJsFile('//full/path/to/cdn.js');
}

Don't want to CDN? No problem! The best place to store local JS files would be in a resources folder:

/craft
  /plugins
    /myplugin
      /resources
        /js
          /handlebars.min.js

In that case, you can use includeJsResource instead of includeJsFile.


Try using setContentFromPost, as mentioned in this answer from Brandon.

$content = array(
    'fieldHandle' => 'value',
);

$globalSet->setContentFromPost($content);
craft()->globals->saveContent($globalSet);


Custom routes using kebab {type} in URL segment

You could have a try with dynamic routing, where you map a URL (or a url pattern) to a specific template.

Dynamic routes take priority over template paths.

If I misunderstood you, can you give an example as to what the URL is for a specific entry compared to what you need it to be?


Use the ActiveRecord from Yii2

$userGroupId = 1 // insert your usergroup Id here
$users = User::find()->groupId($userGroupId)->all();

Or via handle

$userGroup = Craft::$app->userGroups->getGroupByHandle('handle');
$users = User::find()->group($userGroup)->all();

If you mean the number of users in a group with total you just have to do count() instead of all()

To get the users of each group you can do

foreach(Craft::$app->userGroups->getAllGroups() as $userGroup){
    $users = User::find()->group($userGroup)->all();
}


You have (at least) two options here:

Create a matrix block with the fields you need. That way, the user kan add one or more blocks of the type 'button' (for instance) to the page. Within button, you could have a plain text field for the link and name, a color field for the color, a number field for size, etc.
Create your own fieldtype (http://buildwithcraft.com/docs/plugins/field-types, not as easy as first option). That way you have optimal control over the way your user inputs values.

I would go with option 1.


Filtering orders by date bring wrong results

Try something like:

{% set firstDayOfMonth = year ~ "-" ~ month ~ "-01" %}
{% set daysInThisMonth = firstDayOfMonth|date('t') %}
{% set lastDayOfMonth  = year ~ "-" ~ month ~ "-" ~ daysInThisMonth %}

{% set thisMonthsOrders = craft.commerce.orders.dateOrdered('and', '>= ' ~ firstDayOfMonth, '<= ' ~ lastDayOfMonth) %}


Cannot post data to a plugin controller action

There's alot of different things that could be going on here.

First, if your action is named actionPayWithPaypal (as in the code above) the action url should be paypalPayments/payment/payWithPaypal I guess?

You won't be able to hit the cocktail recipes method directly from your browser since it requires the request to be a post. But you should be able to hit your controller with yourdomain.com/actions/paypalPayments/payment/payWithPaypal.

But, only if you're logged in. If you're not logged in, that will give you a 404 unless you enable anonymous access to the controller, see the documentation on how to do that.

Also, is your .htaccess rewriting working as it should? If not, that could cause problems with calling the action directly.

Try generating an action url and see if that works:

Test me


There are two major approaches.

The easier approach is to create a partial template that displays the cart lineItems, and simply ajax load that template in to a div that is your cart display after you've done the lineItem update.  However, this has the disadvantage of making the whole cart section update in a visible way, which look a lot less finessed than the second approach.
In  short, you'll need to use the cart object in the json response to re-draw just the appropriate parts of your cart display.

Here's an example of approach 2, (don't focus on the specifics below which are from a live site - but rather this should be enough to give you the idea) - if the user e.g. adjusts line item quantities, we grab the appropriate parts of response.cart and then do some local calculations and update the appropriate parts of the page:

            $.post('/actions/' + $('input[name=action]').val(), form.serialize(), function(response) {

            // Change in qty successful
            if (response.success) {
                if (response.cart.lineItems[id]) {
                    var subtotalNew = parseFloat(response.cart.lineItems[id].price * response.cart.lineItems[id].qty);
                    utilities.replacePrice($subtotal, subtotalNew);
                }

                navCart.update(response.cart);
                cart.update(response.cart, true);
            }

...where, for example, utilities.replacePrice is:

replacePrice: function($obj, price, discount) {
    var text = module.exports.currency(price);

    // Handle discounts
    if (discount) {
        // Supplied as negative number - because we want it formatted differently, we make it positive
        var discountPrice = module.exports.currency(price * -1);
        text = '- (' + discountPrice + ')';
    }

    $obj.fadeOut("fast", function(){
        $obj.text( text );
        $obj.fadeIn("fast");
    });
},

...and the cart.update functions are similar and take care of updating the nav bar cart and the totals and shipping sections.

I will warn you that implementing in full a completley ajax updating cart page is a fair bit of work and complexity to get right, and the actual implementation will depend greatly on your checkout flow, which you should have thoroughly worked out BEFORE you implement this, or you can quickly tie yourself in JS knots.

If you want to see a fairly completely ajaxed Commerce cart in action, add this to your cart and then visit your cart and muck about changing quantities and removing things etc:
https://imagescience.com.au/products/inkjet-print-retouching-kit


If the client selects an empty value you probably will get an empty value back.

Try this:

{# Make sure we have a value #}
{% if entry.dropdownFieldHandle != "" %}

Title

{{ entry.dropdownFieldHandle }}

{% endif %}


Two different lightswitches to add class on body tag

You can use the same lightswitch field on both of your channel sections.

But I wouldn't use an EntryModel in the _layout.html (assuming that's a template you use to extend your actual entry and index templates with).

You probably have two different _entry.html templates for your sections "project" and "events". Define a variable in these if your condition (lightswitch) is true:

{% extends "_layout" %}

{% if entry.whiteLogoText %}
    {% set bodyClass = 'white' %}
{% endif %}

{% block content %}
{% endblock %}

This is how your _layout.html should look like:

{% if bodyClass is defined %}
    <body class="otherBodyClasses {{ bodyClass }}">
{% else %}
    <body class="otherBodyClasses">
{% endif %}

<main class="page" role="main">
    {% block content %}
    {% endblock %}
</main>

</body>

Or with the ternary syntax:

<body class="otherBodyClasses {{ bodyClass is defined ? bodyClass }}">

.

Edit:

You can additionally set that bodyClass variable in other templates using different conditionals:

{% if myGlobalSetHandle.whiteLogoTextForProjectsEntries %}
    {% set bodyClass = 'white' %}
{% endif %}

or (based on my latest assumptions on what you wanna do):

{# Define var before the for loop #}
{% set bodyClass = '' %}

{# Check if `whiteLogoText` is set on any "project" entry #}
{% for project in craft.entries.section('projects') %}
    {% if project.whiteLogoText %}
        {% set bodyClass = 'white' %}
    {% endif %}
{% endfor %}

With this last code example you have to define the variable before the loop to make it accessible outside of it. Because you will always have a bodyClass defined then, change the conditional in your _layout.html like this:

<body class="otherBodyClasses {{ bodyClass is defined and != '' ? bodyClass }}">


Craft Commerce product item price showing incorrect

As Jeremy Daalder pointed out, Its the local system settings causing this.
A workaround is available in the link he posted.


That's a bug in Craft that occurs with the specific configuration of PHP you're running.  Just fixed it for the next release, though.

In the meantime, you can open up craft/app/etc/web/UrlManager.php, find the parseUrl method and change it from:

public function parseUrl(HttpRequestService $request)

to:

public function parseUrl($request)


Display all entries matching field of a section

Looks to me like your solution is mostly correct, except for handling the gamesCatalogNumber. For that you could either:

test for specific publisher(s) by id or slug
test if gamesCatalogNumber is empty on the first entry (and assume that the publisher doesn't use catalog numbers), or
(recommended solution) add a checkbox or lightSwitch field to the publisher called 'usesCatalogNumbers' and test for that.

Something like:

{# publisher template #}

{% if entry.usesCatalogNumbers %}
    {% set games = craft.entries.section('games').relatedTo(entry).order('gamesCatalogNumber desc') %}
{% else %}
    {% set games = craft.entries.section('games').relatedTo(entry).order('title asc') %}
{% endif %}

    {% for game in games %}

{% if entry.usesCatalogNumbers %}{{ entry.gamesCatalogNumber }}: {% endif %}{{ entry.title }}

    {% endfor %}

{% set params = craft.entries.section('publishers').order('title asc') %}
{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}
{% if prevEntry %}Previous Publisher {% endif %}{% if nextEntry %}Next Publisher{% endif %}

I recommend this (instead of the other options) because it's a bit more explicit and extensible (i.e. allows you to add other publishers that use catalog numbers without modifying the templates).


This answer is a bit self-serving, but I'm the author of the Digital Download plugin. It allows you to control how and when assets are downloaded.
You can restrict downloads by a time period, maximum number of downloads, or tie them to a logged-in user.


Anyone with a tricked out .htaccess file

Been using this one for years, works great:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # ========================================= #
    # Force website to use "www"
    RewriteCond %{HTTP_HOST} ^example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
    # ========================================= #

    # ========================================= #
    # Force website to use "https"
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
    # ========================================= #

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

</IfModule>

This one adds www, but it's simple to reverse that (as you do in your original example).


Applying image transforms to remote images?

Imager plugin is capable of resizing remote images


(Not necessarily a great answer to your question, but it's in the same wheelhouse and might be handy if you're working in this area)!

I remember having issues with this myself (to be honest the precise details are a bit lost in time for me - but basically IIRC it's by design that they're not logged in after creation, perhaps to force them to practise login/their password?  I can't remember but do remember I found it odd behavour) - anyway in my case the issues arose as part of adding user registration during commerce checkout.  It was discussed on Slack and the solution was that Steve Rowling made a very handy plugin to auto-login newly created users:
https://github.com/steverowling/autologin

I'm using it, works a treat.

(I should also wrap up my code for registration during checkout as a plugin and release that one of these days!)


This was an ordering mistake. I didn't setup my grid properly for the loop that has to take place.


You can call the first() function to just get the first image:

{% set image = block.backgroundImage.first() %}
{{ image.getUrl() }}

But this will fail if there is no image. So to be safe, you need:

{% set image = block.backgroundImage.first() %}
{% if image %}
    {{ image.getUrl() }}
{% endif %}


Pass 'not' category.id to relatedTo in Craft

You need to exclude the ids in order to achieve your goal. So instead of relatedTo not you need a normal related to but the not statement in your id

I'm not on my computer currently so I'll edit the exact code in about 2h but it's the same like that one
https://craftcms.stackexchange.com/a/22532/5557

id.('and, not ' ~ idsOfEntriesYouWantToExclude|join(', not ')
Is the important part. In order to get them you just select all entries that are related to the thing you want to exclude

Edit
untested but this should do it

{% relatedEntries = craft.entries.relatedTo(status).ids() %}
{# just for debugging to test if the queryString is correct #}
{% set queryString = 'not ' ~ relatedEntries|join(', not ') %}
{% set results = craft.entries({
    id: 'and, ' ~ queryString,
    section: 'properties',
    price: range,
    search: query.location,
    order: priceDesc
}) %}


How to add a facebook and twitter share button on a page

Facebook/Twitter look for Open Graph(OG) metadata when a page is shared. To specify what this data is, you have to include the meta tags in the head of your page.

Step 1:

Have meta tags for the page

e.g.

  <title>My Website Title</title>
  <meta property="og:url"           content="https://www.myWbsite.com/my-page.html" />
  <meta property="og:type"          content="website" />
  <meta property="og:title"         content="My Website Title" />
  <meta property="og:description"   content="Page description" />
  <meta property="og:image"         content="https://www.myWebsite.com/asset/image.jpg" />

You can also create custom fields and call them dynamically on each page.

//Facebook
<meta property="og:url" content="{{ craft.app.request.absoluteUrl }}"/>
<meta property="og:type" content="website"/>
<meta property="og:title" content="{{ entry.title }}"/>
<meta property="og:image" content="{{ entry.socialImage }}"/>
<meta property="og:description" content="{{ entry.description }}"/>
<meta property="og:site_name" content="{{ site.name }}"/>

//twitter
<meta name="twitter:url" content="{{ craft.app.request.absoluteUrl }}"/>
<meta name="twitter:title" content="{{ entry.title }}"/>
<meta name="twitter:description" content="{{ entry.description }}"/>
<meta name="twitter:image" content="{{ entry.socialImage }}"/>

I use SEOmatic plugin to make the above procedure easy. There are also other plugins available for things like this as well.

Step 2:

Static URL:

Share on Facebook

Share on Twitter

or Dynamic URL:

then add these below in JS

function shareWindow(url) {
    var left = (screen.width - 570) / 2;
    var top = (screen.height - 570) / 2;
    var params = "menubar=no,toolbar=no,status=no,width=570,height=570,top=" + top + ",left=" + left;
    window.open(url,"NewWindow",params);
}

function setShareLinks() {
    var pageUrl = encodeURIComponent(document.URL);
    var tweet = encodeURIComponent(jQuery("meta[property='og:description']").attr("content"));

    jQuery(".share.facebook").on("click", function() {
        url = "https://www.facebook.com/sharer.php?u=" + pageUrl;
        shareWindow(url);
    });

    jQuery(".share.twitter").on("click", function() {
        url = "https://twitter.com/intent/tweet?url=" + pageUrl + "&text=" + tweet;
        shareWindow(url);
    })

}

References:

https://css-tricks.com/simple-social-sharing-links/
https://developer.twitter.com/en/docs/twitter-for-websites/tweet-button/overview
https://developers.facebook.com/docs/plugins/share-button


ElementAPI - Can I use javascript/ajax to load json

Totally do-able.

Once you have the ElementAPI plugin downloaded and installed, you'll want to make sure you have created a file called elementapi.php and it is in your /craft/config/ directory.

For simplicity's sake, I've used a stripped down version of the example on the github page.

elementapi.php

<?php
namespace Craft;

return [
    'endpoints' => [
        'news.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function (EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'jsonUrl' => UrlHelper::getUrl("news/{$entry->id}.json")
                ];
            },
        ]
    ]
];

Going back to your /craft/config/ directory, you will want to enable CSRF protection..

Finally, (again for simplicity) here is an example of getting my news entries via ajax on docReay

_layout.html

<head>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js">  </script>
<script>
    $(function () {
        var data = {
            'CSRF': $('input[name="CSRF"]').val(),
        };

        $.ajax({
            'type': 'get',
            'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cache': false,
            'data': data,
            'url': 'news.json',
            'dataType': 'json',
            'timeout': 50000
        }).done(function (response) {
            console.log(response);
        }).fail(function (error) {
                // Total fail.
            });
        });
    </script>
</head>

<body>
<div id="container">
    {{ getCsrfInput() }}
...

Then if you look at your console, you should see something like this:

{"data":[{"title":"We just installed Craft!","url":"http:\/\/craftsandbox.dev\/news\/2016\/we-just-installed-craft","jsonUrl":"http:\/\/craftsandbox.dev\/news\/3.json"}],"meta":{"pagination":{"total":1,"count":1,"per_page":100,"current_page":1,"total_pages":1,"links":[]}}}

Hope this helps!


Whilst this mainly seems like a front-end development question, and Dr_Codswallop has perfectly summed up some steps in the comments to tackle that, as an answer for the Craft CMS specific side of the question there is a plugin I have used in the past that is very helpful, but it is only for Craft 2.x:

Donkeytail

I have had a look through the plugin store and I can't find an alternative plugin for Craft 3.x, so it looks like you will need to follow Dr_Codswallops instructions and build up something manually if you are running this version of Craft.


migrating from Linux to Windows, but my templates aren't loading

It looks like your craft/templates folder on the Windows box has the default template that Craft ships out-of-the-box with and not the custom templates and front-end resources that you've designed.

Make sure your correct files are actually in craft/templates.


For security reasons, this was changed in Craft 2.3...

  Admins are no longer allowed to change other users’ passwords.

But savvy admins can still pull it off... Simply click the gear icon in the right sidebar, and select "Copy password reset URL". Then, instead of sending that URL to the user, just use it yourself.


Get entry url from primary site (using seomatic)

So probably you don't want to use canonical URLs there, but rather hreflang -- and the good news is that as long as all of your localized sites are in the same site group in Craft, SEOmatic does all of this automatically for you:

SEOmatic Multi-Site Language/Locale Support


How to show entries with IF statement based on field

Your if statements looks correct. You might check that you are testing the value vs. the name (i.e. 'Portrait' vs 'portrait') or printing out the value (using {{ entry.postAspectRatio }}) so you can see the output. Also, a 'dryer' way to write this might be:

{% block content %}

    {% for entry in craft.entries.section('projects').order('postDate asc').limit(500).find() %}

{{ entry.studio }}{{ entry.title }}

    {% endfor %}

{% endblock %}


Sort single entries by section with same query order

This is only possible with the id parameter in combination with fixedOrder.

{% set entries = craft.entries.id([307, 287, 488]).fixedOrder(true) %}

You can look up your singles' IDs in the URL of the entries in the CP.

example.com/admin/entries/section1/307-section1/


Something like this should work:

public function init()
{
    craft()->on('commerce_lineItems.onPopulateLineItem', function(Event $event) {
        $purchasable = $event->params['purchasable'];

        $myDropdownFieldValue = $purchasable->getProduct()->getContent()->myDropdownField;
    });
}

Relevant event docs: https://craftcommerce.com/docs/events-reference#commerce_lineitems.onpopulatelineitem


How would one allow users to edit only some other users entries but not all? Linked via a related field

I managed to implement it, don't know if it's the best way. Ideally I would like to disallow users to edit other entries, then in the EVENT_BEFORE_SAVE grant permissions, but I think the permissions are being checked before EVENT_BEFORE_SAVE so I could not find a way to tap into it before then.

Therefore I have granted the user permissions to edit other users entries, then the following code will check if the user is in the same organisation, and if they are not set the event isValid to false, which stops it saving.

Event::on(
Entry::class,
Entry::EVENT_BEFORE_SAVE,
function(Event $event)
{
    // Only do it on front end
    if (Craft::$app->request->isSiteRequest)
    {
        // Get Entry Data
        $entry = $event->sender;

        // Only call it if its sectionId 1 = Projects or 22 = KPIs
        if( $entry->sectionId == 1 || $entry->sectionId == 22)
        {
            // Entry Organisation ID
            $entry_organisation_id = $entry->client->id[0];

            // User Organisation ID
            $user = Craft::$app->getUser()->getIdentity();
            $user_organisation_id = $user->getFieldValue('organisation')->first()->id ;

            if($user_organisation_id != $entry_organisation_id)
            {
                // Disallow!
                $event->isValid = false;
            }

        }
    }
}

);

Code goes into a plugin init() function I have for my site.


Custom Shipping Method Availability in Commerce - User Messages

100% untested, but I think one way to go would be to use addError on one of the Commerce_OrderModel's attributes (in the defineAttributes method).

Then your template could do something like:

{% if 'myShippingMethod' not in craft.commerce.availableShippingMethods|keys %}
    {% for error in order.getErrors('theAttribute') %}
        {{ error }}<br />
    {% endfor %}
{% endif %}


What should my controller return in a Craft.postActionRequest

If you're just looking to return true or an error message from your controller's action, then it should probably be something like:

$this->returnJson(array('success' => true));

Or on error:

$this->returnErrorJson($e->getMessage());

returnErrorJson will set an 'error' key and pass whatever mess you use as its value.


Write into Sprout Forms from another plugin

When leveraging another plugin programmatically, you will typically want to use the service layer. In your case, the SproutForms_EntriesService.php is where the saveEntry action gets processed. The saveEntry service method expects a SproutForms_EntryModel:

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

Here is a longer example:

// Create a new instance of a SproutForms_EntryModel
$entry = new SproutForms_EntryModel();

// Set some SproutForms_EntryModel attributes
$entry->formId    = 4051;
$entry->ipAddress = '127.0.0.1';
$entry->userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36';

// Set the custom fields
$entry->setContentFromPost(array(
    'fullName' => 'Test Name',
    'message' => 'Test message'
));

// Save the entry
craft()->sproutForms_entries->saveEntry($entry);

Sprout Forms should dynamically set the title value for you, based on the value you have in the Advanced->Title Format setting.

In the case it doesn't seem to work, a quick way to see if there are any errors is to kill your script after you tried to save the entry and view the full list of errors (or use a more advanced PHP debugging workflow with a tool like XDebug):

Craft::dd($entry->getErrors());

See the answer from Brandon Kelly on this post for more information on how to set custom fields on an Element.


How can I change the Date Created for Assets?

The dateCreated column you're referring to is more of a minimum internal audit trail that Craft uses when a new row is inserted into the database (along with dateUpdated).
Is sounds like you want something that references the original time the asset was created, which would be stored in the images EXIF/metadata.  You could write a plugin that read that information: https://craftcms.stackexchange.com/a/8521/57


Can a model or record have conditional requirements?

I can think of a couple of options and I'll just throw them all out there.

Have a separate model per partial form and each model performs its own validation.
Have a single model, but have it override the rules() method and you can conditionally set what validations methods you want depending on the step you're on. Presumably, you'd want to pass in a step number either through the querystring or through POST.  You can see an example of how we're doing some conditional validation using this method for email settings in EmailSettingsModel.
Don't worry about any of Craft's/Yii's automagic validation classes and just have the controller manually do its own validation per form and return errors as necessary.


Migrating a Craft site to a different host.

Per the OP's comment, there was a database connection error in the Craft log files. Once that was corrected it solved the 500 Internal Server Error.


Push Notification plugin will not send iOS alerts when Craft CMS devMode is set to false

I finally figured this out!

For any iOS application, in order to test the "Production" alerts to a physical iPhone Device -> You have to create an Ad-Hoc Application and deploy that to your iPhone device.

In order to do this, you must have an Ad-Hoc Distribution Profile created in the Member Center of "Certificates, Identifiers, and Profiles.

See this page for more information: https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/TestingYouriOSApp/TestingYouriOSApp.html

When using the Push Notification Plugin in debug mode, it works with the sandbox URL of Apple's Push Alerts. It will not use the production URL if you have debugMode set to true in the general.php file of Craft's configs.

Note: You will also have to set up the production certificate and configure that in the Push Notification Plugin settings to use the PEM file for the Production.

Once you deploy an Ad-Hoc Application to your iPhone device and have the PEM file setting pointed to your Production certificate, then everything should work fine (Make sure debugMode is set to false or remove this setting from the general.php file), the device will receive the alert.

I have tested this and it works on my iPhone 6 device.

Nothing is wrong with the ZendFramework or Push Notification code.

The issue was the deployment for the application on the iPhone device. I was testing directly from Xcode and using its build which is a development build (not an Ad-Hoc Build).


PHP version issue when installing Craft 3 using Composer

You are running PHP 5.6.30 on the command line (read the error message), which you can also verify with php -v.

To swap the PHP, you should add the path to your preferred PHP executable to your shell’s configuration file (e.g. ~/.bash_profile, ~/.bashrc, ~/.zshrc).

export PATH="/Applications/MAMP/bin/php/php7.1.1/bin:$PATH"

Another option is to ignore the PHP requirement using --ignore-platform-reqs

composer create-project craftcms/craft . -s beta --ignore-platform-reqs

and then fake the PHP version in the project’s composer.json for later updates

"config": {
  "optimize-autoloader": true,
  "platform": {"php": "7.0"}
},


Craft Licensing and Multiple Environments on Different Domains

There's a guide to how licensing is enforced :)


Plugin for creating categories on an entry page in Control Panel

Can you use tags maybe? I think they work kind of the same, and u're able to add new ones right in the entry.


Your approach is technically correct – the problem is that craft()->imager->transformImage() requires two additional parameters; $transformDefaults and $configOverrides.

You can read more about these parameters and the transformImage method in the plugin's official docs, but it's not super important. The two parameters can actually be null, which means the following should work:

$sizerOptions = array('width' => 202);
$transformedImage = craft()->imager->transformImage($asset, $sizerOptions, null, null);

Note that while Imager does work with URLs, if you do have an AssetFileModel (i.e. $asset) it's actually better to feed that to transformImage() because then Imager will handle automatic cache breaking etc. for you (e.g. if you replace the image in Craft later on) – so my advice is to use transformImage($asset), not transformImage($asset->url), whenever possible.

Finally, in case you're wondering why the below works for templates:

{% set transformedImage = craft.imager.transformImage(image, transform) %}

...when you need the additional two parameters when you do the same thing in PHP, here's a quick explanation of what's going on:

Plugins in Craft are made up of several different components – among them, Services and Variables.

You can think of Services and Variables as two different APIs for a plugin – one is only made available to PHP (Services) and the other is only made available to Twig/templates (Variables).

Craft makes plugin Services available in PHP by instantiating them and adding them to the global craft() object in the format craft()->serviceName. For many plugins, there'll only be a single service, usually named after the plugin itself (e.g. ImagerService, which is mapped to craft()->imager). There can be several though, e.g. Imager_AnotherService, which would be mapped to craft()->imager_another.

Unlike Services, plugins can only have a single Variables class, which is always named after the plugin (e.g. PluginNameVariable) and mapped to craft.pluginName. In Imager's case, this means that the ImagerVariable is mapped to craft.imager in Twig.

Whenever you call craft.imager.transformImage() in a template, you're actually interacting with a Variable class – in this case, ImagerVariable. When you call craft()->imager->transformImage() in PHP, you're interacting with the ImagerService class.

The fact that the ImagerVariable and ImagerService both have a method called transformImage is a common design pattern in Craft, where variable classes are used to "wrap" Services, in order to expose the latter for use in templates. Often (and this is true for Imager, as well), the Variable methods do little more than to call their namesake Service methods. Using the same names for Variable and Service methods isn't a requirement, though – just a "best practice" to ensure consistent plugin APIs for templates and PHP. Imager's author could've opted to call the Variable method transform, doTransform, transformy or basically anything else.

Finally – as I mentioned, Imager's Variable method transformImage basically just wraps the ImagerService->transformImage method – but with one important difference: The Variable method makes the two additional parameters ($transformDefaults and $configOverrides) optional. This is why you don't have to declare them when you use Imager in a template, but you do have to define them when you use it in PHP.

A fun trick is that while Craft doesn't expose Template Variable classes to PHP out of the box, there's nothing preventing you from using them "manually". For example, say you prefer the Imager's Template Variable API over its Service API; here's how you can use the Variable methods wherever you want in your PHP:

Craft::import('plugins.imager.variables.ImagerVariable');
$imager = new ImagerVariable();

$transformedImage = $imager->transformImage($asset, $sizerOptions);


Install Craft in a subfolder of an ee site?

In additional to the potential session headaches, you'd also have to worry about getting the .htaccess rewrite rules to play together for each installation considering they inherit from any parent folders.


Related entries in a matrix field are technically related to the matrix block and not the entry. So you will first want to get the related entries via relatedTo(block); then loop through the related entries to get the field values.

{% for block in entry.menuLinks %}
    {% set relatedEntries = craft.entries.section('SectionName').relatedTo(block) %}
    {% for entry in relatedEntries %}
        {{ entry.title }}
    {% endfor %}
{% endfor %}

If you know there is one and only one block or related entry then you can skip the for..in loop(s) and just use the .first() method (i.e. entry.menuLinks.first() and or  craft.entries.section('SectionName').relatedTo(block).first());

Keep in mind that if you are just trying to create a simple list of links to related entries you do not need a matrix field at all (unless of course you are doing something more complicated). The Entries Field Type itself can support an unlimited number of related entries (and are sortable), so you could just create an entries field directly in programs.


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

In Craft 3, you can't really have locales. If in Craft 2 you had multiple locales, that should have been automatically migrated to multiple sites (as now the site is always single locale)

Having said that, you now need to use site or siteId parameter https://docs.craftcms.com/v3/dev/element-queries/entry-queries.html#site


How to set view path for rendering email templates?

For anyone struggling with this, apparently this is one way of doing it.

I struggled with this for quite some time before posting my original question, but regardless, sorry about that.

Anyway, here it is.

Craft::$app->setViewPath('/path/to/templates/');
$body = Craft::$app->getView()->renderTemplate('confirmation.twig', ['orderId' => $orderId, 'customerId' => $customerId]);
Craft::$app->mailer->compose()
    ->setFrom(['me@me.com')
    ->setTo('me@me.com')
    ->setSubject('hey')
    ->setHtmlBody($body)
    ->send();

Edit:

There's probably a better way of doing this, but if you're working in multiple environments, you can do this in general.php

'dev' => [
    'templatePath' => '/Users/stian/dev/site.com/templates/',
],
'staging' => [
    'templatePath' => '/Users/stian/dev/site.com/templates/',
],
etc

and then Craft::$app->setViewPath(Craft::$app->config->general->templatePath) in your plugin/module.

PS! Will mark as answered once I'm allowed


It's hard to see what you're actually trying to achieve here, but yes it's likely to do with the amount of queries you're doing on the page.
I would either re-consider the page layout (without knowing what you're trying to achieve by having two loops it's hard to judge) OR pull some, or all of the results asynchronously using javascript so the page rendering isn't blocked whilst the query is being processed.
The newly released sprig plugin may be of interest.


Can I use Regex in the Find and Replace tool?

Nope, because MySQL doesn't support RegEx replacements in SQL statements.  It's been an open feature request since 2007, so feel free to add your vote.

There are some potential workarounds listed here, too.


requireAdmin is hard coded into the actionActivateUser action in line 444 of the UsersService file, so I suspect that there is no way to over-ride this without creating your own plugin.


Can you use Craft to build a relational web app database in a Knapp or Caspio style?

It is perfectly possible. You would probably need a channel for the events and perhaps a separate channel for interactions on the event (ratings, comments etc). You can use Guest Editions or create your own plugin to add entries via a form.


Multiple URL Formats per element type (Entries, Categories)

So semantically, I don’t love the URL format you’re coming up with.  I’d like to see something like /gear/{category}/{entry}

This gives you a few benefits

it’s semantically readable…
it gives you natural breadcrumbs for the hierarchy of content
it’s likely going to be better from an SEO perspective

Relevant feature request: https://github.com/craftcms/cms/issues/1189


Immediately found a solution!
{% set newsQuery = craft.entries({
    section: 'news',
    after: now|date_modify('0:00 -1 months'),
}) %}


I assume this is in the context of an event, in which case you've got access to the EntryModel.

If so, $entryModel->locale should be what you're looking for.


I think you're nearly there! Give this a shot:

{% set allEntriesByPrename = allEntries | group('{{ (object.composerName | first).lastName | upper | slice(0, 1) }}') %}

I believe the issue is that relations always come back as an array, and you were trying to immediately access a property of the Element at index 0 in that array, rather than de-referencing it, then accessing the property.

Be aware that this may generate some deprecation errors, as using the first filter will attempt to use the relational field as an array. Instead, I'd recommend eager-loading your Composers along with the Compositions--in addition to being safer, moving forward, it avoids an N+1 problem, and will dramatically reduce the number of queries on your page:

{# See: `with`, including the `composerName` field handle: #}
{% set allEntries = craft.entries({
  section: 'komposition',
  limit: null,
  with: [
    ['composerName']
  ]
}).all()

{# Grouping by a relation will no longer trigger another query per Composition: #}
{% set allEntriesByPrename = allEntries | group('{{ (object.composerName | first).lastName | upper | slice(0, 1) }}') %}

  Note: I had to use the expanded syntax for the group filter ({{ ... }}) in order to enforce the proper order of operations. In that context, object is a reference to the Composition.


What is the best way to handle HTTP requests within a plugin using Yii or Craft?

Craft includes Guzzle which is very full-featured... I'd use that.
Sorry I don't have time for converting your example but here's a simplified version of how to use it in a Craft plugin:
$client = new \GuzzleHttp\Client([
    'base_uri' => 'https://www.example.com/api',
    'http_errors' => false,
    'timeout' => 10
]);

$data = ['some' => 'stuff'];
$uri = 'post-a-thing'

$response = $client->request(
    'POST',
    $uri, [
        'body' => json_encode($data),
        'headers' => [
            'User-Agent' => 'CraftCMS',
            'Content-type' => 'application/json'
        ]
    ]
);

(I usually set http_errors to false so that I can handle http error responses in my own code and fail more gracefully than Guzzle).


Database Backup Contains Perplexing Number Of Duplicates

It's because (at least for the one table you posted) your table is missing its foreign keys, which is responsible for maintaining uniqueness on their referenced columns.  For example, the asset_files table should have this as part of its DDL:

CONSTRAINT `craft_assetfiles_folderId_fk` FOREIGN KEY (`folderId`) REFERENCES `craft_assetfolders` (`id`) ON DELETE CASCADE,
CONSTRAINT `craft_assetfiles_id_fk` FOREIGN KEY (`id`) REFERENCES `craft_elements` (`id`) ON DELETE CASCADE,
CONSTRAINT `craft_assetfiles_sourceId_fk` FOREIGN KEY (`sourceId`) REFERENCES `craft_assetsources` (`id`) ON DELETE CASCADE

This can happen if the database was imported to a MySQL box that only had MyISAM (which doesn't support foreign keys) and the keys will silently get dropped.

Or we've seen it happen from a failed import/export whether from a script or a MySQL client.

Regardless, you can use this script to try and help restore the missing foreign keys: https://github.com/pixelandtonic/craft-fixfks

Be aware you still might have to do some manual data cleanup from duplicated/inconsistent data.


How to setup assets in multi site where each site should have its own assets?

When you're creating a new local asset volume, you choose a file system path. I use both the site handle and the section handle in the path. For example:

/assets/<SiteHandle>/images/<SectionHandle>

Or, referencing your example (and using 'blog' as a section in your site):

/assets/site1/images/blog

I find that it's important to divide up the assets this way so that if you need to migrate content or backup, it will be much easier to figure out which assets go with which content.

If the sites share images in common (eg. social icons), I usually make a common folder to hold these above the site level in assets:

/assets/common/images

But I ultimately recommend that instead of local storage, you use Amazon S3 Buckets. It's relatively simple to set up and you'll see much better performance from Amazon's CDNs. You can use this same concept outlined for local files on Amazon S3.


How can I record sales data from Stripe Checkout and then restrict access to content based on the item purchased?

My understanding of Stripe Checkout is that it doesn't actually charge the user's card. It simply authorises it, and returns a token which you can then use in a server-side script to capture the payment using the Stripe API.

As such, you'll need a server-side component, in the form of a plugin. Charge might provide a decent starting point for that.

I don't think Charge works with Stripe Checkout as standard, but it's probably worth having a chat with the developer (Joel Bradbury) about the costs of adding this functionality.


Porting from EE - How to filter by category/segment in one template

/work/ecommerce-websites is giving you a 404 because there is no obvious place to route it. See http://buildwithcraft.com/docs/routing for details on how Craft tries to route each request that comes in.

You have 3 options:

GOOD: Create individual templates for each category

I’m not sure why you would want to do that, but it is an option, so I’m putting it here.

BETTER: Create a dynamic route

You can create a new dynamic route that tells Craft to point URLs that look something like “work/(slug)” to the “work” template, or you might be better off just creating a new “work/_category” template so that you don’t have a single template that is responsible for two entirely different types of pages, which is a little weird. (If there are similarities between the work index and a work category page, you should probably just create a new Work-specific layout template that outputs those things.)

BEST: Make these your primary category URLs

You said you have a category group set up, and the second segment is supposed to match one of them. If this is the primary place that you would expect to find info about these categories on your site, then go into Settings > Categories > [your group] and check the “Categories in this group have their own URLs” checkbox, and fill in the “Category URL Formats” and “Category Template” settings like so:

Then, double-click on each of your categories and make sure their Slugs are what you would expect the 2nd segments to be.

Here I’m expecting you’ve decided to create a “work/_category” template as suggested earlier, but if you really want your work index template to be handling these pages you can change the Category Template setting to just plain “work”.

As a bonus with this third approach, you won’t need to fetch your categories manually from the template; a category variable will already be available to the template, so you can go straight to outputting {{ category.title }} or whatever. (See step 4 on http://buildwithcraft.com/docs/routing).

This third technique also applies to sections/entries by the way. I mention that because based on your posted template code ({{ entry.websiteLink }}) it looks like you’re managing entry URLs manually with a custom field, which is really not necessary in Craft. Check the “Entries in this section have their own URLs” checkbox in your section’s settings and Craft will assign a primary URL to all the entries in your section, based on the URL Format you give it.


How could I include another template on a click with ajax?

Primarily, this is a Javascript question, not a Craft CMS question. For the Javascript part of this, I would look for general AJAX tutorials or try searching on Stack Overflow.

But rather than downvote this question as being off-topic, here are some things to help on the Craft CMS side of things.

You can create a template to generate a chuck of HTML you want to include in other pages.

For example, if you create a file called:

/templates/includes/example.twig

You can access that from http://mysite.com/includes/example no matter if it's directly in a browser or thru an Ajax request from another page.

If you need to test wether a template is being accessed directly thru a browser or an Ajax request, you can test that with craft.app.request.isAjax:

{% if craft.app.request.isAjax %}
  Yep
{% else %}
  Nope
{% endif %}

If you'd rather have your Javascript deal with JSON data instead of a chuck of HTML code, you have a few options.

You can name a file with the .json extension and file-based routing will automatically serve that URL as the content type 'application/json'.

/templates/includes/example.json

Or you can use the Element API plugin. This is a much more performant solution, but require some PHP knowledge.


How can I populate a drop-down on the front-end using Sprout Forms?

As of Sprout Forms 2.0, this has become a lot easier.  Hopefully I can win that last answer away from myself!

A few options

First, Sprout Forms 2.0 adds multiple new override options so you may be able to address this problem in a different way now to that will get away from needing to handle this in Custom HTML.  Things to consider:

Template Overrides - If you were using custom HTML because the default templates we're not the right HTML format for your needs, you can now easily override those default templates on a per-form basis.
Rendering Options - If specific attributes of the field such as the ID or Class did not meet your needs, you could potentially dynamically override them while still using a tag like displayForm() or displayField()
Front-end Field API - You could create a custom plugin that adds front-end field support for a custom State Dropdown field.

Custom HTML

If you still feel custom HTML is the best fit for you, there is now a SproutForms_FormModel::getField() method and craft.sproutForms.getEntry tag to help manage retained values and error states.  Here is a generic example.  A more complete examples of all Standard front-end field types can be found in the docs Custom HTML Forms and Example Fields

{# Get our Form data #}
{% set form = craft.sproutForms.form('formHandle') %}

{# Get our Form Entry data to manage error states and re-populating field values #}
{% set submittedEntry = craft.sproutForms.getEntry(form) %}

{# Get our Field Model #}
{% set dropdownField = form.getField('dropdown') %}

{# We use the Twig attribute tag to dynamically access our
     field value on the submitted Form Entry #}
{% set submittedDropdownValue = attribute(submittedEntry, dropdownField.handle) %}

{% if dropdownField is defined %}

  {{ dropdownField.name }}

  <select name="fields[{{ dropdownField.handle }}]">
    <option value="">Select...</option>
    {% for option in dropdownField.settings.options %}

      {% set defaultValue = option.default ? option.value : null %}
      {% set selectedDropdownValue = submittedDropdownValue != '' ? submittedDropdownValue : defaultValue %}

      <option value="{{ option.value }}" {% if selectedDropdownValue == option.value %}selected="selected"{% endif %}>{{ option.label }}</option>

    {% endfor %}
  </select>

  {% if submittedEntry is defined %}

    {# Assumes you have an errorList macro #}
    {{ errorList(submittedEntry.getErrors(dropdownField.handle)) }}

  {% endif %}

{% endif %}


If you're sure that InnoDB is installed and enabled for MySQL on this server, that error can also happen when InnoDB fails to start - for whatever reason. i.e. insufficient disk space, log file size, corrupt data, etc.

Check your MySQL log files for the underlying error.


Control Panel URLs being rewritten to use index.php?p=admin/

With regard to the 2nd part of the original question, whereby no entry, asset, category or user lists were display, this turned out to be a post_max_size issue in the php.ini config. It had been incorrectly set to 64MB rather than 64M.


What's the difference between "is defined" and "is not null"?

is defined - The variable has been defined, and set to any value (or null).

is not null - The variable has been defined, and is specifically not null.

In PHP terms, it's like the difference between is_null() vs. checking whether the variable exists using get_defined_vars() (see this Stack Overflow thread for a little more clarity)

Try this experiment... Without setting myVar, put this in your template:

{{ (myVar is defined) }}

Since that equates to false, nothing will appear in your template. Now change it to this:

{{ (myVar is not null) }}

That will actually throw an error, since myVar was never defined.


To get a specific entry you need to know the id or slug of the entry. If the slug for Chicago is "chicago" (you find the slug in the side panel of the entry edit screen), you can get it like this:

{% set chicagoEntry = craft.entries.slug('chicago') %}

But hardcoding slugs and id's into templates is rarely a good idea. If you explain a bit more what you're trying to achieve, maybe we can provide a more helpful answer.

If you're trying to turn the structure into a menu of sorts, have a look at the documentation for the {% nav %} function, it was made specifically for this.


Element API — Endpoint has an invalid elementType

Your second example has the correct elementType value (Entry::class with a corresponding Entry import at the top of the file). Alternatively you could do

'elementType' => 'craft\elements\Entry',

The error you’re getting in that example is because you changed the endpoint to just news.json rather than api/news.json. So the request isn’t getting routed to this endpoint in the first place.


Turns out... the ID's are wrong. I've listed the shortlist ID's and not the entry ID's. Should use entry.elementId.

Here's the fix:

 {% for entry in list.items %}
      {% set favId = entry.elementId %}
      {% set favIds = favIds|merge([favId]) %}
 {% endfor %}


Getting info on the currently logged in user

Craft::$app->getUser()

returns only the user service/component. You should read the docs about that

What you want is the current Identity

Craft::$app->getUser()->getIdentity()


Save and show card fee for Commerce plugin

I would save the response to an incognito field (or fields) on your order (probably both the entire response and also just the fee separate out).

https://github.com/mmikkel/IncognitoField-Craft

The readonly incognito field is particularly good for this sort of thing - I use a bunch of these fields in a debug tab on my order layout to save useful things.

Just create the fields, add the fields to your order, and you update the values with the usual <input name="fields[fieldName]"> syntax with any cart operation, or use setContentFromPost if you're in a plugin:

    $order->setContentFromPost(array(
        'fieldName' => $creditCardFee,
    ));
    craft()->commerce_orders->saveOrder($order);


Display entries including all locales for XML sitemap

Not sure, but I think the only way is to query for each locale and merge.

{% set siteLocales = craft.i18n.getSiteLocales %}
{% set pages = [] %}
{% for locale in siteLocales %}
    {% set localePages = craft.entries.section('pages').locale(locale.getId).find() %}
    {% set pages = pages|merge(localePages) %}
{% endfor %}

{% for page in pages %}
    {{ page.title}}
{% endfor %}


Sprout Form redirect after submit not working correctly

In Craft 3, Form redirect values must use the hash filter:

<input type="hidden" name="redirect" value="{{ form.redirectUri|hash }}">

It's mentioned in passing in the docs here.

Without that hash filter, you'll get redirected to the home page as you are experiencing.


List child categories which have entries based on the current categories

Use the descendantOf parameter to select just the subcategories, then run an entries query to check if that category has any entries assigned to it.

    {# loop through the subcategories #}
    {% for subCategory in craft.categories({
        groupId: 2,
        descendantOf: parentCategoryObject,
        orderBy: 'title'
    }).all %}
        {# check if this subcategory has at least one entry assigned to it #}
        {% set subCatEntries = craft.entries({
            section: 'blog',
            relatedTo: subCategory,
            limit: 1
        }) %}

        {# display a link to the subcategory page if entries are assigned to it #}
        {% if subCatEntries|length %}

{{ subCategory.title }}

        {% endif %}
    {% endfor %}

You'll need to provide the parentCategoryObject yourself based on however your templating works.


New user registration activation timeout?

The verificationCodeDuration config setting is what you're looking for.  Defaults to 24 hours.


Upgrade to 3.0.0 RC1 failed due to 504 Gateway Time-out

Updated using composer update craftcms/cms


MAMP isn't really tuned for performance either. And also keep in mind Time to First Byte is not the only indicator of a fast website. You should consider overall perceived time and actual download time as factors as well.

CloudFlare talked about one aspect of this on their blog... for example: with Gzip compression, the web server has to wait while it compresses the output then send it along. That adds to your TTFB. So on first blush, gzip compression would appear to be a bad thing but in reality, your overall download time and file size shrink, and as a result, it's an easy win.

If your content doesn't change all that much, when you get your Craft site up live, you might also want to consider caching on the server level as well, either with Nginx (fastcgi_cache) or something like Varnish in front of Apache. Those layers add complexity (e.g. when and how to clear the cache?) but it'll get you super fast output if that's your goal.


List all entries in a section filtered by given category groups

I would use the without filter and relations for this.

{# starting points #}
{% set externalCategory = craft.categories.slug('external-content').first() %}
{% set allEntries = craft.entries.section('webdev').find() %}

{# create the arrays/objects you need #}
{% set externalEntries = craft.entries.section('webdev').relatedTo(externalCategory).find() %}
{% set otherEntries = allEntries|without(externalEntries) %}

then use the usual for loops for each array / object you have created. That way, you only need to define your external-content category, all the rest is automatic, regardless of the number of other categories you have.

Depending on the number of entries you have and the kind of traffic you get, you might want to consider caching this.


How can I set live preview's minimum interval?

If you're referring to the time it takes between you click the "Live Preview" button and the time the actual Live Preview pane shows up, then that's currently not configurable in Craft.

Might be worth adding to the feedback site, though.


Any examples of Craft Commerce checkout process for PayPal or any other gateway?

Craft Commerce ships with a templates/shop folder that has a working check-out processes using the Dummy gateway adapter and some default products that get populated during installation.

After installing it, you'd access it by going to yoursite.com/shop.  You can use a test credit card number like 4222222222222 to complete checkout and convert a cart to a completed order.


This turned out to be an issue with a misconfigured Google API key.
When setting up your Google API keys, make sure that:

Your domain is whitelisted (including any staging servers).
Your keys have granted permission to the necessary functionality.

Be sure to read the full instructions for how to set up your Google API keys.


Override the postDate for entries so their URL works on the frontend?

You can add status(null) in your ElementQuery in order to fetch all items or you add status(['pending', 'enabled']) to pull all entries, that are not disabled and not expired


How do I target the second item in an array with Twig?

You can use the slice filter but it will return an array, so you either have to loop the result or access the first index

{% for item in array|slice(1, 1) %}
    {{ dump(item) }}
{% endfor %}


Organize filtered entries by a specific category

You should be able to order them using a combination of the order method (if needed) and group twig filter.

{% set productList = craft.entries.(params).order('title')|group('myCategoriesField.first().title') %}

The problem here is that the products might end up being displayed in the order that the size categories were created (i.e. postDate) and not the category 'size' title. If this is a problem then your solution may in fact be the only way. Have a look at this question for alternative answer and discussion of some of the issues.


twig for loop put every 2 elements in a new container

I usually do this like so:

{% for block in blocks %}
  {% if loop.index0 % 2 == 0 %}

  {% endif %}
   {# other stuff #}
  {% if loop.index0 % 2 == 1 or loop.last %}

  {% endif %}
{% endfor %}

Or, more generally,

{% set cols = 2 %}
{% for block in blocks %}
  {% if loop.index0 % cols == 0 %}

  {% endif %}
   {# other stuff #}
  {% if (loop.index0 % cols == cols - 1 or loop.last) %}

  {% endif %}
{% endfor %}


How do I find the closest parent entry with an Assets field filled in?

You can get your entry's parent entry with getParent(). Use this entry method in a conditional, if your entry has no hero image set.

You can nest the code to climb up all of your structure's levels:

{# Check if entry has hero image #}
{% if entry.hero.first() %}
    {{ entry.hero.first().url }}
{% else %}

    {# Check the parent entry #}
    {% if entry.getParent().hero.first() %}
        {{ entry.getParent().hero.first().url }}
    {% else %}

        {# Check the entry 2 levels above #}
        {% if entry.getParent().getParent().hero.first() %}
            {{ entry.getParent().getParent().hero.first().url }}
        {% else %}

            {# ... Oh no, we're not finished yet :( #}

        {% endif %}

    {% endif %}

{% endif %}

Yes, that's not good code. That's why I recommend to use the same technique in a macro, that you can call recursively:

{% macro showHero(thisRecursionEntryModel) %}

    {% import _self as self %}

    {# Check if entry has hero image #}
    {% if thisRecursionEntryModel.hero.first() %}
        {{ thisRecursionEntryModel.hero.first().url }}
    {% else %}

        {# Check the entry's ancestors recursively #}
        {% if thisRecursionEntryModel.getParent() %}
            {{ self.showHero(thisRecursionEntryModel.getParent()) }}
        {% endif %}

    {% endif %}

{% endmacro %}

{% import _self as self %}
{{ self.showHero(entry) }}

You can also import the macro from a file, if you want to use it in more than one template file or just like your code to be modular:

{% import '_includes/macros.html' as macros %}
{{ macros.showHero(entry) }}


I'm not sure if this is the intended way, but I rigged this up and so far it works well.

{% set yankee = craft.amForms.getForm('hotel') %}

{% macro foxtrot(errors) %}
    {% if errors %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import foxtrot %}

{# list of form errors #}
{% if hotel is defined %}

        {% set fields = yankee.getFields() %}

Please correct the errors listed below before submitting the form.

            {% for field in fields %}
                {{ foxtrot(hotel.getErrors(field.handle)) }}
            {% endfor %}

{% endif %}


I'm glad you identified and resolved the issue!

I stumbled across this post because I had the same GUI response/result in Craft CMS and want to share how I resolved it for others that may have the same issue without being a firewall problem.

See my answer here


It's actually not SQL friendly at all to store multiple values (Title and Video ID) in a single column. The data is stored as a serialized string and all you can do is to use the pattern matching operator LIKE to get the row you're after.

For best performance you should refactor your fields and store each of them individually. If all the data has to be in one field, store the field in its own table (like Matrix fields do).

If this is no option for you, I would recommend to not use the search parameter with your ElementCriteriaModel, but to prepare a DbCommand object using buildElementsQuery and add your "Video ID condition" using the LIKE operator I mentioned above, so you don't rely on up-to-date search indexes.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'video';

$query = craft()->elements->buildElementsQuery($criteria);
$params = array(
    ':video_id' => '%video_id='.$video_id.'%',
);
$query->andWhere('entries.video LIKE :video_id', $params);
$result = $query->queryRow();

return EntryModel::populateModel($result);


Multi-site Live Preview not working in Craft 3

Update

This has been implemented for the upcoming Craft 3.1 release.

Currently Live Preview will only work across sub-domains (i.e. site1.domain.com and site2.domain.com), not completely different domains (site1.com and site2.com)
 Here's a guide on how you'd set that up: https://craftcms.com/guides/using-live-preview-across-multiple-subdomains

In order for it to work across completely different domains, https://github.com/craftcms/cms/issues/1521 will need to be implemented.


Set Structure Parent when creating Entry in Plugin

This question is old, but the solution is:

// look up parent with a ElementCriteriaModel

$parentCriteria = craft()->elements->getCriteria(ElementType::Entry);

$parentCriteria->search  = 'slug:'.$parentSlug; // whatever you have

$parent = $parentCriteria->find()[0];

$entry = new EntryModel();
$entry->sectionId = $section;

$entry->parentId = $parent->id;

...


Including block templates under different subdirectories

It could get unwieldy if you have too many subfolder options, BUT... You CAN supply a list of templates to Twig's include tag. Twig checks each option, and includes the first template in the list that exists:

{% include
   [
    '_widgets/_images/_'  ~ block.type,
    '_widgets/_mockups/_' ~ block.type,
    '_widgets/_text/_'    ~ block.type,
    '_widgets/_special/_' ~ block.type
   ]
   ignore missing
%}

(The ignore missing tells Twig to fall back to rendering nothing if none of the templates exist. Otherwise it would throw an exception. A popular alternative is to have a default fallback template as the last item in the list.)

Bonus 2¢: I think it's good practice to keep include templates in hidden folders (i.e. _widgets/ instead of widgets/) — to signify to yourself and others that the directory does not match with a public route, and that its contents are never meant to be displayed directly.


Less complicated local development w/Craft 3, is it possible?

If you're used to Local you can also use that for Craft.

Here's 2 articles to get you started:

https://medium.com/@madebyraygun/a-quick-and-easy-local-environment-for-craft-3-4fd7c7ff5815

and

https://www.tyssendesign.com.au/articles/craft/using-local-by-flywheel-with-other-cms/

I'm also hearing good things about https://ddev.readthedocs.io/en/stable/
but haven't tried that one myself.

And it looks like Pixel and Tonic have developed something of their own: Craft Nitro

https://craftcms.com/blog/craft-nitro


Having arrived here from a Google search while trying to do this in Twig rather than PHP, I thought it might help someone in future to leave an answer, even though it doesn't address your question directly:
{{ item is instance of('craft\\elements\\Entry') ? 'This element is an entry!' }}
{{ item is instance of('craft\\elements\\Asset') ? 'This is an asset!' }}
{{ item is instance of('craft\\elements\\Category') ? 'This is a category!' }}
{{ item is instance of('craft\\elements\\User') ? 'This is a user!' }}

I find this especially useful in, for example, internal keyword search results listings templates, where the elements that were found might be of different types and you want to take different actions depending on the types.


I want to get the HTML/text contents of the Redactor editor

I'm not 100% sure I follow, but I think this is what you are looking for.

In your javascript file, you'll want code.set

API Reference

...

$('#yourTextArea').redactor('code.set', your.data);


Import Plugin on localhost Craft 2 crashes

This could be a PHP memory limit issue but it's hard to say until you get access to the log files or can output the error to the browser instead of a blank page.
I would first make sure devMode is enabled in Craft. Then I would look at the log files in storage/logs/web.log or storage/logs/php-errors.log. There might be a lot of stuff logged already, so sometimes it's easier to delete everything in logs and then redo the import and see what errors were logged.


How to limit number of entries to a given user/user group

You might want to take a look at this

Your condition will be

$author = Craft::$app->getUsers()->getIdentity();
$numberOfEntriesByUser = Entry::find()->sectionId($entry->getSection()->id)->authorId($author->id)->count();
if($numberOfEntriesByUser){
    $event->isValid = false
}

You should make sure the author is not an admin or Craft::$app->getRequest()->getIsCpRequest() is false otherwise you won't be able to save new entries as well.

Keep in mind to check for a current user as well. There won't be a user for cronjobs / other public post request


There's a Craft 3 port of Category Sources in the v2 branch for the repo. It doesn't appear to be published to Packagist and the Plugin Store, which means you'll need to add the URL for the plugin's Git repository to your project's composer.json file in order for Composer to find it.

Add the following to the root of your composer.json file:

"repositories": {
    "craftcms/category-sources": {
        "type": "git",
        "url": "git@github.com:pixelandtonic/CategorySources.git",
        "trunk-path": "v2"
    }
}

You might also need to add the following to composer.json:

"minimum-stability": "dev",
"prefer-stable": true,

Then, you can do composer require craftcms/category-sources to actually download the plugin.

Note: I haven't tested this plugin myself, and the fact that it isn't released probably means it's not completely ready for primetime (it might not even work at all, with recent versions of Craft 3). Proceed with caution; you might also want to get in touch with Pixel & Tonic to hear if the plugin is likely to get a proper release anytime soon.


Craft 3 PHP

$transforms = Craft::$app->getAssetTransforms()->getAllTransforms();
foreach($allTransforms as $transform){
    echo $asset->getUrl($transform->handle);
}

Craft 3 Twig

{% set allTransforms = craft.app.getAssetTransforms.getAllTransforms() %}
{% for transform in allTransforms %}
    {{ asset.getUrl(transform.handle) }}
{% endfor %}

Craft 2 PHP

$allTansforms = craft()->assetTransforms->getAllTransforms();

Craft 2 Twig

You'll need a plugin for this because you don't have access to that component

{% set allTransforms = craft.pluginHandle.getAllAssetTransforms %}

And in your PluginVariable

public function getAllAssetTransforms(){
    return craft()->assetTransforms->getAllTransforms();
}


How to strip out src="" value with twig from iframe code

You could write a module that adds a twig extension to return the value of src from the string. That way you get to utilise PHP as per https://stackoverflow.com/questions/17017684/how-to-get-url-from-the-iframe-using-php to get the value.

https://pluginfactory.io/ is a good starting point for adding a module to Craft.

alternative very dirty approach: If the iframe markup is always going to be the same, you could do |replace(), replacing everything before the src=" and everthing after the " width with empty strings. Then replace " width with an empty string.


How to search for a specific field using getCriteria()?

As per the (new) "Working with Elements" guide from the docs, it works the same as from your templates.

  The actual list of available parameters depends on the element type. They are identical to the parameters available to your templates.

So this template example:

{% craft.entries.section('news').myPlaintextField('xyz').myLightswitchField(1) %}

Works from your plugin like so:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section            = 'news';
$criteria->myPlaintextField   = 'xyz';
$criteria->myLightswitchField = 1;

Using custom field parameters is a fast and reliable solution if you are looking for EXACT matches. I would only use the search parameter if there's no other solution.


Is it possible to return a User Model Entry or userid from a successful registration form submission?

In your redirect hidden input in your form, add an {id} tag like so:

<input type="hidden" name="redirect" value="nextStep/{id}">

And that will be populated with the newly created user's userId.

  Is there a corresponding getNotices() similar to getErrors() or some way to retrieve these on the front-end?

You'd have to duplicate the code that the control panel uses to retrieve the notices on the front-end of the site.


How do I reference the settings of my plugin from a template?

In more recent versions of Craft 2.x (I forget when it was added), you can simply do this without needing a plugin:

craft.config.get('setting', 'plugin')

Where 'plugin' is the name of your plugin's config file (sans .php).

If you want to do this in Craft 3, you'd do:

craft.app.getModule('pluginHandle').getSettings().mySetting


In a large set of entries across multiple sections, how can I loop through each section type in the set?

Try using the group filter

{% set entries = craft.entries.search(query).order('score') %}

{% for sectionName, sectionEntries in entries | group('section.name') %}

{{ sectionName }}

        {% for entry in sectionEntries %}

{{ entry.title }}

        {% endfor %}

{% endfor %}


field from category not available via craft.categories

Because your category variable is no object of type craft\elements\Category but an ElementQuery in order to fetch the category you need to use the one() function

{% set category = craft.categories.slug(filter).one() %}
{% if category != null %}
    {{ category.titleTag }}
{% endif %}

Your {{category.titleTag}} printed the search criteria. Imagine you would like to set other conditions in your query: how is Craft supposed to know when your query ends?


The docs here are what you need: https://docs.craftcms.com/v3/config/app.html#memcached-example

Which is 99% exactly what Yii uses (since they have an example of using multiple servers): https://www.yiiframework.com/doc/api/2.0/yii-caching-memcache


Image Transform in template 'Auto' errors

This was an error in the docs. You get the automatic format assignment by default, no need to explicitly set format: 'auto'.


How Do I Restart an Entries Loop Once It Hits the Last Entry

You can repeat a loop with another for loop.

For example, here's a loop that repeats 15 times:

{% for i in 1..15 %}
    Loop: {{ i }}<br>
    {% for entry in block.homeClientQuote %}
      ...
    {% endfor %}
{% endfor %}

You can also use the i variable if you need to change the output depending on the loop number.

{% if i > 10 %}{% endif %}


Get Entries That Match ALL of the tags specified

Short version
change the title into an id and it will work
{% set entries = craft.entries.section('journalArticles').relatedTo(
    'and',
    { targetElement: >>idOfYourElement<< },
    { targetElement: >>idOfYourElement<< })
%}

Long version
It looks a little bit nasty (I never do these kind of things in twig because I don't like the syntax and prefer PHP for many reasons) but here you can see a working example for a twig search form
first your html: it could be like this
<form>
    {# loop all your tags and display a checkbox for each one #}
    {# Important: insert the id of your tag as value not the title #}
    {% for tag in craft.tags.group('default') %}
        <input type="checkbox" name="selectedTags[]" value="{{ tag.id }}">{{ tag.title }}

    {% endfor %}

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

And your twig
{% set isSubmitted = craft.request.getParam('submit') %}
{% if isSubmitted %}
    {# get all selected input ids #}
    {% set allRelatedTags = craft.request.getParam('selectedTags') %}

    {# proceed only if the user selected at least one tag #}
    {% if allRelatedTags %}
        {# build your related to array #}
        {% set relations = ['and'] %}

        {# inlcude an additional 'targetElement' for each selected tag #}
        {% for tag in allRelatedTags %}
            {% set relations =  relations|merge([{targetElement: tag}])%}
        {% endfor %}

        {# search for entries with the related parameters #}
        {% for entry in craft.entries.relatedTo(relations).find() %}
            {{ entry.title }}

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

The reason why your code did not work is quite simple as you can see in the relatedTo documentation

In its simplest form, you can pass in one of these things to it:
An AssetFileModel, CategoryModel, EntryModel, UserModel, or TagModel object
An element’s ID
An array of element objects and/or IDs

you inserted the not unique title which could be everything. So all you have to do is to insert the id of your element instead of the title... that's it


How do I query for orders that were completed between two dates?

It looks like I figured it out by doing this:

.dateOrdered('and', '>=' ~ startDate, '<=' ~ endDate)


How Can I Output Only the First Word of the Title of an Entry in a Template?

Yes, you can do this with Twig alone. Here's how:

{{ entry.title|split(' ')|slice(0, 1)|join }}

This series of Twig filters:

Uses split to turn the title into an array, splitting on spaces.
Passes that array through slice to grab the first item in the array.
Then uses join to turn the array back into a string for output. The array is now just one item (the first word of the title), but join is needed because Twig doesn't want to treat an array as a string.


Preview function for different devices, screen sizes and screen
  configurations(portrait/landscape)

Yes it has live preview. However this isn't per device. You can open the entry with a secret url and then user your browser tools to check different devices

  Is it possible to publish only a subset of my website?

Yes, each entry can be turned on or off

  Is lazy loading supported? E.g. loading images on scrollto? Does a
  frontend created with Craft CMS use much .js code? Can I minimize the
  amount of .js code (for performance reasons)? Is mobile first approach
  supported? Are URLs SEO-friendly?

Yes, it's all how you code it. You can do whatever you want. Craft makes no assumptions or requirements

  Can I integrate Onsite-Banners from external Ad servers?

Yes code as you want

  Does the cms contain Digital Asset Management? Which media file types
  are supported?

Yes, full list here:

  Is there any REST API provided? Does the CMS internal search engine
  support synonyms and how about the error tolerance?

I'm not sure

  Can I login to the CMS on mobile devices? Do I have good usability
  when doing so?

Yes you do. I've done this myself and it was easy to move around

  Do I upload high resolution images and later on these are generated
  and maybe compressed for target devices?

Yes you can and then you can set transforms to crop/resize/compress as you want. Targetting per device that all depends on your html.


Do you only need the HTML labels in the Control Panel?
I tried it for a short time and found this solution.

Install doublesecretagency/craft-cpjs.

Add this snippet into the editor of the plugin.

var $labelReplaceElements = document.querySelectorAll('#fields th > a, #fieldlayoutform .fld-field > span, .field > .heading > label[id]');
Array.from($labelReplaceElements).forEach($element => {
    $element.innerHTML = $element.innerText;
});

You should be careful, that only admins can change fields because this solution brings an XSS risk with it.

The disadvantage is that the labels are first displayed as HTML and only after the JavaScript has been executed are they displayed correctly.


How do I publish entries with a specific category id?

You can pass in a CategoryModel to the relatedTo parameter, so its just a matter of getting the CategoryModel you're after. Something like:

{% set category = craft.categories.id(42).first %}
{% set entries = craft.entries.section('blog').limit(3).relatedTo(category) %}


You could eager load a little more to speed things up. Especially your eventVenueName and eventCity

For your query, try:

{% set entries = craft.entries ({
        section: 'events',
        limit: '30',
        order: 'postDate desc',
        with: [
            'eventMediaTile',
            'eventVenueName',
            'eventCity'
        ],
        relatedTo: category }) %}

Then in your _card do:

    {% if entry.eventPercentageSaving > 0 %}

{{ entry.eventPercentageSaving }}% Off

    {% endif %}

    {% set cardImage = entry.eventMediaTile[0] ?? null %}
    {% if cardImage %}

    {% endif %}

{{ entry.title }}

{{ entry.eventVenueName[0].title ?? 'N/A' }}, {{ entry.eventCity[0].title ?? 'N/A' }}

From £{{ entry.eventMinimumPrice }}

If you turn the debug toolbar on your front-end (under your user's preferences) before implementing, and look at the query count, you should see a significant drop.

If this isn't enough, you could start caching. Andrew has a great article on this.


Is it possible to have lowercase globals?

If you have a global set named globalSet, and a plain text field in that set named textField, and the value you enter is Eng, then {{globalSet.textField}} will output Eng

Things that could be going wrong:

caps-lock: Did you enter ENG in the field in the first place?
|upper: {{globalSet.textField|upper}} will output ENG
CSS: text-transform: uppercase;
jQuery: $("*").text($("*").text().toUpperCase()); (or other jQuery)
all caps font
translations: {{globalSet.textField|t}} and a translation file with "Eng" => "ENG"

[edited to fold in suggestions from the coments - Marion]


Installation stops halfway. Files not found and internal server error 500

The log file got me on my way after a tip from Brad Bell:

  'CDbException' with message 'CDbCommand failed during the SQL statement: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'craft_assetfiles' already exists' in ...craft/app/framework/db/CDbCommand.php:358

Removing the database and doing a fresh install solved the issue.


How to structurize a multi-project documentation site?

Welcome to the Craft community. You try to create a new section for each project - right? In my opinion this is only necessary if you need different view and edit rights on each project. If you'r creating a "open for all" project documentation tool (open means for only one user group), than i would go with a single section. It's much easier to manage and starting with a new project. I would use two entry types in the section (https://craftcms.com/docs/sections-and-entries#entry-types). One entry type is for the project and one is for your chapters and the content.

    Example:
    1x Section called "projects"
        1x entry type called "project" with following fields (example)
            - name
            - project description (rich text field)
            - project team (user field)
            - release date (table field with date and description)
            - ...

        1x entry type called "chapter" with following fields (example)
            - name/title
            - content (richt text field)
            - images (file field)
            - documents (file field)
            - ...

    Finaly you "project" section would be like this:
    Project 1 (entry type "project")
        - Chapter 1 (entry type "chapter")
           - Chapter 1.1 (entry type "chapter")
           - Chapter 1.2 (entry type "chapter")
        - Chapter 2 (entry type "chapter")
           - Chapter 2.1 (entry type "chapter")
           - ...
        - Chapter ...

    Project 2 (entry type "project")
        - Chapter 1 (entry type "chapter")
           - ...

For creating the dropdown-navigation, you can simple use the nav tag (https://craftcms.com/docs/templating/nav). Instead of a use option tags for output:

{% set entries = craft.entries.section('projects').level(1) %}

<select id="nav" onchange="if (this.value) window.location.href=this.value">
    {% nav entry in entries %}
        <option value="{{ entry.url }}">{{ entry.title }}</option>
    {% endnav %}
</select>

For the subnavigation you could take a look on this Craft recipe -> https://craftcookbook.net/recipes/fully-dynamic-hierarchical-nav-menu-template.

Other solutions:
Depending on how many content is used in each chapter, you could also make use of a matrix fields for your content...

Doe's this make sense for you?


Was out of town so couldn't answer this question until now. With Google Maps for Craft you can do so like this:

{% set marker = entry.yourMapField.getMarker(0) %}

{{ marker.lat }} {{ marker.lng }}

Or you can loop through all the markers on the map like this:

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

    {% for marker in entry.yourMapField.getMarkers() %}

        {{ marker.address }}<br>

    {% endfor %}

{% endfor %}

https://github.com/objectivehtml/Google-Maps-for-Craft/wiki/Getting-Address-From-Map-Markers


Getting a 'ReflectionException' error, "Class modules\Module does not exist' when I change the namespace of my module in Craft 3

It's a bit difficult without seeing all of your code, but I'm going to guess that you also need to make changes in your config/app.php to make the namespace changes you're making.

So two things I'd recommend... first, you can generate your module's framework here: https://pluginfactory.io/

...and second I wrote up a tutorial on creating a module in the Enhancing a Craft CMS 3 Website with a Custom Module article.


How do I exclude a Channel, Structure or Singles from search?

This should work for a single section:

{% set entries = craft.entries.section('not news').search(query).order('score') %}

to exclude more sections:

{% set entries = craft.entries.section([
    'and', 'not news', 'not blog'
]).search(query).order('score') %}


Why are my profile pages not generating which I click on 'submit'?

Try setting the action and redirect as hidden inputs, see below:

<form method="post">
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="/profile/{{ currentUser.username }}">


How can I show the child category and not it's parent - but other times show it's parent?

You can change the sort order in your CategoryQuery

{% set child = entry.getFieldValue('servies').orderBy('level DESC').one() %}

returns the category of the deepest level -> the child. If no child is selected you'll receive the parent


What's the difference between using single and double quotes in strings?

There is a small difference, single-quoted strings don't support interpolation:

{% set string = 'There is a #{car}.' %}

The above example won't work. If you want to use it, you need to wrap your string in double quotes:

{% set string = "There is a #{car}." %}


Craft Commerce 3 Decrease line Item qty by one?

Try just POSTing the new absolute quantity you want to change to - e.g. if you have 5 in your cart and want to decrement by one, you'd POST something along these lines:
{
    "redirect": "6bb2a73aac3479c68e0946e4455624e2c1b840bc2b6356074a51ba01ee1234d/cart",
    "action": "commerce/cart/update-cart",
    "lineItems[82503][qty]": "4",
    "lineItems[82503][options][note]": ""
}

That's what we do, and it works.
Result:
{
    "lineItems": [
        {
            "id": 82503,
            "weight": 0,
            "length": 0,
            "height": 0,
            "width": 0,
            "qty": 4,
            "note": "",
            "privateNote": "",
            "purchasableId": "5115",
            "orderId": 145817,
            "lineItemStatusId": null,
            "taxCategoryId": 1,
            "shippingCategoryId": 1,
            "dateCreated": "2020-10-29T11:55:02+11:00",
            "dateUpdated": "2020-11-25T11:34:47+11:00",
            ...etc
}


You can grab the handle of an element that has different types (entries, matrix) with getType()->handle for example:

$handle = $entry->getType()->handle

In your case

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->relatedTo = array(someCoolId, anotherCoolId);
$relatedStories = $criteria->find();
foreach ($relatedStories as $block){
    $handle = $block->getType()->handle;
    switch ($handle){
        case 'foo':
            break;
    }
}

Edit:

Not sure what you mean exactly so I'll just insert some random code parts until something is correct.

// get the parent element -> the owner of that block.
$parent = $block->getOwner()

// get the field that relates both elements
$field = craft()->fields->getFieldById($block->fieldId);
$fieldHandle = $field->handle;


Every criteria model in Craft 2 has a limit set to 100 by default. You can override it by setting a limit parameter on the model.

{% for block in entry.supporters.type('individuals').order('firstName').limit(null) %}


Adding a new site returns 503 Service Unavailable

System status was disabled, enabling it solved the problem.

Now I'm not sure if this is the expected behavior, what threw me off was that I could still preview the primary site. I'm guessing on multi-site installs it's best to disable at the site level rather than the system level.


Central Craft CMS management for agencies

To your first problem there is a plugin to handle Single-Sign-On here: https://plugins.craftcms.com/saml-sp I've used it successfully with Azure AD, it will be expensive for 60 sites, but perhaps it's worth talking to flipbox factory

On the updates side, there is a plugin that will notify you by slack or e-mail when something needs updating: https://github.com/lukeyouell/craft-updatechecker


Problems with Craft CMS development strategy

I do not know where your problem is? In Wordpress, you can build pages with CustomFields, and I think the same with Drupal.

Because you will have the same problem when Devs delete fields and play on the live system, the content is missing or the frontend error generated.

Therefore, it is simply forbidden to simply delete fields, they do the same nevertheless is not the CMS to blame, then that is Human Failure.

If you are familiar with the principle of the ContentBuilders (no static backend masks), then you would not get far with field configurations with YAML or JSON, then the editor determines which fields he needs for each article individually.

I'm not sure if it's so much performance gain when you put the fields into the filesystem, because Craft has to double into the filesystem for the representation of a field in the backend (general fieldstyle, the field configuration) and then into the database To pick up the content.

Craft 2 is fast, Craft 3 is even faster. Anyone who builds fixed fields does not have to worry about the backend performance.


How to import existing users into database

You can use an existing import/export plugin that supports handling users, or you can write your own plugin that calls Craft's UsersService->saveUser(), which takes care of saving the right data into the right tables in the database.


Does anyone have a working example of frontend form with multiple file upload, drag & drop etc?

OK, figured it out (or at least it works, so correct me if a better way is available):
This method assumes logged in frontend users, not sure if it's possible for guests, have not tested that. Might give permission errors.
Let's say, we have a section message with id 2, containing an asset field called photos. This is the field in which we want to save all frontend uploaded images.
In your form template, do everything exactly as this doc page says. Beware of the fact that you're own fields input names should start with 'fields[myFieldHandle]', and default fields such as title and author should just have their handle as input name.
Also, make sure your form has enctype="multipart/form-data" in its tag. What you have now, should look like this:
<form action="" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="action" value="entries/saveEntry" />
    <input type="hidden" name="sectionId" value="2" />
    <input type="hidden" name="enabled" value="1" />

    <input type="file" name="assets-upload" multiple />

    <input type="submit" value="Make it work!" />
</form>

You'll notice that the file input field has 'assets-upload' as its name. You can either do this, or make your uploading mechanism change the field name to 'assets-upload' for you, because Craft assumes this name in the controller class you're about to use.
For my form, I used the excellent Jquery File Upload plugin, which starts to do its work once files are selected in the file input field. I'm sure any other plugin could do the same. Make sure the plugin uploads the files to Craft's assets/uploadFile controller for them to be processed. The only thing this controller needs, is a folderId (the id of the asset folder the assets should be copied to). So, this is what the upload plugin needs:
$('#assets-upload').fileupload({
    url: '{{ url(actions/assets/uploadFile) }}',
    dataType: 'json',
    formData: [{ name: 'folderId', value: yourfolderId}],
});

By now, you should be able to have your plugin send one or more assets to Craft's controller. Use firebug or Chrome's devTools to see what is returned. If everything worked as it should, a json-string should be returned containing the fileId(s) of the uploaded file(s).
The only thing left to do then, is creating hidden input fields to tell Craft which assets to relate to this entry. What JavaScript should append to the form, is one or more instances of:
<input type="hidden" name="fields[photos][]" value="yourFileId" />

Example, using the 'done' callback function in JQuery File upload:
...
done: function (e, data) {
    if(data.result.success) {
        var fileId = data.result.fileId;
        $(this).after('<input type="hidden" name="fields[photos][]" value="' + fileId + '" />');
    }
},
...

Submit your form, and see if it works. It should. If not, use the errors Craft returns to solve your problems (quite possibly permission-related).
Final note: My asset field is set to create a different file folder for each entry. In this case, I created a temporary folder and used its ID in the frontend form (because the folder is only created once the entry is saved). Craft will copy the assets to the right place and clean out this temp folder on saving the entry.


What is the current landscape regarding e-commerce plugins for Craft?

E-commerce Master List

This is a compilation of all publicly available solutions. Other answers here describe each plugin in greater detail... This is simply a complete list of every known option.

Listed in alphabetical order (not by popularity or preference)

1st party plugin

Craft Commerce (see more info below)*

3rd party plugins (built exclusively for Craft)

Charge
Sprout Commerce (in private beta)

3rd party services with official Craft plugins

FoxyCart (integration notes)
Snipcart

3rd party services with unofficial Craft plugins

Moltin
Shopify
Snipcart

DIY custom solutions (via an API)

Moltin
PayPal
Stripe

  * Craft Commerce was formerly known as "Market Commerce" (aka "Cellar Commerce"). The name was changed after the plugin (and its developer, Luke Holder) were acquired by Pixel & Tonic.