Plugin DB migration add "not null" column

This looks like it could be a Yii issue, if a rather occluded one.

Here's how it is in another framework: MySQL TINYINT(1) columns are always interpreted as booleans #3506

And here is a pointedly uncertain link with link, on a quite confused Yii discussion circling around this: It is already documented that tinyint(1) would be treated as boolean

I don't think it is actually doc'd so -- actually it's the other way around. But doc may not tell all.

I would suggest making the def tinyint(2) and see if it cures...good fortune...


How do I setup my Element Types Sources for deep linking?

Your plugin has to create those routes — via registerCpRoutes() — to match your desired URL structure.

Routes either trigger a site template or a controller, as described in the Routing docs. (Craft's own internal convention is for CP routes to trigger a controller method, which sets up the request and renders your desired template.)

You can look at Craft's own CP routes for inspiration in setting up your own; they're defined in /app/etc/config/common.php.


Changing the "homepage" url for logged-in users

Sure, something like this should work (untested):

Home

The above should create an absolute URL to whatever's in your postLoginRedirect config setting, relative to your siteUrl.

Note that if you want an URL relative to your Control Panel (e.g. "dashboard"), you'll want to use cpUrl() instead, i.e.

Home


How to list entries related to a category + related to a section?

When you call this:

craft.entries({section: 'games'}).relatedTo(category).relatedTo(craft.entries.section('reviews'))

that second relatedTo param is just overriding the first one. Lucky for you, that parameter does accept multiple criteria (see the “Passing Multiple Relation Criteria” section on http://buildwithcraft.com/docs/relations#the-relatedTo-param).

{% set games = craft.entries({
    section: 'games',
    relatedTo: ['and',
        category,
        craft.entries.section('reviews').status(null)
    ]
}) %}

It's a good idea to specify that category will be a target element (where the Games entries did the selecting), and that the Reviews will be source elements (where the Games were selected by the Reviews), as this will slim the DB query down a bit:

{% set games = craft.entries({
    section: 'games',
    relatedTo: ['and',
        { targetElement: category },
        { sourceElement: craft.entries.section('reviews').status(null) }
    ]
}) %}


Do I need a plugin to load entries via AJAX?

There is a new RESTful plugin which might be what you need: Rest-Easy from Wes Rice.
But you could also make use of Twig's extends functionality:

_ajax.html:

{% block ajax %}
    { success: false }
{% endblock %}

entry.html:

{% extends craft.request.isAjax ? "_ajax" : "_main" %}

{% block ajax %}
    { success: true }
{% endblock %}

{% block normal %}

Normal entry

{% endblock %}

If you request entry.html via ajax, the template will extend _ajax.html instead of _main.html, and show your json data. In this example _main.html would be your normal layout-template.

Note: Don't forget to set the XMLHttpRequest in your ajax call.


Can I output custom or specific data (Not related to an elementType) on Element API?

Indeed as @robin pointed out, I couldn't figure out a nice way to making custom data outputs with Element API (Not related to a ElementType, like available Sites/Languages or available sections). What I did was:

I created a custom module, in this module I was able to register routes like:

        Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
            function (RegisterUrlRulesEvent $event) {

                $event->rules['api/languages'] = '/endpoints/endpoints/languages';
            }
        );

And in the action of the module. (Still is a rough version, also needs to handle possible errors and that kind of stuff)

public function actionLanguages()
{
    $sites = Craft::$app->getSites()->getAllGroups();

    $languages = Craft::$app->getSites()->getSitesByGroupId($sites[array_search('Languages', $sites)]['id']);

    return $this->asJson($this->formatApiResponse($languages));
}

I don't know if it's the nicest way (Still open to suggestions) but this gave me the freedom I needed to enhance my Element API end-points.


Setting absolute path to asset files for Craft 3 multisite

Found out the answer on how to get all my sites on Craft 3 to share one image folder. So you have to set your base url for all your site to your original site's base url.

Then in your code, you just put {{ siteUrl }} before your image url. Kind of confusing since siteUrl is actually the Base Url in the dashboard.


How to add multiple performers to event schema with seomatic

I hadn't seen those examples but it is bookmarked now.

I've adapted your example as below and it's all working. Thanks @andrew.welch

{% set performersArray = [] %}
{% for block in entry.performers .all() %}
  {% set performersArray = performersArray | merge([seomatic.jsonLd.create({
      'type': block.performerType,
      'name': block.performerName,
  }, false)]) %}
{% endfor %}
{% do mainEntity.performer(performersArray) %}


Force redactor to only display HTML editor view

I don’t think it’s possible at all and what’s the benefit of using a WYSIWYG field at all when you don’t use any of the features.

I’d rather use a plain text field or even better, a field type which is optimized for code editing like the Simple Text field type.

https://github.com/craftcms/simple-text/tree/v1


How do I programmatically set a Users company field?

Close! You should be using setContentFromPost() for this.  See here and here for more info.

You code would look like:

$user = new UserModel();
$user->username  = 'tommy';
$user->firstName = 'Tom';
$user->lastName  = 'Foolery';
$user->email     = 'tom@thefoolery.com';
$user->setContentFromPost(array('company' => 'ACME'));

$success = craft()->users->saveUser($user);

if (!$success)
{
    Craft::log('Couldn’t save the user "'.$user->username.'"', LogLevel::Error);
}


Craft directory 403 Access Forbidden with XAMPP

That’s a good thing - you definitely don’t want to allow direct HTTP traffic to your craft/ folder, as people would be able to access your config settings, license key, and plenty of other sensitive data.

There’s a .htaccess file inside your craft/ folder with Deny from all in it, which is what is responsible for that 403 error you’re getting. Keep it in there!


What are the options for taking membership subscriptions via Craft?

I don't think that there currently is a plugin option right now, but keep an eye on the craft plugin page. However, given your requirement to "automatically assign users to different membership groups", I think you would need to write your own regardless. That is pretty specific and would require that you have your user groups set up to match the subscription plans.

I recently did something similar for a project. Saving for a few issues with javascript and learning the API for stripe it was fairly straightforward. It is currently a bit hard-wired to the specific project, however — I still need to abstract it so that it's more portable. I would be glad to share some tips, if you are up for writing your own.

The process that I'm using is to store the StripeCustomerId in the custom fieldtype. As far as craft is concerned that's all just 1 field, that is auto-generated and never exposed to the client (i.e. they can't edit the 'stripeCustomerId').

Whenever an 'account' (could also be 'user') is created, I use the onSaveUser event to generate and store a StipeCustomerId. The rest of the field just sends calls to stripe to add card, delete card, create subscription, cancel subscription, etc. via service methods, and then refresh itself with the most up-to-date customer data from Stripe (doesn't ever store this info, just the customerId).

Besides this the only thing that you would need to add is to reassign the userGroup based on the plan selection. However, if you want to ensure that the userGroup is always synced with the Stripe account (i.e. if the client, for example, canceled the subscription directly from their Stripe account), you would probably need to create a webhook to trigger the userGroup re-assignment. Or instruct them to always re-save the user in craft afterwards.


How are people adding public comments to their Craft sites?

What you describe above is essentially your options. If you use built in sections for comments, you can probably make them more secure from spam by using Dukt's OAuth plugin to require a log in from a more reputable site.

Other third-party options include:

Intense Debate (from the makers of WordPress)
LiveFyre Comments
Facebook Comments


I figured out this issue was caused by a permissions issue on Amazon AWS.
The site was not able to write to the S3 bucket, due to AWS blocking public access to the bucket, which was over-riding the policy I'd applied to the bucket.


Migrating entries to custom element and UID

If you want to be future-proof, then yes - you should create a new UUID for each new row.

You can use MySQL's uuid() method for that.


Task "Resaving all localizable elements" is stuck when adding new new locale

As from Craft 3.1.15 you could use the resave/entries console command if you want  to offload entry saving to the terminal in order to update your content.

Please note that you should enable propagating entries across all enabled sites (see documentation).


Change how the PDF filename is formatted?

There's currently not a native way to change this format, but it is planned for a future release.

In the meantime as a workaround, you can listen to the onBeforeSaveOrder event and change the order number to whatever format you want.  A by-product of that is that the PDF receipt filename should change to your format as well.


Possibility to change where Image Transform folders are stored?

Currently the answer is no.  Those paths are hard set in the code.

Sounds like something for the feedback site, though.  Be sure and share your use case.


Is there a prescribed way to to represent complex field types as strings?

There isn’t, and yeah, the collapsed Matrix block preview text is just created with some Javascript that checks the fields and their inputs within each block.


Get entries which have a certain category assigned to them

This should do what you are looking for:

{% set category = craft.categories.slug('family') %}
{% set entries = craft.entries.section('images').relatedTo(category).find() %}

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

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

{% endif %}

So we are creating a variable called category, in which you set the category you want to get the list of related entries from.

Next we set a variable called entries, which checks to see if there are any entries in the Image section that relate to the category we set.

It then loops through the entries that we find (if there are any).

EDIT

More than one category group might have the Family category. To get round this you can target a specific category group when we set the category variable:

{% set category = craft.categories.group('categoryGroup').slug('family') %}


Auto generating slug with custom fields or ID

I think for this you'd want to write a custom plugin that listened to the onSaveEntry event.

That plugin would check that the given entry is in the correct section/entry type you're interested in, pull any data from custom fields set on the entry update the slug for that entry accordingly.

I'd probably look at updating the slug directly in the database and avoid going back through craft()->entries->saveEntry() to avoid getting into an infinite save entry loop.


Creating new assets subfolder throws error

Two possible suggestions:

Are you positive that the File System Path of your assets source is correct?
Does your assets source folder have the correct permissions which would allow Craft to create a new subfolder?


Find entries that have a category selected from a category field within a matrix block

Try using targetElement: cat instead of sourceElement – in my experience the entries are considered the source of the relation in cases like these, not the categories.

Edit: Also, the field parameter of the relatedTo method shouldn't include the Matrix field's block type, only the actual category field – i.e. contentBuilder.content, not contentBuilder.relatedCategories.content.


I'm on the same boat ... Check out http://status.mandrillapp.com . Your issues are, more than likely, due to Mandrill currently being down and having issues (for the past couple days now).


Slow initial response time when website has been idle?

You mention you're using cache, which could mean a whole lot of things, but the symptoms you're describing are typical of what you'd see if you're doing some heavy-handed things inside of a {% cache %}, you let that expire, then you're the first person to hit the page when the cache has to rebuild.

That {% cache %} tag, by default, will purge its cache every 24 hours unless you've specified otherwise.


Commerce Order Model in Gateway Event Plugin Hook

You have access to the order from the transaction like this:

craft()->on('commerce_payments.onBeforeGatewayRequestSend', function($event) {

    $transaction = $event->params['transaction'];
    $order = $transaction->order;

}


Per item ie gift wrapped with additional cost in Craft Commerce?

To add additional information about a product when adding to cart, you can use the options param to submit any data you wish along with the product you are adding to cart. You can see documentation on this here: https://craftcommerce.com/docs/add-to-cart#line-item-options-and-notes

As for modifying the price of the product based on those options; this is not possible by default in Craft Commerce, although we have provided a way that a plugin can achieve this.

There are 2 possible solutions:

1) Write a plugin that provides a Purchasable. A purchasable is a Craft Element, which your customers could build or edit on the front-end, and then add it to the cart. This is the more advanced path. You would need to know how to create a Craft Element, allow front end users to create and edit them, then make the element a purchasable. Documentation on Purchasables here: https://craftcommerce.com/docs/purchasables

2) Submit line item option data, but write a plugin that uses the onPopulateLineItem event to modify the price of the line item based on the option data submitted. It would look something like this:

craft()->on('commerce_lineItems.onPopulateLineItem', function($event){

    $purchasable= $event->params['purchasable'];
    $lineItem = $event->params['lineItem'];

    if(isset($lineItem->options['giftWrapped']) && $lineItem->options['giftWrapped'] == 'yes'){
        $lineItem->price = $purchasable->getPrice() + 10; // gift wrap is 10 dollars
        $lineItem->saleAmount = 0;
    }

});

The original price would still show in the product listing, but the option submitted when adding to cart would change the price of the line item when in the cart.

The 2 methods above allow you to have configurable prices of products.


Responsive background images in carousel

It's not really a Craft CMS question, but...

I don't remember Flickity supporting what you describe. You could try listening for screen size on pageload (and resize), assigning the correct image to the cell, and then creating the slideshow (destroying it first if it's a resize).

But half the point of lazy loading is to avoid loading images until they're needed anyway, so I'd question whether serving different images for different sizes is the right approach. Probably the easiest method would be to forget lazy loading and use an inline <style> element with media queries targeting each cell.


Difference between using subscript syntax and "dot" syntax when accessing attributes of a variable or advantages of usage one of them

They're both the same for the most part.

The only time I'd use the second way you listed is when the property is a variable.

For instance:

{% set foo = 'name' %}
{{ variable[foo] }}

This will give you {{ variable.name }}


There are no sites in the config file on nitro add

It probably because nitro doesn't overwrite your host file. You may need to edit it yourself using nano (assuming you're on linux).
sudo nano /etc/hosts
you will need to provide

the IP address- that you can find using nitro info in the terminal or by opening the nitro-dev shell in multipass
the hostname- example.test or whatever else that may be

There is a github issue raised for it, see https://github.com/craftcms/nitro/issues/213


if entry has specific category, show specific html block

craft.entries() returns an EntryQuery. You must then execute the query with one of those methods:

one()
all()
count()
exists()

In your case, I think .exists() is the best choice: {% if categoryListings.exists() %}
Edit: You may also have to execute your category query with {% for category in craft.categories().group('catGroup1').all() %}. See https://craftcms.com/docs/3.x/categories.html#querying-categories.


Generating a precache manifest for service workers

So you shouldn't try to come up with a hashed file naming scheme for busting the cache; instead use one of Workbox's Strategies -- I think a great pattern for what you're trying to do is Stale While Revalidate

TL;DR Workbox has strategies for doing what you're trying to do.


Only display the first tier of categories

You can filter elements based on their hierarchy level with the level attribute

{% for category in categories.level(1).all() %}

Will only show top tier categories

{% for category in categories.level(2).all() %}

only all the first tier children of all first tier categories (so tier 2) and so on.

Additional note

You can also search for descendants elements

element.getDescendants(1) //<-- include the level based on the parents level

With the parameter  1 it is the same as

element.getChildren()


Counting included child blocks in the Neo plugin

The answer by Tom Bauer given to my question here should be of help.

You're not far off. You need to set a variable and count the blocks in your neo loop. Then use if statements in the loop depending on the counter variable.

The other option is you add a columnWidth dropdown field, and give them the option to choose between 2 or 3, the values are the css (2=col-sm-6, 3=col-sm-4.)

Then your code code look like:

{% block blockContent %}
{% for block in entry.body %}
{% switch block.type.handle %}
{% case 'serviceItem' %}

  {{ block.text }}
  LEARN MORE

{% endswitch %}
{% endfor %}
{% endblock %}


Yes — an error.twig template in your error templates directory serves as a catch-all template when a more specific template (e.g. 404.twig) can't be found, or when the system throws a general error that doesn't have a status code attached.

(You can customize the path prefix for error templates by changing the errorTemplatePrefix setting in the Craft General Config.)


Filter entries by matching an url segment to Checkboxes Field values

This is just a guess, as I've never used the 'contains' method before, but it's possible that it can't be used directly with an ElementCriteriaModel query. You might have to filter the entries after the fact.

{% set entries = craft.entries.section('news') %}
{% for entry in entries if entry.category.contains(craft.request.getSegment(2)) %}
    {{ entry.title }}
{% endfor %}

This probably defeats the purpose of using it as a psuedo-category selector however.

Update If this answer is any indication it also looks like you could use the search method. Using this method, however, may not be 100% reliable if the search index becomes outdated for whatever reason.

 {% set entries = craft.entries.section('news').search('category:' ~ craft.request.getSegment(2)) %}


It looks like https://plugins.craftcms.com/super-pdf might do what you're asking for although I've not used this plugin.
Check out the docs here:
https://docs.amiciinfotech.com/craft-cms/super-pdf/backend/config
Search for password on that page to see what it offers.
Good luck.
-John Morton


You are close, the template loaded by the macro can be found in craft/app/templates/_includes/forms/textarea.html. It does have a value attribute, and a few others, for example:

{{ forms.textareaField({
    label:         "Submitted Subject"|t,
    id:            'submittedSubject',
    name:          'submittedSubject',
    instructions:  "Input your setting"|t,
    value:         settings.submittedSubject,
    rows:          4,
    cols:          50,
    errors:        settings.getErrors('submittedSubject'),
    maxlength:     250,
    showCharsLeft: true,
    autofocus:     settings.hasErrors('submittedSubject'),
}) }}

All the form macros are defined in craft/app/templates/_includes/forms.html.


Dukt Analytics Plugin - Web Profile not showing up

After doing the latest Craft Update, the plugin seems to be working fine now. It was either a bug in Craft that has been fixed, or you just have to give Google a few days before it's able to fetch the list of hosted analytics accounts.


Craft hosted on Google App Engine - failing to load Craft classes?

I got the same error and started debugging with XDebug.

I've put some hours in this and my conclusion is: You can't run Craft on GAE. It gets worse: You can't even run Yii1 (the framework Craft was built on) on GAE. So that's where it stops.

I did manage to get Craft running on a GAE development server instance, but to do that I had to uncomment every filesystem check in both Craft and Yii (functions like is_dir(), etc). These functions don't even work with the gs:// wrapper.


That error is occurring at entries.limit(10), because at that point entries is already an array of fetched entries, rather than an ElementCriteriaModel. (The entries will get fetched as soon as the ElementCriteriaModel is passed to your |group filter.)

The only way to grab just 10 entries per section (per page) will be to loop through each of your sections, and create a new ElementCriteriaModel for each one.

{% set sections = {
    'news': 'News',
    'events': 'Events',
    // ...
} %}

{% for section, sectionName in sections %}

    {% set entries = craft.entries.section(section).limit(10) %}
    {% paginate entries as pageInfo, pageEntries %}

    {% if pageEntries|length %}

{{ sectionName }}

        {% for entry in pageEntries %}
            {{ entry.title }}
        {% endfor %}
    {% endif %}

{% endfor %}

Note that Craft does not support multiple independently paginated lists of entries on a single webpage. So if you use the built-in {% paginate %} tag like this, when it takes you to page 2, all of the sections’ {% paginate %} tags will start showing page 2 content. And you’ll need to keep track of which section actually has the most pages, before building out your pagination nav.

// ...

{% set primaryPageInfo = null %}

{% for section, sectionName in sections %}

    {% set entries = craft.entries.section(section).limit(10) %}
    {% paginate entries as pageInfo, pageEntries %}

    // ...

    {# Does this section have the most entries (so far)? #}
    {% if not primaryPageInfo or pageInfo.totalPages > primaryPageInfo.totalPages %}
        {% set primaryPageInfo = pageInfo %}
    {% endif %}

{% endfor %}

{# Build out the pagination nav using the biggest section's pageInfo #}
First Page
{% if primaryPageInfo.prevUrl %}Previous Page{% endif %}
{% if primaryPageInfo.nextUrl %}Next Page{% endif %}
Last Page


It's a little unclear what you need to achieve here –

If your entries' entry type handles actually are 'contact' and 'location', the above code should work; which means that you've got an error somewhere that isn't really possible to figure out based on your description – e.g. the entry type handle is actually contacts, and not contact, or something like that.

One thing you might try, is to simply print the entry.type variable in a template, to see if it contains what you expect it to contain:

{{ entry.type }}

On the other hand, if your issue is simply that some entries have a contact field populated and others have a location field populated, you can't really use a {% switch %} statement in any sensible manner for that – though a plain old {% if %} would do it:

{% if entry.contact %}
    {{ entry.contact }}
{% elseif entry.location %}
    {{ entry.location }}
{% endif %}


{% cache %} always creates new cache data, never uses existing cached data

Update:

This has been fixed for the next (post 2.4.2725) release.

Turns out there is a bug in Craft where if you put cache tags around code that doesn't actually output anything, then duplicate keys get created in the craft_templatecaches table.

No workaround for it yet (other than to make sure you don't cache an empty string), but it's been logged as a bug.


Can I atttach uploaded file in A&M Forms to notification email

There is a switch in notification tab for doing that -
Add attachments with notifications / Whether to add possible attachments to the email.

Feeling stupid now :)


How to make fields required on the contact form?

You could also hand this over to HTML since it supports form validation as of version 5.
Depends on your browser support requirements though. This is what “Can i use” says.


Can Craft or any of its plugins render down flat html files for speed

I've come to understand that if Craft CMS can render flat html or cache some of the pages then it makes thing a lot quicker to load

I believe you're looking for the the {% cache %} tag, which will – on the first page request – capture the compiled HTML output inbetween the opening and closing of the tag, and write it to the database. On subsequent requests, Craft will pull and output the compiled (flat) HTML using a single SQL query (until the cache expires, is cleared manually or any entries, categories etc. involved is changed). This means that for most pageloads, complex database queries or taxing PHP operations (Twig templates are compiled to PHP) can be eliminated, which is usually a performance boost.

  will it will be ok using assets from a cloud front CDN setup too?

Yep, Craft is easily set up with external asset sources, and S3/CloudFront is supported. You will need a Craft Pro license, though.


Programmatically create new entry with saveElement

In Craft's v3 API documentation they give an example:

https://docs.craftcms.com/api/v3/craft-services-elements.html#method-saveelement

$entry = new Entry();
$entry->sectionId = 10;
$entry->typeId = 1;
$entry->authorId = 5;
$entry->enabled = true;
$entry->title = "Hello World!";
$entry->setFieldValues([
    'body' => "
I can’t believe I literally just called this “Hello World!”.
",
]);
$success = Craft::$app->elements->saveElement($entry);
if (!$success) {
    Craft::error('Couldn’t save the entry "'.$entry->title.'"', __METHOD__);
}


Best solution for get json results from third party api?

This works great for templates too: https://github.com/engram-design/FeedMe

Just tested it for a RSS feed, but apparently it also supports JSON.

The RSS example:

{% set params = {
    url: 'http://url.to/feed.rss',
    type: 'rss',
    element: 'item',
    cache: 60,
} %}

{% set feed = craft.feedme.feed(params) %}
{% for node in feed %}
    Title: {{ node.title }}
    Publish Date: {{ node.pubdate }}
    Content: {{ node.description }}
{% endfor %}


Add custom element criteria attribute without a field type?

Currently, yes, the only way to modify an element query (when it’s not your own element type) is to do it with a custom field type, from its modifyElementsQuery() function.

UPDATE

As of Craft 2.5, plugins can listen for the elements.onBeforeBuildElementsQuery and elements.onBuildElementsQuery events to make changes to the query (or prevent it from getting executed).

craft()->on('elements.buildElementsQuery', function(Event $event) {
    /** @var ElementCriteriaModel $criteria */
    $criteria = $event->params['criteria'];

    /** @var DbCommand $query */
    $query = $event->params['query'];

    if ($criteria->myCustomParamName) {
        $query->andWhere( //...
    }
});


You first have to get the CategoryModel of that category you want to filter by. Use slug as a parameter and the first() method to get the first and only category matching that criteria.

This CategoryModel is the target element of your relation. Set your craft.assets ElementCriteriaModel using the relatedTo parameter to filter by your category and also set the relation's field name here (not necessary if you don't have other relations set on your assets).

If you really have the need to further filter by an asset source (don't get the assets which match the other criteria but are in a different source folder), you (currently) can only do this by looking up that asset source's ID in the database and filter by that sourceId. Set all other parameters to your needs.

{% set categorySlug = 'sitePlan' %}

{# Get the CategoryModel #}
{% set category = craft.categories.slug(categorySlug).first() %}

{# Get the assets related to this CategoryModel #}
{% set assets = craft.assets({
    relatedTo: {
        targetElement: category,
        field: 'documentType',
    },
    sourceId: '1',
    limit: null,
    order: 'dateUpdated desc',
}) %}


How can I change the rich-text editor to remove the "Heading 1" option

formattingTags is not the correct syntax.

You should be using formatting instead, as per my answer on this question.


Find Related Entries with Identical Tags

Marion's answer is fine but you can also do it a different way, and move the conditional logic out of the for loop. By adding it to the query, you can ask for a specific amount of items to grab, and it won't mess up the loop.index values if you need them.

This is how I would do it.

{% set relatedEntries = craft.entries.relatedTo(tag).id('not ' ~ currentEntry.id).limit(4).find() %}

{% if relatedEntries | length %}
    {% for e in relatedEntries %}
        {# entry stuff here #}
    {% endfor %}
{% endif %}


How to handle multiple users simultaneously editing an entry?

There currently isn't a native way to do this and I'm not aware of a plugin that's has the functionality.

You can semi-work around it with entry revisions, but if you think this should be a core feature you can vote for it!


How to show entries which are live between dates regardless of postdate or expiry dates?

"Live" is determined in part by postDate and expiryDate (in addition to status), so not technically independent, but this may be what you're after. You would still use the technique described in Carlcs' answer, only that the criteria would be searching the entries using the month values passed to your template.

{% if craft.request.param('startMonth') and craft.request.param('endMonth') %}

    {% set startMonth = craft.request.param('startMonth') %}
    {% set endMonth = craft.request.param('endMonth') %}
    {% set startDate = now|date(Y) ~ '-' ~ startMonth %}
    {% set endDate = now|date(Y) ~ '-' ~ endMonth %}

    {% set entries = craft.entries.section('mySectionHandle').postDate('and, >= ' ~ startDate ~ ', <= ' ~ endDate) %}

    {% for entry in entries %}
    ...
    {% endfor %}

{% endif %}

You could also use .after(starDate).before(endDate) for this.

Update If you want to get entries that are live during a particular month range (rather than posted during the month range) then you could check for postDate before the selected 'start month' and expiryDate after the selected 'end month'.

{% if craft.request.param('startMonth') and craft.request.param('endMonth') %}

    {% set startMonth = craft.request.param('startMonth') %}
    {% set endMonth = craft.request.param('endMonth') %}
    {% set startDate = now|date(Y) ~ '-' ~ startMonth %}
    {% set endDate = now|date(Y) ~ '-' ~ endMonth %}

    {% set entries = craft.entries.section('mySectionHandle').postDate('<= ' ~ startDate).expiryDate('>= ' ~ endDate) %}

    {% for entry in entries %}
    ...
    {% endfor %}

{% endif %}

Not tested.


Hey So here is what i came up with, curious if anyone has a more streamlined approach.

https://gist.github.com/keithmancuso/17619fc405a621b4a11e

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

{% extends layout %}

{% set limit = 10 %}
{% set params = { section: 'news', limit: limit} %}

{% block content %}

{% if not craft.request.isAjax %}

News

{% endif %}

{% paginate craft.entries(params) as entries %}
{% for entry in entries %}

{{ entry.title }}

    {{ entry.body }}

{% endfor %}
{% endpaginate %}

{% if not craft.request.isAjax %}

load more news

{% set pagingJs %}

$(function () {

    var page = 2;

    $('#loadMore').click (function (e) {
        e.preventDefault();

        $('#loading').show();

        $.get( "/news/p"+page, function( data ) {

          $( "#news-entries" ).append( data );
          $('.loading').hide();
          page++;

        });

    });
});

{% endset %}

{% includeJs pagingJs %}

{% endif %}

{% endblock %}


How to define template routes for a custom element type

You'll need to override the BaseElementType's routeRequestForMatchedElement method in your element type class as follows:

public function routeRequestForMatchedElement(BaseElementModel $element)
{
    return array(
        'action' => 'templates/render',
        'params' => array(
            'template' => '_page',
            'variables' => array(
                'page' => $element
            )
        )
    );
}


Entry template category loop repeats URI when HTML added

Using {{category.uri}} is likely just appending to the page's URL. You can use either {{category.url}} or {{siteUrl~category.uri}} to get the full URL.


Maintaining a relationship of parent from children selected through entry field

This is commonly called 'reverse-related entries' and is achievable using relatedTo(). See here for some info...

  My question is if I chose to show the entry selected on a new page how would I show the relationship to the page it appears on / came from? Perhaps as a title from the previous page or a back button.

For example, if a visitor were on an Audio Entry page, your template code would look something like:

{% set relatedResearchProject = craft.entries.section('researchProjects').relatedTo(entry) %}
{% for researchProject in relatedResearchProject %}

{{ researchProject.title }}

{% endfor %}

The above, would display any Research Projects which contain related "audio" Entries.

The logic is as follows:

{% set relatedResearchProject = craft.entries.section('researchProjects').relatedTo(entry) %}

Create a new variable called "relatedResearchProject" (in fact the variable name can be any word which makes sense to you)
The new variable should contain any entries from the Research Projects Section which are related to the the (Audio) entry being displayed on the current page.

Then...

{% for researchProject in relatedResearchProject %}
{{ researchProject.title }}</a
{% endfor %}

Loop through and display any entries which are in the 'relatedResearchProject' variable.

In a different example below, you can see that "Third news entry..." contains the Entry field. then, on /news/we-just-installed-craft you can see the rendered link back to the "Third news entry..." page.

Sorry, Scott - I hope illustrating two examples isn't confusing! Let us know how you get on.

{% for researchProject in relatedResearchProject %}
{{ researchProject.title }}</a
{% endfor %}


no element type exists with getCriteria and custom element type

As Stephen pointed out, you're getting that error because your Commerce_GroupModel class is a Model that extends BaseModel, not an Element Type, which is what ElementsService->getCriteria() is looking for.

Are you sure you actually need a custom element type here?  Depending on what you're going for, Models might be enough.


What's the correct way to relate element types to a custom element type?

One or more Entries Fields might help you establish the relationship between your custom element and the other elements - after that, you should be able to call setContentFromPost() on the Entries in that field to change the content of related elements.


Can I get entries related to one category from a specific site?

Relations don't work with a slug. You'll need to insert an ElementQuery an Element or the ID of an Element

{% set entries = craft.entries
    .section('sectionHandle')
    .relatedTo(category)
    .site('siteHandle')
    .all()
%}

However this will only work in certain cases where all category ids are the same for both sites. You'll need to to fetch the category from the other site at first if these are different


Ok I actually managed to fix this. I moved the index.php file from the cms/public subfolder to public_html and it worked a treat. I had to change the following code:

// Path to your craft/ folder
$craftPath = '../craft';

to

// Path to your craft/ folder
$craftPath = 'cms/craft';


being replaced by  tags in redactor rich text editor

You can create a new redactor config under craft/config/redactor named Simple-With-Divs.json with the following code:

{
    buttons: ['bold', 'italic'],
    toolbarFixed: true,
    replaceDivs: false
}

Now you can select Simple With Divs under the Rich Text field type.


How can I get unpublished drafts in my plugin?

Depending on what you want to do with them you can request them using craft.entries but you'll probably need to change the status to pending.

If this doesn't work you'll need to fetch them through a custom controller/service that goes in and fetches the entry model and returns a list that fit you criteria.

Hope this helps.


How does Craft know when to generate an Image Transform

Craft will make the image transform the first time the template is loaded in the browser and the getUrl() is called. The image will at first be saved in a temporary directory, then moved into a sub-directory in your assets folder. The subdirectory will be descriptively named according to the type of transform. For example, if my template calls for a 500 x 500 center-center crop at 75% quality, it will be saved in /uploads/_500x500_crop_center-center_75/img.jpg.

This works similarly when using a CDN like S3 or Google Cloud.


Archive page - only show posts from certain month

There's probably a cleaner way to go about this, but something like this should work:

{# These are probably coming from the querystring, but I'll hard code them here #}
{% set year = 2015 %}
{% set month = 'July' %}

{% set entriesInYear = craft.entries.section('news').limit(null).after(year).before(year+1) %}
{% set groupedEntries =  entriesInYear | group("postDate|date('F')") %}

{{ month }}

    {% for entry in groupedEntries[month] %}

{{ entry.getLink() }}

    {% endfor %}

You'll probably want to add error checking and validation in case no entries exist for the month or the month/year is invalid, etc.


Is this the correct and safest way to update / save a new record?

It is definitely a way to save record. :)

You might want to be more explicit with validation, though.  i.e.

if ($record->validate())
{
    // Save record
    if ($record->save(false))
    {
        // Populate id
        if($isNewGoal)
        {
            $model->id = $record->id;
        }

        return true;
    }
    else
    {
        return false;
    }
}
else
{
    $model->addErrors($record->getErrors());
}


Do you need to filter by block type?

Maybe something like this:

{% for block in entry.contentMatrix %}

    {# Tabs Block Type #}
    {% if block.type == "tabs" %}

        {% set entries = craft.entries.relatedTo(block.tabEntry) %}

        {% for entry in entries %}
            {# Matrix Content #}
            {% for content in entry.tabsMatrix.type('videoChannel, videoPlayer, copy') %}

                {% if content.type == "videoChannel" %}
                    {{ content.title }}
                {% elseif content.type == "videoPlayer" %}
                    {{ content.url }}
                {% else %}
                    {{ content.text }}
                {% endif %}

            {% endfor %}

        {% endfor %}

    {% endif %}

{% endfor %}

Note: Matrix Content vars (*.title, *url, *text) are just examples.


Is it possible to call a variable within a tag pair?

Try this:

{% for block in availability[foo] %}

The square brackets let you access a variable variable name on an object.

As a general rule you never put {{ }} inside of {% %} tags in twig.


Update Asset Indexes gives "getFileList() is not implemented"

This exception in thrown in the class craft\volumes\MissingVolume that states one of your Volumes has an invalid class

/**
 * @inheritdoc
 */
public function getFileList(string $directory, bool $recursive): array
{
    throw new NotSupportedException('getFileList() is not implemented.');
}

Maybe you uninstalled a plugin that adds a certain Volume class like S3 or something?


Route: {slug}-recipes

The in the template:

{% set parts = craft.app.request.getSegment(1)|split("-") %}
{% set newslug = parts[0] %}

Then you can use: .slug(newslug)


You can use this plugin to make it possible for you customer to add new descriptions to a translation file: https://github.com/boboldehampsink/translate.


Understanding migrations and CLI commands

How does craft know which migrations have been applied and which are new? I.e. Is it by comparing the craft_migrations table to the migration files found in '/vendor/craftcms/cms/src/migrations' folder (or plugin folders)?

Exactly!

Where does the information from running 'php craft migrate/new' and 'php craft migrate/history' come from?

migrate/history purely checks the migrations table in the database for a list of migrations that have already run.
migrate/new grabs the same list of migrations from the database that migrate/history does, then compares it again the migrations folder on the file system to find any newer migrations (using the timestamp in the filename) that haven't run yet and returns that list.

So clearly something is out of sync (or is terribly wrong in this project).

Something does sound out-of-sync to me.

How are version numbers and migrations associated with each other?

Craft's (and a plugin's) version number is independent of migrations. Both have a separate concept called a schemaVersion, and when that number gets incremented, that tells Craft that a plugin (or itself) that there are new migrations that need to run.

What determines the order that migrations are run?

They are sorted, but since timestamps are embedded in the migration names, they will run from the oldest unapplied migrations to the newest unapplied migrations.

Finally, if a migration fails, is there something else that should be done besides restoring the DB to reset the craft state, before attempting to run migrate/all again?

Nope - restore from a pre-update attempt database back, fix whatever caused it to fail, then try again.


You're basically looking for authentication/authorization for the Element API plugin, which it currently doesn't support.

  Should this require us to write our own plugin with a custom authentication system or is it possible to get this working with the user logic provided by Craft?

I'd probably approach this by forking the Element API plugin and adding authentication/authorization to it instead of adding it to a separate plugin and getting them to interact.

You'd need some way to authenticate the user and once they are authenticated you could authorize future requests either based on a custom token or using authorization headers and each could have their own expiration logic.


Missing "Plugin Store" navigation on Craft 3 admin section

You need Craft 3 for that. Looks like you are on version 2.7.4
The link provided gives information about new features in version 3, among them being the Plugin store.


Brad mentions there's no limitations on entry types, though whether it's a good idea long term for maintainability and UI purposes is another story.
Entry Types are the most useful when your content is quite different among them but you still want to keep entries together in the same section.
For example, in a News section, you might have a Link to Page entry type where you link off to different websites and a Blog Entry type where they're just regular entries. (John Gruber's Daring Fireball site is a good example of this.
In my experience, when a user starts to see a dozen or so entry types, it can start to become pretty overwhelming... here's what 50 of them staring you in the face might look like:

Entry types are useful because they each have their own set of fields.
However, from a maintainability standpoint, let's say you want to add or move a field in every report. Doing it to 2 or 3 entry types is pretty straightforward but doing it consistently to 50? Way harder—whether you're using YAML files or the GUI!
The 80/20 rule might be helpful here: I'm guessing 80% of the reports generated are probably going to fall into 20% of their types. That just narrowed down the number of entry types to 10.  Maybe you add a few other more common ones plus a catch-all "Other..." entry type or something.
Unless your client is also a fellow developer/designer, they don't want to be adding fields and sections to the backend unless absolutely necessary.
If I were you, I might ask you client: what's different about each report? What's the same? You'll come across some good answers which can help you and your client model this nicely.
That could lead you to use something like Categories instead, where it's very easy to add new ones. If the report types are more like filters, they also will show much nicer in the GUI.
And maybe you do need some report types to hide and show different fields but are otherwise pretty similar. You might consider doing this with, say, the Reasons plugin.
Food for thought!


We are working on providing better search for entries, products, orders,  and all other custom elements in Craft within Craft 3. For example we recently added the search keywords method to the element interface to allow searching on non core attributes or custom fields: https://github.com/craftcms/cms/commit/afffaa5dcdb0fc02b484192e42cd5c9d528db94a

The above additions like above will help us provide searching on attributes that aren't actual properties/getter methods on the order.

This of course doesn't help you in the short term when searching for orders on the attributes you listed. I have added it as a priority to see if we can somehow make searching on those attributes easier in Commerce 1.x

A temporary work around would be adding the information to the search index by creating some pre-parse custom fields: https://github.com/aelvan/Preparse-Field-Craft

For example you could create a pre-parse field called "businessShippingName" and add it to the order field layout. In the settings for that field, you could use the template: {{ commerce_order.shippingAddress.businessName }}. This would allow you to search based on the business shipping name, as well as list it more easily in the order index screen.


Set Up A Global Dashboard For A Specific User Group

The dashboard widgets are currently set on a per user basis. Brandon has said on the Google+ community that a site-wide and/or user group solution is planned but doesn't have en ETA.

https://plus.google.com/106689452282751248337/posts/CvZZa5DDGwb

https://plus.google.com/103717873128586100650/posts/gW9buKqF4LA


For anyone stuck on this -- when changing a Section's name you have to goto the entry under Entries and hit save. This will update the mysql row / title.


Set Entries field in Commerce order on completion

See What is getContent() / the ContentModel, and how do I use it to get and set custom field values?

So you needed to change the method used for setting content on an element.

Also see In a plugin, how do I save an entry with a related entry

So the relation fields always expect an array of ids, even if there is a single relation.

Putting those together you should be able to do:

craft()->on('commerce_orders.onOrderComplete',function($event){
    $order = $event->params['order'];

    $order->setContentFromPost(['entryRelaionFieldName' => [678] ]);

    craft()->commerce_orders->saveOrder($order);
});


Craft doesn't have a setting for defining the transformations image path, they are automatically placed in a subfolder inside your created assets source' path. It could look something like this _960x540_crop_center-center_70, if you had a transform like this:

{ width: 960, height: 540, mode: 'crop', position: 'center-center', quality: 70 }

By default, the url you're seeing is what Craft will return if the transform hasn’t been generated yet. The next time the page is loaded, it should reference the actual image file. See Brandon's answer here, for a more thorough explanation.

But, if everything is working, you should see the image in your browser even if it returns the transform url. If the image isn't created, check if the file path for your asset source is correct (guess it is if you can upload images), and that url rewriting is working.


How to get the previous or next two entries with images and

Bratvold, what do you mean with "input"?

Actually, if you can get the title of your prev-item, you can get everything of it.

{% if prevEntry %}

{{ prevEntry.title }}

      {% for row in prevEntry.kunde.all() %}
          {{ row.kundenavn }}
      {% endfor %}

{% endif %}


Unknown error occurred after install on MAMP

Chances are your craft/config folder isn't writable, but you can see the underlying error in your craft/config/storage/runtime/logs files.  Just search for [error] or [warning].


Getting assets from an entry programatically

In the returned object I'm expecting to see an array somewhere for custom field values listing the asset Id's, but it's drawing a blank

The reason for this is that entry fields are lazy-loaded, meaning Craft only queries the values from the database once you access them using their field handle (or execute the entity query you get through the field handle, like with the asset field). You can change this using Eager-Loading.
Without eager-loading, to get the asset you need to use the field handle (featureImage, in your case) to get an AssetQuery. Then you can use that to get the images (assets) in your field.
$entry = Entry::find()
  ->slug('0002')
  ->one();

/** @var \craft\elements\Asset */
$featureImage = $entry->featureImage->one();

$featureImageId = $featureImage->id;

See Working with assets field data and Querying assets. The object returned by AssetQuery::one() is an instance of \craft\elements\Asset.


Correct IAM settings for Amazon S3 bucket

You need to allow to list bucket location. Also, I'm not confident if you'd be able to upload and delete objects from the bucket with that policy.

I'd go with:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:ListAllMyBuckets"
        ],
        "Resource": "*"
    },
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetBucketLocation",
            "s3:ListBucket",
            "s3:PutObject",
            "s3:GetObject",
            "s3:DeleteObject",
            "s3:GetObjectAcl",
            "s3:PutObjectAcl"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname/*"
        ]
    },
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetBucketLocation",
            "s3:ListBucket"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname"
        ]
    }
]
}


You can, using reference tags, but unfortunately they only work in plain text fields:

Reference tags in rich text fields parse and converted on save


How to remove empty tags in rich text? (Redactor or Twig)

I ended up using this solution:

Filter empty tags in Craft/Twig template

{{ entry.houseDescription|replace('/<[^\\/>][^>]*><\\/[^>]+>/', '')|raw }}

The replace filter /<[^\\/>][^>]*><\\/[^>]+>/ searches for empty tags and removes them.
The raw filter stops Twig from escaping HTML tags.

Regular expression test (RegExr)


You can't use PHP in a Twig template.

A plugin Craft plugin would be the easiest way to pull off what you're looking for.  I've added an answer to your other related question.


Refer to specific section handle when querying an element by 'getCriteria'

You've got a couple of incorrect things going on in your current example.

Calling craft()->elements->getCriteria(ElementType::Entry) returns an ElementCriteriaModel.

That's what you want to set the parameters on for the entries you're searching for. Stuart sums it up well here.

By calling ->first() on it immediately, you're going to get the defaults, which for entries is by post date in descending order.

By calling:

$entry->slug = $page;
echo $entry->title;

You are actually updating the slug for the entry that was returned to be something new.

This should work for what you're trying to do:

    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->slug = 'about';
    $criteria->section = 'news';
    $entry = $criteria->first();
    $title = $entry->title;


Entry versioning history only shows last 10 versions

I don't think Craft has any other place for viewing old entry versions. You can browse the entire set by examining a table in the database, or write a plugin to display all of them.

Quick and Dirty

If you're just digging into this specific entry, you can pop into the craft_entryversions table and search for the entryId matching the one in question. You'll see all versions past and present, each with a bunch of JSON in the data column with that version's content.

Let's say you fancy one of those entries and its id column is 346 in the database. As you've already discovered, you can modify the entry's edit URL from...

/admin/entries/projects/1234-gobias-industries-about-page

...to...

/admin/entries/projects/1234-gobias-industries-about-page/versions/346

...and view it from the Craft control panel.

This is a bit uncomfortable of course, but you can quickly share a bunch of URLs with your client that'd make it easy to visit and inspect each version.

Slower and Cleaner

Otherwise you'd have to whip up a plugin to display additional version details in the control panel, probably linking to each version for further examination. If you're comfortable taking a stab at the plugin, it'd be fairly quick work displaying the results of craft()->entryRevisions->getVersionsByEntryId() however you like.

Versioneer

I just made a quick Field Type plugin for this. It's v0.0.1, but it may be worth checking out!

https://github.com/workingconcept/versioneer-craft-plugin


Without seeing the code of your template _private/partials/matrix it's not easy to help you.
Maybe you need to check the block type first.
I usually do that with a switch and have a different partial for each block.
So your template _private/partials/matrix could look something like this:
{% for block in blocks %}
  {% switch block.type %}
    {% case "richText" %}
      {% include "_private/partials/richtext" %}
    {% case "quote" %}
      {% include "_private/partials/qoute" %}
    {% case "image" %}
      {% include "_private/partials/image" %}
    {% case "embed" %}
      {% include "_private/partials/embed" %}
    {% default %}
  {% endswitch %}
{% endfor %}

The quote partial could look something like this
{# do something with block.style #}

{{block.quote}}

{{block.attribution}}


Craft 3: White blank page when accessing website and Craft login page

Based on the response headers:

It doesn't look like the response is coming from Craft at all, so I think it's likely that you should contact your hosting provider again.

To me, it seems like the domain isn't pointing at the right place for your website hosting, because Craft isn't even fielding the request.


Include the URL of a related entry field

Try this - using {{ entry.section }} and {{ entry.slug }}

{% for row in entry.homeFeaturedProducts.order('RAND()')|batch(4) %}
{% for entry in row %}

{{ entry.title }}

    Product Description
    {{ entry.price }}
{% endfor %}
{% endfor %}


Notice you got
handle: Pages

And in code below
template: pages/page

A lucky guess would be, your local is not case sensitive. As you might running it on a windows machine with a virtual host.
However, your server ,if its a Linux server, it is likely to be case sensitive.
So I will suggest you change your handle: Pages to handle: pages


Yes, there is. There is a plugin called Weighted Search which I have used a few times which does exactly that. https://straightupcraft.com/craft-plugins/weighted-search


Is it possible to get all elements in a Matrix field by type or field name

There is no craft.entries.matrixes variable available natively in Craft.

(craft.entries returns an ElementCriteriaModel, which does not have a matrixes property explicitly set.)

So, craft.entries.matrixes is actually looking for ElementCriteriaModel->matrixes(), which could implicitly exist if:

You have a field called matrixes, or
There's a plugin in the mix that is changing functionality

You'll need a plugin to run these custom queries. Luckily Craft's MatrixService has plenty of methods that would be helpful.

Also, Low created a plugin (LowBlocks) to do this sort of thing, which might fit your need, or at least offer a helpful starting point.


Assets are not saved in dynamically generated folders

I got the images to upload into correct folders by switching Image field to "Restrict uploads to a single folder" option. I also had to fix the File System Path in Settings>Assets>Asset Sources to the full file system path.


Routing templates thats start with an underscore

Yes, prefixing a template's filename with an underscore does what it says on the box – any underscored template will be excluded from route mapping.

A typical use case is to use underscores for partials or wrappers, e.g. "_mainmenu.html" or "_baseTemplate.html" – essentially any template that doesn't make any sense to load up or access directly in the browser via that template's path.

This isn't a mandatory thing, but a good practice.


Using the Group filter with Squarebit Charge plugin

I got this to work with the following:

{% set allCharges = craft.charge.charges.limit(5) %}
{% set charges = allCharges|group("dateCreated|date('F')") %}

{% for month, details in charges %}
    <div>
        {{ month }}

        {% for detail in details %}
            <p>{{detail.id}}{{detail.customerName}}</p>
        {% endfor %}
    </div>
{% endfor %}

Two things to note: the group filter was applied to the results of the Charges query, rather than applying it to the query itself; the second issue is that the Charge model contains sub-models,which will require an inner loop.


Commerce: Payment does not get completed

Not an answer to the specific issue as such, but perhaps handy for future folks looking to debug issues in this area - you can dump the gateway request data with something like this in your business logic plugin:

(see hook docs here: https://craftcommerce.com/docs/hooks-reference#commerce_modifygatewayrequestdata)

    public function commerce_modifyGatewayRequestData($data,$type,$transaction)
{

        BusinessLogicPlugin::log("commerce_modifyGatewayRequestData");
        BusinessLogicPlugin::log("data");
        BusinessLogicPlugin::log($data);
        BusinessLogicPlugin::log("type");
        BusinessLogicPlugin::log($type);
        BusinessLogicPlugin::log("transaction");
        BusinessLogicPlugin::log($transaction);
 }

(assuming you have a log function in there that accepts strings and if not a string does a var_dump)

That at least gives you a full look at the data you're sending.

You can also modify the $data in there, and return $data at the end if you need to massage any of the data before submissin.  E.g. with eWay you should truncate some fields if they are too long or you will get errors...

E.g.

        if(isset($data['Customer']['Street1']))
        $data['Customer']['Street1'] = substr($data['Customer']['Street1'], 0, 49);

        ...etc

        return $data;

Similarly, after a transaction, you can log the response etc using this event: https://craftcommerce.com/docs/events-reference#commerce_transactions.onsavetransaction

(See what you can log at https://craftcommerce.com/docs/transaction-model)

craft()->on('commerce_transactions.onSaveTransaction', function ($event){

    $transaction = $event->params['transaction'];
    BusinessLogicPlugin::log($transaction->response);

});


Checking if current entry exists in an entry custom field in a different entry

You can get the posts related to your "entry" (the currently shown project) with a
craft.entries element criteria model where you set the relatedTo parameter like so:

{% set relatedPosts = craft.entries.relatedTo({
    targetElement: entry
}) %}

Then check if this does find anything using Twig's length filter:

{% if relatedPosts|length %}
    <aside>
        {% for relatedPost in relatedPosts %}
            {{ relatedPost.title }}
        {% endfor %}
    </aside>
{% endif %}


Your problem is "only" database.

The first thing - create a another copy of your backup file.

Have you got phpMyAdmin?

You can create a new database and set env file in Craft.

or

You can drop all tables there and try load sql backup. If it is not working try create individual tables first after relations and data.


Alternatives to Mamp Pro – which works with Craft CMS

I'd highly recommend you check out Laravel Valet.

Here's an article on it that may be useful to you as well: Running Craft CMS 3 on Laravel Valet


Updating old setup (3.0.41.1) to 3.1.0 various errors every time

There used to be a bug in Craft 3.0 (fixed in 3.0.19) where, if an error occurred during an update, your composer.json file could be left in a weird state where it was directly requiring all of Craft’s dependencies (recursively). My guess is that this happened to you.

Try opening your composer.json file and see if your require setting contains a whole bunch of dependencies, such as twig/twig.

If so, then just delete all of the dependencies that don’t need to be in there. If the file is tracked in Git, then you should be able to look up its history and find the point where all of the extra dependencies were added. Otherwise you’ll need to figure that out for yourself.

You definitely need craftcms/cms.
You probably need vlucas/phpdotenv, if any of your environments are using a .env file.
If you have any plugins installed, then each of them will have one corresponding dependency.
Beyond that, everything else should be safe to remove (unless you intentionally added something else).

Once you’ve removed everything you don’t need, try changing your craftcms/cms requirement to ^3.4.5 and then run composer update. As a sanity check, pay attention to which dependencies get removed in the process, in case you accidentally over-corrected.


Translate icon appears but no translations exist

You need to set the Translation method to Not translatable for each field displaying the unwanted translation icon, in the field's settings page.

It may be a tedious task if you have a lot of fields.


I tried removing a few of the options from one of the Dropdowns within the Matrix and lo-and-behold, the errors are gone. Thanks so much! I guess I hit some kind of limit?


Entry with many fields vs plugin/custom data structure

Since the data will be imported programmatically, my vote would be to write a plugin that manages these products as a custom thing. There will definitely be a performance benefit to giving your products their own DB table that’s perfectly suited for them, and it doesn’t sound like you’ll be missing any of the features you’d get by having these be actual entries.


Display all entry titles on one line during FOR loop

This is because you're using an html list
 element, which by default puts each element on a new line.  You could style away the newline I suppose, but why use it at all...there are a bunch of ways of doing this, but this is one simple one:

{% set developers = entry.GamesDeveloper %}
{% if developers|length %}
Developer:
{% for developer in developers %}
    {{ developer.title }}{% if not loop.last %}, {% endif %}
{% endfor %}
{% endif %}


I'm not sure I can tell you much more than the error messages are telling you, you need to update your twig code eg. in index.twig (line 6) where it says; getPurchasableId() change it to getId().

These errors are just warning you that a future version of Craft won't support them (I imagine it will be Craft 4, but could be sooner).

Changing e-commerce systems based on this error would not be advised as it's a very simple fix!


DeleteStaleTemplateCaches job getting stuck

See these for help debugging stuck tasks:

Generating pending image transforms stuck in process

Deleting Stale Template Caches Failed

http://buildwithcraft.com/help/stuck-tasks

As far as what cache gets saved where, template caches (the {% cache %} tag) always get saved in the database.

See here for an explanation on how all of that works.

The cacheMethod config setting, which is what you've set to memcache affects any PHP code in Craft that is using craft()->cache (including plugins).

See these for more discussion on it:

How much data can craft()->cache hold?

Use cache instead of saving to database


Under Settings > Users > Settings Tab there is an option to allow public registration and Default User Group with a drop down that lets you select a user group.

If you need more flexibility, you could also write a simple plugin with an init function defined in the primary plugin class that listens to the saveUser event, and assigns a user group based on some criteria that you define — perhaps test the value of a custom user field on users (that is a hidden field on the registration form).

*UPDATED to assign group based on checkbox field called 'groupPreference':

namespace Craft;
class BusinessLogicPlugin extends BasePlugin {
  public function getName() {
     return 'Business Logic';
  }
  public function getVersion() {
     return '0.1';
  }
  public function getDeveloper() {
     return craft()->getSiteName();
  }
  public function getDeveloperUrl() {
     return 'http://mysite.com';
  }
  public function init() {
     parent::init();

     craft()->on('users.saveUser', function(Event $event) {

        // only fire if new user
        if ($event->params['isNewUser']) {

           // retrieve the userModel from the event
           $user = $event->params['user'];
           // retrieve the groupPreference field content
           $groupPreference = $user->getContent()->groupPreference;
           // create an empty array to store group ids
           $groups = array();

           // test for values in groupPreference array
           if (in_array("group1", $groupPreference)) {
              $groups[] = 1;
           }
           if (in_array("group2", $groupPreference)) {
              $groups[] = 2;
           }
           if (in_array("group3", $groupPreference)) {
              $groups[] = 3;
           }
           // assign the user to the groups
           $_POST['groups'] = $groups;
        }
     });
  }
}

Haven't tested, but should be pretty close. Please comment if you see an error.

Keep in mind this event will fire, whenever this field is defined, even when saving a user through the CP. So you would have to delete the value before reassigning the user to a different group, or they will just get reassigned.


Craft pro test environment expires? Can no longer access test environment

Are you using MAMP or MAMP Pro? If it was running on a different port yesterday (8888), then it sounds like you might have multiple installations. Try going over the additional resources posts here to verify your installation.

  "You’re running Craft Pro with a Craft Personal license, downgrade/upgrade."

Try clearing your craft/storage/runtime/cache folder.


Got it:

Had already set the slug variable to the first segment in _layout.twig thus overriding everything after. m(


Display user photo within a User field type

It works very simply. Note that the photo field is an asset object, not an array of asset objects.
{% for user in block.staffList.all() %}
   Image URL: {{ user.photo.getUrl() }}
{% endfor %}


Matrix field containing asset field blocks entry editing

Well, i found an answer. It seems it was caused by xdebug.

All fields disappearing except 'Title' after saving

Adding this to php.ini helped:

xdebug.max_nesting_level=200


Required a different operator

{% set affiliateLink = relatedEntry.offerLink ?? relatedEntry.affiliateUrl %}


Best way to create tags under new EntryModel?

To relate the tags, all you'd have to do is feed the entry's tag field an array containing tag IDs.

So, after creating (or finding existing) tags, you should end up with an array with one or more tag IDs.

Then, if it's a new entry, you would do:

$myTagIds = array(1,2,3,4); // your tag IDs
$entry = new EntryModel();
$entry->setContentFromPost(array(
    // ...
    'tagFieldHandle' => $myTagIds,
));

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


How to export Sprout Form submissions with a JSON API endpoint?

Please see the Sprout Forms Element API documentation page. If it doesn't address your answer, please update your question and I can clarify further.

Here's the example from the docs of both a Form and Form Entries being retrieved from the Element API:

<?php

use barrelstrength\sproutforms\elements\Form;
use barrelstrength\sproutforms\elements\Entry;

return [
    'endpoints' => [
        'api/sproutforms/<formId:\d+>.json' => function($formId) {
            return [
                'elementType' => Form::class,
                'criteria' => ['id' => $formId],
                'one' => true,
                'transformer' => function(Form $form) {
                    foreach ($form->getFieldLayout()->getTabs() as $tab) {
                        foreach ($tab->getFields() as $field) {
                            $fields[] = [
                                'field' => $field,
                                'folder' => $field->getFieldInputFolder()
                            ];
                        }

                        $tabs[] = [
                            'title' => $tab->name,
                            'fields' => $fields
                        ];
                    }

                    return [
                        'handle' => $form->handle,
                        'tabs' => $tabs
                    ];
                },
            ];
        },
        'api/sproutforms/<formId:\d+>/entries.json' => function($formId) {
            return [
                'elementType' => Entry::class,
                'criteria' => [
                    'formId' => $formId,
                    'status' => 'unread'
                ],
                'paginate' => true,
                'transformer' => function(Entry $entry) {
                    return [
                        'id' => $entry->id,
                        'dateCreated' => $entry->dateCreated,
                        'title' => $entry->title,
                        'customField' => $entry->customField,
                    ];
                },
            ];
        }
    ]
];


Multiple dropdown filters interfering with each other

If your goal is to filter by one drop-down value at a time then you could use an if statement to check if the passed value is set for each drop-down.  This will only work if each drop-down has an option that is blank or it submits on select so that the other drop-down is not set.

{% set query = "" %}
{% if craft.request.getParam('country1') and
      craft.request.getParam('country1') is not empty %}
    {% set query = craft.request.getParam('country1') %}
{% elseif craft.request.getParam('development1') and
          craft.request.getParam('development1') is not empty %}
    {% set query = craft.request.getParam('development1') %}
{% endif %}

{% for category in queryFilter %}

....markup...

{% endfor %}


How to trigger code once in a thank you page?

We do this by setting a flash message server side and then checking for this in the template. Flash messages are only shown once so no need to manually delete/unset. The best way to do this would be using a custom plugin that listens for the commerce_orders.onOrderComplete event:

<?php
namespace Craft;

class FireAnalyticsPlugin extends BasePlugin
{
    function init()
    {
        craft()->on('commerce_orders.onOrderComplete', function($event)
        {
            craft()->userSession->setFlash('successfulOrderPlaced', true);
        }
    }
}

Customer order page template:

{% if craft.session.getFlash('successfulOrderPlaced') %}
// Add Google Analytics here
{% endif %}


Using values from one entry as default values in another?

First of all I would like to leave a few links for you.

Pluginfactory.io is a page where you can create your "starting" files. It creates an empty Plugin, with all the required files/functions with example codes for routing and services....
The Docs about Craft Plugin developement

Then to the code: you'll need to insert a function like this in your Plugin's primary class

craft()->templates->hook('cp.entries.edit', function(&$context) {
    if ($context['sectionHandle'] === 'course') {
        // you can get these from a config file or you could create
        // plugin settings, I'll just insert an array here, it's faster
        $config = [
            'entryTypeOne'     => [
                'title'         => 'A title',
                'body'          => 'some information',
                'relationField' => [1, 2, 4] //<-- array of element ids
            ],
            'anotherEntryType' => [
                'title'         => 'Another title',
                'body'          => 'some more information',
                'relationField' => [] //<-- array of element ids
            ]
        ];

        /** @var \Craft\EntryModel $entry */
        $entry = $context['entry'];
        $entry->getContent()->setAttributes($config[$entry->getType()->handle]);
    }
}

However: unfortunately you can't set default values when the user changes the entry type with this method, thus we'll need another "hack".
As you can see in the Relabel Plugin Craft provides ways to change default functions. You can insert this javascript

Craft.EntryTypeSwitcher.prototype.onTypeChange =  function(ev)
{
    this.$spinner.removeClass('hidden');

    Craft.postActionRequest('entries/switchEntryType', Craft.cp.$container.serialize(), $.proxy(function(response, textStatus) {
        this.$spinner.addClass('hidden');

        if (textStatus == 'success')
        {
            var fieldsPane = this.$fields.data('pane');
            fieldsPane.deselectTab();
            this.$fields.html(response.paneHtml);
            fieldsPane.destroy();
            this.$fields.pane();
            Craft.initUiElements(this.$fields);

            Craft.appendHeadHtml(response.headHtml);
            Craft.appendFootHtml(response.footHtml);

            // Update the slug generator with the new title input
            if (typeof slugGenerator != "undefined")
            {
                slugGenerator.setNewSource('#title');
            }
        }
    }, this));
}

To change the default behavior when someone changes the entry type. All you have to do is to change the destination of the script
from

Craft.postActionRequest('entries/switchEntryType'

to something like

Craft.postActionRequest('yourpluginhandle/controllername/switchEntryType'

Then you'll take the default EntriesController function

public function actionSwitchEntryType()
{
    $this->requirePostRequest();
    $this->requireAjaxRequest();

    $entry = $this->_getEntryModel();
    $this->enforceEditEntryPermissions($entry);
    $this->_populateEntryModel($entry);

    $variables['sectionId'] = $entry->sectionId;
    $variables['entry'] = $entry;
    $variables['showEntryTypes'] = true;

    $this->_prepEditEntryVariables($variables);

    $paneHtml = craft()->templates->render('_includes/tabs', $variables) .
        craft()->templates->render('entries/_fields', $variables);

    $this->returnJson(array(
        'paneHtml' => $paneHtml,
        'headHtml' => craft()->templates->getHeadHtml(),
        'footHtml' => craft()->templates->getFootHtml(),
    ));
}

And do exactly the same like in the first function

$entry->getContent()->setAttributes($config[$entry->getType()->handle]);

Unfortunately if you want to take care of all use cases you have to overwrite another function. When someone is trying to create an entry via an ElementEditor(the thing that pops up when you click on "new entry") in a relation field. It works exactly the same like my first method and it's the same like Here


Is there a plugin like Compressor for Craft 3?

I don't think there's a single plugin, but looking through https://plugins.craftcms.com it looks like maybe Minify and Asset Rev would do it together.


Programaticaly create entry with simpleMaps field

I actually just had to do this for a project, so I hope this will shed some light on how to set the props:

I started by looking at SimpleMap_MapModel.php and its attributes.

The available properties are: ownerId, fieldId, ownerLocale, lat, lng, zoom, address, and parts. (Don't touch ownerId, fieldId, and ownerLocale—they'll get set automatically when saved!)

So, this means you can set any of the above by simply assigning an associative array to your EntryModel, before saving:

$entry->setContent([
  'simplemap_field' => [
    'lat' => $lat,
    'lng' => $long
  ]
]);

If you have the data already, and want to populate the address "parts", you can json_encode those into the parts attribute:

$entry->setContent([
  'simplemap_field' => [
    'lat' => $lat,
    'lng' => $long,
    'parts' => json_encode([
      'street1' => $address,
      'locality' => $city,
      'administrative_area_level_1' => $state,
      'country' => $country
    ])
  ]
]);

Not a huge fan of the way those "parts" are saved, but it's basically the serialized/cached response from Google.

The address attribute, as far as I could tell, is basically the value that ends up in the search bar, when you're using the field in the front-end. During our import, we were able to build a meaningful string here, from other data (i.e. a venue name and city), so if any records didn't have a complete set of information, admin didn't have to reconstruct the search, manually.

Unfortunately, SimpleMap will not geocode (or reverse-geocode) your information to fill in gaps… you'll need to manually save each entry. This was something we struggled with when building out import scripts, but fortunately only the more recent location-sensitive content really needed to be updated.


Is there a way to return the number of columns in a table?

entry.tableHandle is an array of all of the rows, and each row is an array with keys that are the column names and values that are the column values AND keys that are col1, col2, etc. and values that are the column values.

So you can do entry.tableHandle[0]|keys to get the keys, entry.tableHandle[0]|keys|length to get the number of keys, and finally (entry.tableHandle[0]|keys|length)/2 to get the number of columns.

You will want to check first that there is a row in the table - this won't work if there is no row 0.


I just return the form model object back to the template. Yii has built in validation and error handling within the models themselves. In the example email is the instance of your form's model.

The template:

{% if email is not defined %}
    {% set email = craft.postmaster.email() %}
{% endif %}

{% for error in email.getAllErrors() %}

{{ error }}

{% endfor %}

    To Email

    <input type="text" id="toEmail" name="toEmail" value="{{ email.toEmail }}" />
    {% if email.getError('toEmail') %}
    {{ email.getError('toEmail') }}
    {% endif %}

The controller:

$model = new Postmaster_EmailFormModel(craft()->request->getPost());

if(!$model->validate())
{
    // Prepare a flash error message for the user.
    craft()->userSession->setError(Craft::t('The email could not be sent.'));

    craft()->urlManager->setRouteVariables(array(
        'email' => $model
    ));
}
else
{
    $event = new Event($this, array(
        'email' => $model
    ));

    craft()->postmaster_forms->onEmailFormSend($event);

    $this->redirect(craft()->request->getPost('redirect'));
}


Assuming your store/brand field handle in your new channel is relatedEntryField, set your URL format when you're defining the channel section to:

{relatedEntryField.first().slug}-{slug}

That'll pull the slug from the first related entry, add the slug from your current entry, and populate your URL.

As an aside, relational fields are always "arrays" even if there's only one so you need .first().


You're likely missing the PHP JSON extension, which is a requirement to run Craft.


Looks like your php.ini file's memory_limit is set to 64M.  Bump it up to something higher like 128M or 256M.


Craft 2.X Local setup error – Craft not connecting to MySQL (via Sequel Pro)

Rather then passing the database details in virtualhost. You should put the database server details in db.php file as below.

DB.php file below:

<?php

/**
 * Database Configuration
 *
 * All of your system's database configuration settings go in here.
 * You can see a list of the default settings in craft/app/etc/config/defaults/db.php
 */

return array(

    // The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
    'server' => '127.0.0.1',

    // The database username to connect with.
    'user' => 'root',

    // The database password to connect with.
    'password' => '',

    // The name of the database to select.
    'database' => 'db_name',

    // The prefix to use when naming tables. This can be no more than 5 characters.
    'tablePrefix' => 'craft',

);

Your VHost file should be like below:

#
<VirtualHost *:80>
    ServerName crafty-coffee.local
    DocumentRoot "c:/wamp64/www/crafty-coffee/httpdocs"
    <Directory  "c:/wamp64/www/crafty-coffee/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

host file (C:\Windows\System32\drivers\etc) :

127.0.0.1   crafty-coffee.local
::1 crafty-coffee.local

This works perfectly for me. After this restart your Sequel Pro.


Does setting requireMatchingUserAgentForSession to false have any additional implications to be aware of?

The reason Craft stores the user agent string in the authentication cookie when logging in is to help prevent session/cookie hijacking.  If will validate that it is the same subsequent requests on the presumption if your cookie is hijacked, there's a significant chance that the browser that stole the cookie will have a different user agent string that the one the session was started with.

Granted, this isn't fool proof (user agent strings are easily spoofed) and some browsers store their version number (like you discovered) in the user agent string as well.  This is all well-and-good until your browser decides to auto-update, forcing the string to change and then auto-logging you out of Craft, which looks like what you're seeing.


For reference, this worked:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]


First up I'm not sure if I actually need to place any information into the Entry URL Format and Entry Template settings for the section

Nope, you can probably just un-check the Entries in this section have their own URLs checkbox in the Section settings and don't worry about it – I'm guessing the nav items should only function as pointers to "actual" entries, and won't need their own URLs or template.

  [...] in my Structure section I have an Entries field which allows me to
  choose an entry. I first of all have no idea of how to spit out this
  as the link instead of the {{ page.getLink() }} code above.

You can't use the getLink() function when the URL you want is the URL for the entry in the Entries field, and not the actual URL for the nav item (phew). You'll have to build the  tag yourself – something like this should work:

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

        {% nav page in pages %}

            {{ page.title }}
            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

        {% endnav %}

The crucial part here is the page.singleEntrySelector.first().url|default part for the  tags's href attribute.

It's important to realize that whenever you call an Entries attribute/field – such as page. singleEntrySelector in this case – Craft returns an instance of ElementCriteriaModel, which essentially is an array-like object. That means that even if the Entries field only has 1 entry inside it, you can't call page. singleEntrySelector.url directly – you'll need to explicitly select an entry inside the model, either by looping over it, calling a specific index (page. singleEntrySelector[0].url) or use the first() method to return the first entry. This is true for Asset, Tags, User and Category fields as well – basically any fieldtype that returns one or more related elements.

If you're wondering about the |default filter applied to the URL, that's there to prevent Craft from throwing an error if the page doesn't actually have an entry selected in the singleEntrySelector field. If you make the latter a required field, you can skip the |default part.

  [...] I'd like to have it so that when I'm on say Sub
  Service 1 that I can create a secondary navigation on the page which
  will show me everything from Services down to (in this example)
  Service 3 so pretty much a very standard secondary navigation output.

To output a sub navigation containing all nav "descendants" of the current entry, you'll first need to find the relevant nav item using the current entry in a relation query. Then, you can use the descendantOf() method to build the pages array, using the nav item as the ancestor:

{% set navItem = craft.entries.section('navigation').relatedTo(entry).first() %}
{% if navItem %}
{% set pages = craft.entries.descendantOf(navItem) %}

        {% nav page in pages %}

                {{ page.title }}
            ...
{% endif %}

If you want the sub nav to display the entire sub tree for the current entry – not just the descendents – this is how that could look:

{# Get the related nav item for the current entry #}
{% set navItem = craft.entries.section('navigation').relatedTo(entry).first() %}
{% if navItem %}
    {# Get the top level item #}
    {% set topItem = navItem.getAncestors().level(1).first()|default(navItem) %}
    {# Build a "pages" array w/ the top item and its descendents (child entries) #}
{% set pages = craft.entries.id([topItem.id]|merge(topItem.getDescendants().ids()|default([]))) %}

    ....

Note: If you use the same Entry for the Entries field multiple times in your Navigation Structure, results may vary. The examples above will pull the first nav item that has a relationship with the current entry, and disregard any others. However, a many-to-one relationship between the Navigation Structure's entries and the entries in the Entries field, with single sub tree output for the sub nav doesn't really compute – so I've disregarded that particular issue and assumed the relationship will always be one-to-one.


Mail: There was an error testing your email settings

Check your Craft storage/logs folder for the underlying error message.  You can also use these knowledge base articles to help debug what's going on based on what you find:

https://craftcms.com/knowledge-base/troubleshooting-email-errors

https://craftcms.com/knowledge-base/why-doesnt-craft-send-emails


How to get one entry's related stuff in Vuejs component

So your AJAX request likely hit an Element API or GraphQL endpoint, which would return the data to you as JSON.

What exactly that endpoint returns is totally up to the endpoint, but realize that it's not a PHP/Twig object that gets returned. It's a JSON-ified representation of it.

So for you to get the article.relatedTopics either the endpoint would need to have resolved the .relatedTopics and return them as JSON, or it could return an id or other information that you could use in another AJAX request to return that data.

More reading:

Lazy Loading with the Element API & VueJS
Autocomplete Search with the Element API & VueJS
Using VueJS + GraphQL to make Practical Magic


You can limit to only products that have multiple related categories like so:

{% set dressesCat = craft.categories...first() %}
{% set blackCat = craft.categories...first() %}

{% set products = craft.commerce.products({
    relatedTo: {
        targetElement: ['and', dressesCat, blackCat],
        field: 'productCategories'
    }
} %}


You could also delete all rows in your craft_elements table, which have type set to Entry (or whatever ElementType you want to delete).


Ok so in general this depends on if the custom field is on the product or the variant.   Assume the filed is called masterImage either way.

If the field is on a variant:
{% set image = lineItem.purchasable.product.masterImage.first() %}

If the field is on the product:
{% set image = lineItem.purchasable.masterImage.first() %}

Remember (either way) you should always check there is an image first really:

{% if lineItem.purchasable.product.masterImage|length %} ... set the image

In practise I usually have code that falls back to the product image if the variant image is not set for whatever reason:

    {% set image = lineItem.purchasable.masterImage.first() ?? null %}
    {# Fallback on product image if there is no variant image set #}
    {% if not image|length %}
        {% set image = lineItem.purchasable.product.masterImage.first() ?? null %}
    {% endif %}

(Note here I am not doing the initial test on the asset because I am instead using the null coalescing operator)


Why is Redactor cutting off Headings after Heading 2?

The client was using a Mac and the trackpad scrollbars are set to only show when over scrollable content. This is embarrassing, but the issue is resolved.


Date filtering returning wrong results - timezone issue?

Essentially you're running into this same issue: Using user-selectable timezones to show localized post dates

Not terribly pretty, but as a workaround, you can do something like this:

{% set start = date("2017-11-09 00:00:00")|date_modify("+7 hours")|date('Y-m-d h:i:s')  %}
{% set end = date("2017-11-09 23:59:59")|date_modify("+7 hours")|date('Y-m-d h:i:s')  %}

{# +7 hours is because America/Denver is UTC-7, but would need to be adjusted to +6 hours when observing daylight savings time #}

{% set orders = craft.commerce.orders.dateOrdered('and', '>= ' ~ start, '<= ' ~ end).find() %}

{% for order in orders %}
    {{ order.dateOrdered | date('Y-m-d H:i:s e') }}<br/>
{% endfor %}

Also, note that this should "just work" in the upcoming Craft 3 as well.

There might be a cleaner way to do this using @carlcs's workaround, but I'm not seeing it at the moment.


Missing templates using PHPStorm when using Craft 3

Was probably a bug in PHPStorm 2019.1.

Currently using 2019.1.2 and the warning disappeared.


project.images is an array because you are eager-loading the images.

Since you’re only loading one project entry, you’re not actually gaining anything by eager-loading the images (or category), though. In fact, you’re actually slowing things down a bit. Eager-loading does come with a little bit of overhead, so you should only use it when you’ve got an “n+1” problem, as described on the Eager-Loading Entries page.

So to get this working, just remove the with param.

{% set project = craft.entries()
    .section('projects')
    .orderBy('RAND()')
    .one() %}

{% paginate project.images.limit(1) as images %}

Note that this will also affect how you access your category, as project.category will go from an eager-loaded array, back to a category query.


I should've realized that this was a plugin issue, that changes everything. Thanks for the lead, Brad.


When should I build upon existing models in my own plugins?

BaseComponentModel, BaseElementModel and BaseEntryRevisionModel all ultimately end up extending BaseModel, which itself extends Yii's CModel.

I like to think of them, roughly, as beefed up Data Transfer Objects.  Primarily useful for transferring data throughout the various layers of Craft (templates, controllers, services, etc.).

Regarding which ones you extend, it depends entirely on what you are trying to do in your plugin and with your Models.

BaseModel is the most "generic" one as far as Craft is concerned that gives you all of the Craft specific attributes of Models.

BaseElementModel is useful if your plugin is dealing with Element Types.

BaseComponentModel is useful if your plugin is dealing with Component Types (tools, widgets, tasks, etc.).  You can check the craft/app/enums/ComponentType.php enum for a full list.

And BaseEntryRevisionModel is pretty self explanatory.

And there is nothing stopping you from extending things like Craft's own EntryModel directly, if you need specific features that it has.


Checking for first time an entry is "published" i.e. saved with a Live status

There isn't an "event" that gets fired when an entry goes live, but you should be able to listen to the onSaveEntry event, then check the same criteria that Craft uses to determine if an entry is live or not.

As far as tracking if it's the first time the entry had a live status or not, it's kind of lame, but your plugin could have a Record/table that kept track of the entry ID and status so you'd know if it was the first time an entry ID had a status of Live or not.


Is it possible to create a page that shows only a specific post type with its own url?

Certainly possible and simple too :)

First in the CP go to:

Category->Settings

You'll want to set your Category URL formats and Category Template to reflect your URL scheme and desired location of your template file.

Then create an _entry template in the directory you specified above for example /categories/_entry.twig

When you head to the URL above your template will load with an entry variable that reflects whichever category you are browsing to.

In the _entry template to get all the entries related to the current category:

{% set entries = craft.entries.relatedTo( entry ) %}

(note this will default to 100 entries if you want more append .limit(101) etc. or .limit(null) to get them all.

and finally to load a layout based on the entry.type simply:

{% include ["_layouts/types/" ~ entry.type, "_layouts/types/default"] %}

where the default layout is for all entries that don't need any special layout.


There are many ways to skin this particular cat I'm sure, but the easiest way is just to use the manual payment gateway and a/some custom field(s) on your order to record the purchase order details.

Whenever you call the updateCart controller, from your input form where you gather the PO details, you can then pass in the POST parameters as fields[purchaseOrderDetails] to save the data to your field named purchaseOrderDetails for later processing.

Update using your code above:

{% if not craft.commerce.paymentMethods|length %}

No payment methods available.

{% endif %}

{% if craft.commerce.paymentMethods|length %}
    <form method="POST" id="paymentMethod" class="form-inline">

        <input type="hidden" name="action" value="commerce/cart/updateCart">
        <input type="hidden" name="redirect" value="commerce/checkout/payment">

        {{ getCsrfInput() }}

        Payment Method

        <select id="paymentMethodId" name="paymentMethodId"
                class="form-control">
            {% for id,name in craft.commerce.paymentMethods %}
                <option value="{{ id }}"
                        {% if id == cart.paymentMethod.id %}selected{% endif %}>{{ name }}</option>
            {% endfor %}
        </select>

            Purchase Order Number
            <input type="text" name="fields[purchaseOrder]"
                placeholder="Purchase Order"
                class="purchase-order-field"
                value="{{ cart.purchaseOrder }}">

    </form>
{% endif %}

All I have really done here is change how you're referencing the filed  on our order (which must have a handle of purchaseOrder for the above to work).  And I am presuming you have the cart available in cart obviously.

Don't forget to accept the answer if it gets you going!
Untested, but that's pretty much it, you were almost there really!


I think you should look into "Globals" for content you want to edit, and re-use throughout your entire site.

http://buildwithcraft.com/docs/globals


Using Feedme to import data from ExpressionEngine 2

I had a similar error when I was doing an import; some entries made it and others didn't. It ended up I had an error in my JSON file so be sure to lint it first.


Yii will check for the following server environment variables when determining if it’s an SSL request:

HTTPS – should be set to “on”, “ON”, or “1”; or
HTTP_X_FORWARDED_PROTO – should be set to “https” or “HTTPS”

Apparently this is a common issue when running PHP on Nginx, since that HTTPS env variable is only an Apache convention.

Here’s an article that demonstrates how to fix it. According to that, you just need to add the following to your server config.

fastcgi_param HTTPS on;

You can probably add it right before/after your other fastcgi_param line.


Set Parent Template Defined Content to Output in Child Template

You could use include...with, as specified in the Twig Docs here

Example for your case:

{# in Template C #}
{% include 'template-d.twig' with {'foo':'Hello World'} %}

This should give Template D access to foo. Hope that helps!


By default, Craft requires that a browser has a user agent string and IP address for a valid authenticated session, and once that session starts, the user agent string must remain the same for the remainder of the session.

It sounds like whatever browsers are being used on the mobile devices aren't providing this.

You can alter this behavior with these config settings:

https://docs.craftcms.com/v3/config/config-settings.html#requireuseragentandipforsession

https://docs.craftcms.com/v3/config/config-settings.html#requirematchinguseragentforsession


Displaying entires by year from a custom date field

Looks like I finally found an answer to it

year being my param

date being my custom date field

{% set dateParam = 'and, >= ' ~ year ~ '-01-01, < ' ~ (year + 1) ~ '-01-01' %}

    {% for entry in craft.entries.section('evenements').order('date desc').date(dateParam) %}

{{ entry.title }}

    {% endfor %}