{% requirePermission %} with OR condition I need to use requirePermission tag to check if one or another permission is active.

I want to reproduce something like this:

{% if currentUser.can('perm1') or currentUser.can('perm2')  %}
   <!-- My page stuff -->
{% else %}
   {% exit 403 %}
{% endif %}

How can I make this possible {% requirePermission "perm1_or_perm2" %} ?

The {% requirePermission 'perm1' %} tag only supports a single permission. Behind the scenes it's effectively the same as:

{% if not currentUser.can('perm1') %}
    {% exit 403 %}
{% endif %}

So I think either what you already have, or this:

{% if not currentUser.can('perm1') and not currentUser.can('perm2') %}
    {% exit 403 %}
{% endif %}

<!-- Your page stuff -->

Is probably your best bet at the moment. Checking that the user doesn't have both permissions, is the same as checking they do have one or the other.


Laravel Homestead & Craft: Craft can’t connect to the database with the credentials in craft/config/db.php I'm following these instructions to Setting up a local dev environment for Craft CMS with Laravel Homestead.
When I go to http://my-craft-site.dev/admin, I get:

  Craft can’t connect to the database with the credentials in
  craft/config/db.php.

Not having much luck with Google/Stack searches on the error message. I can connect to the Homestead DB via Sequel Pro using the credentials in db.php so I’m a bit confused by the error message.
DB Credentials:

u: homestead
p: secret

When in doubt, reinstall, or in this case do it over again from the top. That fixed it.


Craft Commerce: Addresses not showing in profile I have recently added the Customer Info field to user profiles for the CP. I noticed however that the recorded addresses for the user are not listed. I checked against the order and there is addresses associated with it. Is there something I need to be doing to enable the address to show?

See screen shot:

Its likely that the order was made while a guest user, then signed up, so the guest order was then associated with the new user - but the addresses used in that guest order don't get copied to the address book of the new user.


How to manage breakpoint releases when updating Craft via composer When logged in to Craft, the "Utilities" tab will show you all the latest releases you can update to. In some cases, it will report that you have reached a breakpoint release:

  You’ve reached a breakpoint! More updates will become available after you install Craft CMS 3.1.34.3.

If I'm updating to Craft 3.2 via composer, to ensure the all the migrations get run properly and respect that breakpoint, I believe that I would need to upgrade on the command line in two steps:

Run composer require craftcms/cms:3.1.34.3
Run db migrations
Run composer require craftcms/cms:3.2.0 (or whatever the latest is)
Run db migrations

Over time, as Craft has multiple breakpoint releases it's possible that there are several breakpoint steps that need to be hit while updating from composer directly and, as far as I know, the only place to get information on breakpoint releases is via the Control Panel.

It is also possible for plugins to add breakpoint releases. So, there is a potential scenario that you have to know of and respect both Craft and plugin breakpoints. I'm not sure how Craft handles plugin breakpoints in the CP as I have not seen any do that yet, but I believe the awareness of them would also be necessary if you are doing everything from the command line.

So, it's possible if we have an older site upgrading through several breakpoints we need to do something like:

Run composer require craftcms/cms:3.0.41.1
Run db migrations
Run composer require craftcms/cms:3.1.34.3
Run db migrations
Run composer require plugin/some-plugin:1.2.3
Run db migrations
Run composer require craftcms/cms:3.2.0 (or whatever the latest is)
Run db migrations

So, my questions:

If we are upgrading to Craft 3 for the first time, should we be targeting the first breakpoint release as the initial version that we upgrade to?
Is there any good way to know which breakpoint releases exist in Craft (aside from just seeing the next breakpoint on the CP utilities tab)?
Is there any good way to know which breakpoint releases exist in Plugins?
Can you summarize the potential issues that would arise if someone skipped breakpoints while upgrading?

So far, Craft 3 hasn’t had any “real” breakpoint releases in the way that Craft 1 and 2 had, yet – where you would have a real issue if you were to update past them before updating to them.

Craft 1 and 2 had a handful of them, which we took as opportunities to clear out the migrations/ folder, and clean up some PHP code. If you were to (somehow) update past one in Craft 1/2, Craft would actually stop you in your tracks before you were able to run migrations, and tell you to downgrade to the breakpoint your skipped first.

If/when we release a real breakpoint release in Craft 3, Craft will do the same.

To date, Craft 3 has only had 2 “faux” breakpoints:

When updating from > 3.0.0-alpha.1 && < 3.0.41.1, the built-in updater will have you update to 3.0.41.1 before going past it. This is because Craft 3.1 was a pretty huge update that revealed some bugs in the 3.0 updater. So 3.0.41.1 was released with some fixes to the updater, to ensure people could update to 3.1 more gracefully. Not an issue if you were using composer update to update though.
When updating from >= 3.1.20 && < 3.1.34.3, the built-in updater will have you update to 3.1.34.3 before going past it. This is because there were a couple bugs in the project-config/rebuild command (added in 3.1.20) that we fixed in 3.1.34.3 which could create trouble for the 3.2 update, had the command been used. So adding the faux breakpoint combined with a suggestion in the 3.2 release notes to re-run project-config/rebuild was just a way to reduce potential support for 3.2 updates. If you were to composer update without following those directions, either the 3.2 update would work or it wouldn’t; in the latter case we’d end up steering you right in support.

Regarding plugins, we don’t currently offer support for plugin breakpoints, and aren’t very likely to add it, unless a really good use case comes up.


How can I set up a filter URL like example.com/category/foo/type/bar/country/usa Given a category based set of entries/products, and a filter system based on tags, how would I accept (one of) the following urls and let one template process them all (not interested in the processing, just want to know how to set up the route):

example.com/category/foo -> category page, containing products
example.com/category/foo/type/bar -> category page, filtered by relation to tag (group = 'type') with value 'bar'
example.com/category/foo/type/bar/country/usa -> category page, filtered by multiple relations (filters)
example.com/category/foo/country/usa/type/bar -> category page, filtered by same relations as above

This would be more SEO-friendly than example.com/category/foo?type=bar&country=usa

Anyone done this before?

The parameterized paths (as opposed to the queries) implies a certain hierarchy. According to Google's SEO document, you have to anticipate that users will cut a part of the URL off. What happens if they cut out "usa", but "country"?

What you're doing right now is filtering/searching, not creating a hierarchy. So, you're complicating your own routing (making it more likely to fail and thus hurting your SEO even further), and not conveying the information particularly accurately.

If you want the parameterized URLs as opposed to query strings, you'll want to reorganize your URL structure to be hierarchical -- i.e. - products/shirts/tshirts -- and drop off the "parameter names" that you're trying to shoe-horn in.

Also, consider whether that particular page actually needs to be indexed by search engines, and if it needs to be indexed with the query string. Can you simply allow it to be indexed without any filtering? Does it need to be indexed at all? If you don't need to index it, then you can keep the query string for human usability, and tell spiders not to index it at all. If you don't need to index it as filtered and going to the page, without a query string, results in the non-filtered content, then most spiders will do that by default.

For example, look at google.com, before and after a search. Obviously, search result pages don't need to be indexed (nor would you want to, because that would result in a ton of botched indexed), but the main page, itself, probably should be. As a result, they use a query string that includes q=searchstring on their search results page.


Richtext field removing inserted links I have a RichText field using a standard config. "Clean up HTML" and "Purify HTML" are OFF.

I have a page with a paragraph of text, then an unordered list. After that list, I try to insert another paragraph and add a line with a mailto link in it.

No matter what, the link gets removed/stripped out. If I move the paragraph up before the UL, it works. But being after the UL list, it's getting stripped out.

Essentially the text in the editor looks like:

text

title line of text

title line of text

Send us a message

I did try checking both purify and clean HTML options ON, but that didn't work either. I've tried inserting the text via html view as well as visual view. Still can't get it to stick. I've tried adding multiple paragraphs after the UL list, but HTML is getting stripped out of everything after the list.

Anyone have any ideas?

My standard config json is:

{ buttons: ['html','formatting','bold','italic','unorderedlist','orderedlist','link','image','video'],
plugins: ['fullscreen'],
toolbarFixedBox: true }

Craft Client 2.4.2692

The answer here is to disable the mod_security2 rule on the admin folder as I was tripping the SQL Injection prevention rule (#300015) upon saving the Entry form.

This is a server setup that uses cPanel and Apache 2.2.

Edit file:

/usr/local/apache/conf/modsec2/whitelist.conf

Add the following rule:

<LocationMatch "/admin/">
  SecRuleRemoveById 300015
</LocationMatch>


Managing shared content in Craft I'm fairly new to Craft. I have a question about how to manage and setup the editing of shared content in Craft which is used on multiple pages.

As an example I have a Mailing List signup element which will be used across multiple pages. In my templates I'm using an include:

{% include "includes/_mailing-signup" %}

I come from Perch where you could make a Region of content shared which would take it out of the page and into a 'Shared' area in the admin.

What's the best way to approach this in Craft where content can be edited in one central location to update on all page?

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


Staging / Production w/ common DB and Assets I'm hoping to implement staging and production installations for a larger scale Craft project I'm working on. My plan is to have the following structure:

/staging.domain.com
-- Complete Craft Installation

/domain.com
-- Complete Craft Installation
-- Image Assets

Updates would get done on my local server and then pushed to the staging domain, and finally cloned to the production domain. The two would share the same database and images would live on the production URL. This would allow me to see client updates to content while I make changes to templates and presentation files. I would also be able to make and test Craft software updates in the background.

From reading the documentation I would use the Sites settings to add in both domains and then set variables (dev mode, for example) in the general.php config file.

Does this sounds like a proper set up for this situation?

One optional additional change would be to move image assets off the production server and onto their own (cookieless) domain...

Many thanks in advance!

Database

I strongly discourage you from letting Staging and Production share a database. That is a recipe for disaster.

Your Staging site should be semi-disposable, and it's likely that your client will treat it as such. The last thing you want is for someone to make a change in Staging without realizing that they are also making the same change in Production. It's counterintuitive and dangerous.

Instead, have your Staging database be a copy of the Production database. There are several ways to do this, and with the right tools it is actually very simple to clone the database on a regular basis.

I'd recommend using Craft Scripts by Andrew Welch to quickly & easily clone the database. I've found the pull_db.sh script to be quite invaluable.

Image Assets

Cloning images is also possible (Craft Scripts has a tool for that), but you may find that it eats up a ton of server space. This, of course, only matters if you're storing your asset files in a local folder. If the assets are cloud-based, then cloning them is a non-issue.

So instead of cloning your image files, I highly recommend the new Untransform plugin by Ben Croker. It allows your Staging server to actual use transformed images directly from the Production server. There won't be any need to store a second copy of those files, the Production site can provide the originals to your Staging environment.

Local Dev

You can use both of the aforementioned techniques on your local machine as well. Indeed, that's what they were originally created for.


Is it possible to separate variant options on a front end add to cart form? Is it possible to have separate variant option fields on a front end add to cart form?

For example… have a separate select field for Color and a separate select field for Size?

It's definitely possible and doesn't really need any custom back end code to be done in general.

Ultimately all add to cart options in Commerce are just a simple case of POSTing the variant id and the quantity of that variant.

Generally I would do this all in twig & a bit of JS.

E.g. In twig I wouldt loop through all variants (checking for stock as I go) and build up a JSON array of all the combinations of colour & size, and their availability due to stock.  I'd then 'pass this into' my form as a data-variants attribute.

Actually building the selects is slightly trickier because one will depend on the other but basically you'd probably want some JS that listens to your selects and looks at your passed in array to see if a particular size and colour combination was in stock - if a chosen combination is not, some sort of visual indication and disable the add to cart button, otherwise if it is in stock the form just posts the variant id and the qty and away you go.

Updated with some sample  code:

Here's some untested/pseudo code that should get you on the right track:

so the important thing to understand is that the descriptive data of a variant is really a completely separate concern to the sku of the variant - which in turn is not actually all that relevant to commerce - the variant id is really all that matters in the end in terms of addToCart.  For specifiying the variant data you can do it any way you like really but in this case if it's just say 3 colours and 3 sizes, then a simple approach would be a dropdown for each of those, with handles colour and size say.

You then just make the 9 variants, choose the colour and size for each, and enter the sku for each.

Then, you want to make the JSON for use in the JS.  (It's hard for me to see how you'd have a good UX without JS here, to be honest).

Here the |jsonencode filter is handy.  Something along the lines of:

{% set stockArray = [] %}
{% for variant in product.variants %}
    {% set stockArray = stockArray|merge([{variantId:variant.id,
                                          variantColourAndSize :variant.colour ~ "-" ~ variant.size,
                                          variantIsUnlimited:variant.unlimitedStock,
                                          variantStock:variant.stock,
                                          }]) %}
{% endfor %}

Then you output your form and pass this consolidated data in to it so it's accessible in the JS:

<form id="OrderForm"
    data-stockarray="{{ stockArray|json_encode() }}"
    data-action="/actions/multiAdd/multiAdd"
    data-redirect="/cart"
    etc

>
<selects here>

The rest is really just JS operating on that json data - this is thoroughly pseudo code since it's Friday night :) - but should be enough to get the idea:

var $form = document.getElementById('OrderForm');
var stockArray = $form.dataset.stockarray;
// Listen to your selects and look up in this array whether the matching colour/size variant is in stock/has unlimited stock
var variantKey = $select1.val() + "-" + $select2.val();
if(stockArray[variantKey].variantIsUnlimited || stockArray[variantKey].variantStock > 0 ){
// Enable/Disable your add to cart button accordingly
    $addToCartButton.show();
}
else {
    $addToCartButton.hide();
}


Can I extend entries listing views (currently or in the future)? Is there a way to show custom columns in the backend with entries listing views? Or can it be a feature in the future?
For example: show category as a column in the news overview in the backend

The current answer to this is no, not out of the box.

The unofficial answer to this is, it has been discussed several times out there in the forums and there are some good arguments to make that this is a core part of 'content management'.

The developer-friendly answer to this is yes, you can control those columns if you create a plugin with a new Element Type.  Your Element can extend the default Entries Element Type and customize the columns in the listing views.

Within your Element Type:

defineTableAttributes() - Returns the attributes that can be shown/sorted by in table views.

modifyElementsQuery() - Modifies an element query targeting elements of this type.

getSources() - Returns the element type's sources and can be used to trigger filters on the table view.

You can create a new listing template with these three lines of code:

{% extends "_layouts/elementindex" %}
{% set title = "Page Title"|t %}
{% set elementType = 'PluginName_Element' %}

Is this a smart thing to do?  It probably depends on your use case.  Elements are powerful, but they also take time to develop and maintain.  While you can easily extend a class, several parts of the Control Panel UI are not as easy to extend if you start adding variations on the intended use cases. Make your case to P&T about this feature being a core part of content management and if enough others do the same, you may save yourself a lot of custom development.  I think there is a strong case that this type of feature can only be done well in the core.


Delete all old versions from the database I've been working on a site for a while in beta. The number of versions for all the pages is getting big and the database is now over 2MB. I'd love to just delete all the old versions of all pages when I go live with the site. Is there any easy way to do this?

I just wrote a plugin that deletes all versions (truncates the craft_entryversions table) and then saves a new version for each of your entries, so you can later revert back to it:

Delete All Entry Versions


How do I get Pagination to Work? I thought this would be easy.  I cut and pasted code that works from the Mijingo Happy Lager tutorial site. But, I keep getting the template error below.

My code...

{% paginate craft.entries.section('posts').limit(8) as postEntries %}

    {% for post in postEntries %}

{{ post.title}}

{{ post.postDate | date('F d, Y') }}

    {% endfor %}

            {% if paginate.prevUrl %}

Previous Page

            {% endif %}

            {% for page, url in paginate.getPreviousUrls(5) %}

{{ page }}

            {% endfor %}

{{ paginate.currentPage }}

            {% for page, url in paginate.getNextUrls(5) %}

{{ page }}

            {% endfor %}

            {% if paginate.nextUrl %}

Next Page

            {% endif %}

{% endpaginate %}

The error message...

  Neither the property "getPreviousUrls" nor one of the methods "getPreviousUrls()", "getgetPreviousUrls()"/"isgetPreviousUrls()" or "__call()" exist and have public access in class "Craft\PaginateVariable"

What am I forgetting?

A couple of years later, I ran into the same issue. In case there are others looking, it looks like this line:

{% for page, url in paginate.getPreviousUrls(5) %}

Should be:

{% for page, url in paginate.getPrevUrls(5) %}


How to implement mailchimp plugin to target different mailists? I'd like to be able to have multiple (2) Mailchimp subscribe forms on the same web site. Each would target different mail lists so I can use one on a landing page for example. I've noticed that the target mail list is set in the List ID field in the plugin settings. Can I simply add another installation of the plugin at this level to accomplish my goal?

If the plugin in question is my MailChimp Subscribe plugin, you can easily target different lists by adding a hidden field called lid to your form with your list ID:

<input type="hidden" name="lid" value="2fd6ec09cf">

This will override the config setting (see the examples under configuration in the repo for more information on this).


Customise the URL for an asset I need to prepend a URL to the beginning of an asset URL in order to track stats for a podcast via Blubrry.

What are the options?

Specifically I need to drop the https that would appear in my URL by default.

This doesn't work with Blubrry specifically, but you can use it to get the data into Google Analytics for things that aren't normally trackable: Instant Analytics

Check out the Tracking RSS Feeds section.


URI is not a valid URI I'm getting an interesting (new) error when adding (or editing) entries in Chinese. If the slug is in Chinese I now get the following error:

URI is not a valid URI

It's interesting because I wasn't experiencing that with Craft 2.2. It was allowing me to save entries with Chinese characters in the URI. After upgrading to Craft 2.3.2615 it looks like all Chinese language URIs are now disallowed?

Is this intended behaviour?

Turns out this was a bug introduced in 2.3 and will be fixed in the next release.

Update:

This was fixed in Craft 2.3.2617.


Filter results by users contained in a Users Relations RelatedTo field I would like to exclude entries from appearing in the template results that contain Users from specific User group.

My code below works if all the User(s) in the RelatedTo field are part of the excluded User group, but it doesn't work if the field contains Users from both the excluded group and a non-excluded group.

{% set excludeFellows = craft.users.groupId('not 11') %}

{% set entries = craft.entries.section('logsQA').logGeneral_statusWorkflow('submitted').relatedTo(
    { targetElement: excludeFellows, field: 'logGeneral_sonographerName' }
) %}

(Also if it's better to check for specific User IDs rather than a User Group for my excluded list that's fine too. I only have 3 Users to exclude.)

If I understand you correctly, you want to exclude any entry that has any user from a certain user group selected in a certain Users field.

Here's an approach that I believe would work:

{# Get the users that should be excluded #}
{% set excludedUsers = craft.users.group('groupToExclude').limit(null) %}

{# Get the entries that should be excluded #}
{% set excludedEntries = craft.entries.section('logsQA').relatedTo({
    targetElement: excludedUsers.ids(),
    field: 'logGeneral_sonographerName'
}).limit(null) %}

{# Get the entries that should be displayed #}
{% set entries = craft.entries.section('logsQA').id('and, not '~excludedEntries.ids()|join(', not ')) %}

What the above does is to first pull the users that should be excluded (you could use the groupId parameter instead of group if you want to), before using those users to pull the entries that should be excluded.

Finally, the entries that should be displayed are pulled – the key here is the use of the id parameter to specifically exclude a list of entry IDs.


Multi-Environment S3 Asset Paths If I have three environments; local, dev, and live, and want assets to be setup like this:

local: stored in a local directory (/public/uploads)
dev: stored on S3 dev bucket
live: stored on S3 live bucket

What's the best way to set this in a multi-environment config?

Unfortunately, this isn't currently possible.

This feature request is very similar to what you're requesting... however, it would still require that all of your environments use the same type of asset source.


Issues with Craft Commerce We have a dutch website build with Craft CMS and for the webshop Craft CMS Commerce. This has been done by a design company. We don't receive any orders and I am wondering if the whole process is okay. Translate version in English will be launched in September. Als the search filter is not working properly. Can someone have a look at it and could give me some reply? I can do the standard items in the backend from Craft but no codes. The webshop is: www.hulshofbusinesscases.com. Thanks for listening and maybe you help. Greetings Marina

Sounds like you need to get in touch with the developers or find some new developers. But run a test purchase for peace of mind anyway.


Get the three last Matrix blocks I would like to include a file on every block but the last three. How can I accomplish this?

You can fetch all elements and slice the last 3 elements from them

{% set entriesList = entry.fieldHandle.find() %}
{% set start = entriesList|length - 3 %}
{% set end = entriesList|length %}
{% set lastThree = entriesList | slice(start, end) %}

Of course you need to make sure you have at least 3 objects your array


using craft.request.getParam to filter by relations I'm requesting entries through a search field like so:

{% set params = {
  section:      'tours',
  startloc:     craft.request.getParam('zoekplaats')
} %}

{% for entry in craft.entries(params) %}
...etc..
{% endfor %}

which works fine. However, as soon as the 'startloc' field type becomes an 'entry' (thus a relation) I can't simply state 'startloc:' anymore, as it has become an entire object. However, I'm quite limited to the syntax I can use within that params field.

I've tried many things but can't really figure it out. Anyone that knows what the correct way to do it would be?

Thanks a lot!!

Wow, ok so I spent all day on this, I seem to have gotten it to work, but to be honest, I'm not 100% sure why/how this works. Anyways, I altered the code in the answer given here: Searching a specific section by four different types of parameters?

And ended with this:

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

 {% set params = {
section:        'tours',
limit:      null
} %}
                   {% set relatedParams = ['and'] %}

{# plaats #}
{% if craft.request.getParam('zoekplaats') %}
{% set plaats = craft.request.getParam('zoekplaats') %}
{% set params = params|merge({'startloc':plaats}) %}
{% endif %}

{# Schip #}
{% if craft.request.getParam('zoekschip') %}
{% set zoekschip = craft.entries.section('ships').shipName(craft.request.getParam('shipName')).first %}
{% set relatedParams = relatedParams|merge([{ targetElement:zoekschip }]) %}
{% endif %}

                        {# add relatedParams to params #}
{% if relatedParams|length > 1 %}
{% set params = params|merge({'relatedTo':relatedParams}) %}
{% endif %}

{# perform search #}
{% set searchParams = craft.request.getParam('q') %}
{% set entries = craft.entries(params).search(searchParams|trim) %}

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

{% endfor %}

Now, this works, it's pretty awesome, and after examining I understand it, and have a better understanding of how the

  relatedTo: {targetElement:  }

works :)

My next challenge, is to add another search param, regarding the dates.
The tours section currently has a matrix field which has one block, called 'vertrekdatum'. (departuredate) How I add the date to the param, and check whether any tour has that date in their blocks, and output if so..?

Thanks heaps in advanced!


Define database details in index.php I've got a multi-environment setup similar to the following, and thinking about adding database details to the index.php. In this way, I can pretty much just edit the index.php when creating new websites - staying out of app/config.

switch ($_SERVER['SERVER_NAME']) {
    case 'local.craft.dev':
        define('CRAFT_ENVIRONMENT', 'local');
        define('CRAFT_DB_USER', 'root');
        define('CRAFT_DB_PASSWORD', 'craftycraft');
        define('CRAFT_DB_DATABASE', 'local');
        break;
    case 'staging.com':
        define('CRAFT_ENVIRONMENT', 'staging');
        break;
    default:
        define('CRAFT_ENVIRONMENT', 'production');
        break;
}

Would there any potential security issues with this? I imagine being in the web root might be risky - but would having this information in db.php a level up really made a difference to a hacker?

Would like to hear your thoughts!

As long as Apache and PHP are working like they’re supposed to, this is fine. Files that end in .php should always get processed by PHP before they’re served to the client.

Here are the risks:

If PHP is ever disabled, or the server is misconfigured so .php doesn’t get processed by PHP, then Apache will start serving that file directly, exposing all of your code (and in this case, your DB credentials).
Every PHP file that gets loaded after index.php will be able to see those constants, and potentially echo them out. (Most likely this would be your own doing, e.g. you might be echoing out everything from get_defined_constants() while trying to debug something.)

If you can live with those, go for it. Personally, I’d say it’s just not worth it.


How would I create a select element with the 14 days from today as options I'm looking to create a select (dropdown) form field that includes the days and dates for the next 14 days, starting from today, as options.

My initial thoughts on how to construct this would be to set today {% set today = now|date("l dS F Y") %} and then set a date 13 days from now {% set finalDate = now|date_modify("+13 day")|date("l dS F Y") %} and then somehow put that into a range loop. It is the last part I'm having trouble getting working, if it is at all possible.

Once I have that range I would ultimately like to pass it as option values to the select macro mentioned in another question like so:

{{ forms.select({
    options: ['Today', 'Tomorrow', ...]
}) }}

Thanks

You're close! If there's one thing I've learned about Twig, it's easy to overthink it...

Create an array with the first date, then merge the rest of dates into the same array with a for loop. Just increment the day in the range:

 {% set rangeOfDates = [ now|date("l dS F Y") ] %}

 {% for i in range (1,13) %}

     {% set rangeOfDates = rangeOfDates|merge( [ now|date_modify("+" ~ i ~ " day")|date("l dS F Y") ]) %}

{%endfor%}

Then in your forms macro:

{{ forms.select({
    options: rangeOfDates
}) }}


No assets found when searching in different locale At the moment I'm working on my first Craft CMS project. There I have two different locales that share the same assets folder.

The assets can be seen and used between the different locales but when I try to search I only get results in one locale. This is strange because they show up in the full list when selecting that locale.

Any tips? Did I miss a certain setting?

This is a known bug on Craft 2 that has been resolved in the upcoming Craft 3 release.  Here's the original Github issue: https://github.com/craftcms/cms/issues/17


Craft paginate not working in merge Queries My Code:

{% set Entries              =   craft.entries.section('not loanConsultants').search(searchQuery).orderBy('dateCreated desc').all() %}

{% set loanConsultants      =   craft.entries.section('loanConsultants').type('loanConsultants').search('title:'~searchQuery).orderBy('dateCreated desc').all() %}

{% set Branch               =   craft.entries.section('loanConsultants').type('branches').search('title:'~searchQuery).orderBy('dateCreated desc').all() %}

{% set loanConsultantsMerge = loanConsultants|merge(Branch) %}

{% set mergeResults         = loanConsultantsMerge|merge(Entries) %}

Pagination code:

{% paginate mergeResults as pageInfo, pageEntries %}
{% for entry in pageEntries %}

{{ entry.title }}

{% endfor %}

{% if pageInfo.prevUrl %}Previous Page{% endif %}

{% if pageInfo.nextUrl %}Next Page{% endif %}

The paginate tag requires an element query to work and by calling .all() on your queries, you've turned them into an array of elements.

Something like this should work:

{# Grab all of the IDs #}
{% set entries = craft.entries.section('not loanConsultants').search(searchQuery).ids() %}

{% set loanConsultants = craft.entries.section('loanConsultants').type('loanConsultants').search('title:'~searchQuery).ids() %}

{% set branch =   craft.entries.section('loanConsultants').type('branches').search('title:'~searchQuery).ids() %}

{# Merge the IDs together #}
{% set loanConsultantsMerge = loanConsultants|merge(branch) %}
{% set mergeResults = loanConsultantsMerge|merge(entries) %}

{# Build new query #}
{% set results = craft.entries.id($mergeResults) %}

{% paginate results as pageInfo, pageEntries %}
{% for entry in pageEntries %}

{{ entry.title }}

{% endfor %}

{% if pageInfo.prevUrl %}Previous Page{% endif %}

{% if pageInfo.nextUrl %}Next Page{% endif %}


Craft 2.6 Asset Upload 500 Error (EC2 and Amazon S3) Our site is hosted on AWS with assets uploading to an S3. Everything has worked great until the last update. Locally, I can upload assets without issue, but on the stage we're receiving an error /index.php?p=admin/actions/assets/uploadFile 500 (Internal Server Error) preventing us from uploading. The files upload to the directory, but the upload bar hangs.

Within the assets directory when pressing "refresh" on the bucket name, we receive the error /index.php?p=admin/actions/assetSources/getS3Buckets 500 (Internal Server Error)

Craft Version: Craft CMS 2.6.2950

This is the data from the logs.

2016/11/14 12:05:47 [error] [exception.Error] Error: Call to undefined function simplexml_load_string() in /var/www/stage.website.com/craft/app/lib/S3.php:2221
Stack trace:
#0 /var/www/stage.website.com/craft/app/lib/S3.php(420): S3Request->getResponse()
#1 /var/www/stage.website.com/craft/app/assetsourcetypes/S3AssetSourceType.php(438): S3::getBucket('website-craft', 'banners/IR_shar...')
#2 /var/www/stage.website.com/craft/app/assetsourcetypes/BaseAssetSourceType.php(237): Craft\S3AssetSourceType->getNameReplacementInFolder(Object(Craft\AssetFolderModel), 'IR_shareholder_...')
#3 /var/www/stage.website.com/craft/app/assetsourcetypes/BaseAssetSourceType.php(172): Craft\BaseAssetSourceType->insertFileByPath('/var/www/stage....', Object(Craft\AssetFolderModel), 'IR_shareholder_...')
#4 /var/www/stage.website.com/craft/app/services/AssetsService.php(709): Craft\BaseAssetSourceType->uploadFile(Object(Craft\AssetFolderModel))
#5 /var/www/stage.website.com/craft/app/controllers/AssetsController.php(52): Craft\AssetsService->uploadFile('1', NULL, 0, NULL)
#6 /var/www/stage.website.com/craft/app/framework/web/actions/CInlineAction.php(49): Craft\AssetsController->actionUploadFile()
#7 /var/www/stage.website.com/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#8 /var/www/stage.website.com/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#9 /var/www/stage.website.com/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#10 /var/www/stage.website.com/craft/app/framework/web/CWebApplication.php(282): CController->run('uploadFile')
#11 /var/www/stage.mediatek.com/craft/app/etc/web/WebApp.php(818): CWebApplication->runController('assets/uploadFi...')
#12 /var/www/stage.website.com/craft/app/etc/web/WebApp.php(288): Craft\WebApp->_processActionRequest()
#13 /var/www/stage.website.com/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#14 /var/www/stage.website.com/craft/app/index.php(62): CApplication->run()
#15 /var/www/stage.website.com/public/index.php(19): require_once('/var/www/stage....')
#16 {main}
REQUEST_URI=/index.php?p=admin/actions/assets/uploadFile
HTTP_REFERER=http://stage.website.com/admin/assets
---

--

2016-11-14 20:25:28

Level   error
Category    exception.Error
Message Error: Call to undefined function simplexml_load_string() in /var/www/stage.website.com/craft/app/lib/S3.php:2221

We haven't made any system changes, so I'm unsure what the next step is. Any help would be appreciated.

Apparently PHP hadn't installed the XML Parser appropriately. The amazing Craft team provided this link. Which solved my issue.

sudo apt-get install php-xml

https://stackoverflow.com/a/35604148/520520


Is there a way to to fire some code before user validation? Am wondering if there is a way to fire some code prior to user validation being actioned? I have code running in a plugin that fire onBeforeSave but validation is actioned before this. So was wondering if there is a function that can be run onBeforeValidation specifically for users.

Cheers

Currently Craft doesn't have any events related to validation.  You can see the full list of events available here.

You can always add it as a feature request, though. Be sure and add examples of your specific use-case.


Double escaping Regular Expressions in Craft's Twig replace filter? Just trying to use Craft's Twig replace filter to remove number prefixes from the beginning of User Groups names and I have had to double escape the character classes etc to get it to work. I tried this...

{{ group.name|replace('/^\d+\.\s/','') }}{% if not loop.last %}, {% endif %}

and it didn't work so for some reason I tried this...

{{ group.name|replace('/^\\d+\\.\\s/','') }}{% if not loop.last %}, {% endif %}

...and it worked. Is there a sensible explanation for this as Regular Expressions are like Voodoo?!

Twig auto-escapes the \ character so by the time it makes it to the Craft replace filter PHP code, the regex string looks like /^d+.s/.

By double escaping it, you're forcing the correct regex to make it through /^\d+\.\s/.


Check the site for missing file links / warn user before removing used files A client removed a lot of files in a moment of clarity, not realizing these were used in pages (thinking since they were used in those pages, they were no longer necessary in the assets system).

Before I completely reset the site to a few weeks ago (that was the time before they realized); is there a way to check the site for missing file links, including those in redactor?

Also is there any strategy for preventing clients from removing used assets? In WP for instance you can see which images are "attached". This is not waterproof, but still.

is there a way to check the site for missing file links, including those in redactor?

I can't think of a way to do this outside of writing a custom plugin/PHP script that loaded everywhere an Asset field might exist on an install, grabbed its contents and verified them against the file system.

Additionally, it would have to load any Rich Text field you have setup with Asset sources, use some regex to match any Assets reference tags it might contain and do a similar file system verification to check for the existence of the images.

  Also is there any strategy for preventing clients from removing used assets?

Take away their "Remove Files" permission from the Asset source under their user/user group permissions.


How to get the original entered password value on registration form error? I want to customize the user-registration-form with error/success-states.
If, for example, the user enters a wrong email, but correct username and password, it would be nice to set the value of the password input field back to the original entered password - like the username-field does.

{% if account is defined %}
<input id="password" name="password" type="password" value="{{account.password}}">
{% endif %}

In matter of UX, this does not really works good, because it's the hashed version of the password. The origin was much shorter. So the user could be a bit surprised...
Not setting the value, but set the state to success with an empty field is not much better.

Is it possible, to set the origin entered password as the value?
If, does this work on resend the form?
Any other ideas are welcome.

Tnx

You could always use the Craft request object to repopulate the fields, however I don't think it's common practice to repopulate password fields for security reasons.

Another thing that is considered bad practice is differentiating behaviour for partially correct credentials - the response from the web server should always be the same whether one part or multiple parts are missing from a correct authorization submission to prevent information disclosure to a potential attacker.


What would cause an custom element listing to just return everything? I'm creating a plugin with its own ElementType, i've been using the Events plugin by P&T for reference, so I thought everything was going fine.

Now when I go to my elements index, I seem to just get a listing for all elements, regardless of anything. What could cause this? I have my element type in my template like

{% set elementType = 'Custom_ElementType' %}

So if I change this to

{% set elementType = 'Entry' %}

I get a list of all entries with the correct sections and whatnot, which is what I expect, but when I change it to the former I get this:

I've obviously overlooked something but I can't figure it out, if anyone else has overcome something similar i'd be grateful for any pointers.

Update

Here is the code i'm using:

Plugin_FooElementType.php

<?php
namespace Craft;

class Plugin_FooElementType extends BaseElementType
{
  public function getName()
  {
    return Craft::t('Foo Element');
  }
  public function getSources($context = null)
  {
    $sources = array(
      '*' => array(
       'label' => Craft::t('All sources')
      )
    );
    return $sources;
  }

  public function populateElementModel($row)
  {
    return Plugin_FooModel::populateModel($row);
  }

  public function defineTableAttributes($source = null)
  {
    return array(
     'id' => Craft::t('ID'),
     'handle' => Craft::t('Handle'),
     'path' => Craft::t('Path'),
    );
  }
}

_index.html

{% extends "_layouts/elementindex" %}
{% set title = "Endpoints"|t %}

{% set elementType = 'Plugin_Foo' %}

{% set tabs = {
  events:    { label: "Events"|t, url: url('events') },
  requets: { label: "Requests"|t, url: url('plugin/foos') }
} %}

Plugin_FooModel.php

<?php
namespace Craft;

class Plugin_FooModel extends BaseElementModel
{
 protected $elementType = 'Plugin_Foo';

 protected function defineAttributes()
 {
    return array_merge(parent::defineAttributes(), array(
        'requestId' => AttributeType::Number,
        'handle' => AttributeType::Handle,
        'path' => AttributeType::String,
    ));
 }

 public function getCpEditUrl()
 {
    $relation = $this->getRelation();
    if ($relation)
    {
        return UrlHelper::getCpUrl('plugin/'.$relation->handle.'/'.$this->id);
    }
 }

 public function getRelation()
 {
    if ($this->relatedId)
    {
        return craft()->plugin->getRelationById($this->relatedId);
    }
 }
}

It is likely just a typo in your template. Can you ensure that if your element type class name is of the format Custom_PluginElementType that your template code is then in the following format:

{% set elementType = 'Custom_Plugin' %}

Or if your element type class name is of the format CustomElementType that your template code is then in the following format:

{% set elementType = 'Custom' %}


If YouTube in Redactor Then Wrap in Div So I have been using this CSS Tricks responsive video trick for years. The problem I'm having is that this new Craft site I built imported data over from EE into a single Redactor field.

Is there any way to run s conditional check that if there is a YouTube video embedded that would wrap a div around said content?

I'm probably asking too much but Craft has been amazing for the past few years I've using it. I fear the only way to do this would be to run an elaborate MYSQL commands to wrap that content in a div (or use JS to wrap each iframe) but I would love to be proven wrong!

Check out the Retcon plugin!

  Retcon is a small Craft CMS plugin offering a series of easy-to-use Twig filters for manipulating HTML content.

Specifically, it sounds like you need the wrap method:

{{ entry.body|retconWrap('iframe', '.videoWrapper') }}


How do I add a tab to my home page I have created a page for our website, but I do not know how to add it as a tab on the home page. How do I do that?

The front-end of a Craft site is 100% custom and leaves you with complete control over the HTML, CSS, JS and images that are generated, so there's really no way for us to give you step-by-step instructions on how to make specific changes to the front of your site

Generally speaking, you can modify the HTML and content of your site from the craft/templates folder on your server.  Any CSS/JavaScript/images on your site will likely live in your public HTML folder on your server.


Craft 2: Exception: CException: Alias "ext.alpha" is invalid Today I updated my craft to latest version Craft V 2.6.3015 by following this url.

I got it updated successfully and now my Craft version is 2.6.3015 which is latest of Craft 2.

After updating the Craft setup, I tested the site, and one of the page is giving an exception as mentioned below:

  Exception thrown in Make a Payment. Exception: CException: Alias "ext.alpha" is >invalid. Make sure it points to an existing PHP file and the file is readable. in C:\path\craft\app\framework\YiiBase.php:324

Please help me to get rid of the error.  I checked that the Craft is not having any extension named alpha.

Stack trace:

#0 C:\path\craft\app\framework\validators\CValidator.php(174): YiiBase::import('ext.alpha', true)
#1 C:\path\craft\app\framework\base\CModel.php(287): CValidator::createValidator('ext.alpha', Object(Craft\BarclaycardEpdq_PaymentModel), Array, Array)
>#2 C:\path\craft\app\framework\base\CModel.php(260): CModel->createValidators()
>#3 C:\path\craft\app\framework\base\CModel.php(158): CModel->getValidators()
>#4 C:\path\craft\app\models\BaseModel.php(501): CModel->validate(NULL, true)
>#5 C:\path\craft\plugins\barclaycardepdq\services\BarclaycardEpdq_ApiService.php(213): Craft\BaseModel->validate()
>#6 C:\path\craft\plugins\barclaycardepdq\services\BarclaycardEpdq_ApiService.php(64): Craft\BarclaycardEpdq_ApiService->callBarclaycard('Craft\\Barclayca...', Array, 'https://site...', 'payByAlias')
>#7 C:\path\craft\plugins\rhp\controllers\Rhp_PaymentsController.php(129): Craft\BarclaycardEpdq_ApiService->makePaymentByAlias(Array)
>#8 C:\path\craft\app\framework\web\actions\CInlineAction.php(49): Craft\Rhp_PaymentsController->actionMakeAPayment()
>#9 C:\path\craft\app\framework\web\CController.php(308): CInlineAction->runWithParams(Array)
>#10 C:\path\craft\app\framework\web\CController.php(286): CController->runAction(Object(CInlineAction))
>#11 C:\path\craft\app\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
>#12 C:\path\craft\app\framework\web\CWebApplication.php(282): CController->run('makeAPayment')
>#13 C:\path\craft\app\etc\web\WebApp.php(836): CWebApplication->runController('rhp/payments/ma...')
>#14 C:\path\craft\app\etc\web\WebApp.php(287): Craft\WebApp->_processActionRequest()
>#15 C:\path\craft\app\framework\base\CApplication.php(185): Craft\WebApp->processRequest()
>#16 C:\path\craft\app\index.php(73): CApplication->run()
>#17 C:\path\index.php(13): require_once('C:\\path\\...')
>#18 {main}

Please download below extension and put alpha.php file in your craft extension folder:
https://www.yiiframework.com/extension/alpha

Best of luck..!!


How to display in the CP only the current user's entries? Well the issue is simple, I have a multi-user backoffice, where they use the same section and entry type to create a new entry.  The problem is when the current user (not the admin) tries to add an entry in the entries field, it display the list of all other users entries, but this is not the case when viewing the section from the dashboard.  The current user (except for the admin who sees all) only sees his own entries. Can I somehow make the entry field display the current user's only list of entries to chose from?

Craft currently doesn't have the concept of "read" permissions for elements (entries, tags, categories, etc.)... technically any user that has access to the Control Panel has read access to every Craft element whether there is a nice UI way to access them or not.

Feel free to comment/vote on this feature request though, which would enable what you're looking for: https://github.com/craftcms/cms/issues/887


Can't clear caches locally I've been stumped on this one for awhile and tried everything. When I click Clear Caches in settings, it appears as if everything works fine but when I check the logs I see...

2015/11/04 17:10:16 [error] [application] Tried to read the folder contents of path/cms/craft/storage/runtime/cache/, but could not.
2015/11/04 17:10:16 [error] [application] Tried to read the folder contents of path/cms/craft/storage/runtime/assets/, but could not.
2015/11/04 17:10:16 [error] [application] Tried to read the folder contents of path/cms/craft/storage/runtime/temp/, but could not.

I ommited the actual path because it contained a clients name but I checked it's accuracy. I also noticed that it appears to be writing files to the cache folder. I also verified permissions on the folders and parent folder, all are set at 777 (for testing) was set at 744. I'm not sure what else to try or do. Thanks!

How are you setting permissions? Command prompt? (S)FTP? What user does php run under? Make sure there are no open_basedir restrictions as well.

You can find out the user that php runs under as well as a bunch of other details right inside Craft: http://server/admin/utils/phpinfo and look for user/group and open_basedir.

Make sure you're giving the storage directory recursive permission as well. I would delete everything under /storage manually...

cd /path/cms/craft/storage/ && rm -r * && chmod -R 777 .

... and then let Craft/php recreate the folders underneath.


Dropdown template URI breaks on language switch I have the following code in my header of a multilingual site. It produces the correct urls in english.

{% for entry in menuentries %}

    {% if entry.entryLink.first|length %}
        {% set navlink = entry.entryLink.first().uri %}
    {% elseif entry.customMenuUrl|length %}
        {% set navlink = entry.customMenuUrl %}
    {% endif %}

    {% if entry.level == 1 and entry.children|length %}

            {{ entry.title }}

                {% for child in entry.getDescendants() %}

                        {{ child.title }}

                {% endfor %}

    {% elseif entry.level == 1 and not entry.hasDescendants() %}

            {{ entry.title }}

    {% endif %}

However when I switch languages eg. to french the child.entryLink.first().uri returns null. Even if I just change the en to fr I get the same result. Bit confused.

UPDATE:
Mats you were right - I didnt have any data in the french menus or i had random custom url data. Once corrected the entry model came back whole. Phew


How can I get entries where a date is within a dynamic date range? {% set params = {
      section : 'events',
      order : 'eventStartDate asc',
      eventStartDate : '>=' ~ now,
      limit : row.itemsPerPage.value
} %}

I am trying to pull a set of event entries for a basic event calendar and I'm trying to figure out the syntax for the eventStartDate parameter to have it pull starting with the current date and ending with a value of the current date + 1 month, 3 months, or 6 months depending on the value set in another field named eventDateRange. I need help with how to write that as a command like the one listed above.

Ok, so in the end you’d want your “startDate” custom field parameter to be a string in this format:

'and, >= 2017-08-04T05:00:00+08:00, < 2017-08-11T04:59:59+08:00'

I’m outputting a format for the dates that includes the time and timezone, so that we are able to define when exactly events are being refreshed. To do that I’m using the date filter (otherwise Twig outputs dates in Y-m-d format).

Here’s how you compose the final string including the value from the Global Set, that I am simply concatenating to a string that I pass into the date_modify filter.

{% set var = myGlobalSet.myNumbersField %}

{% set rangeStart = now|date_modify('5:00')|date('c') %}
{% set rangeEnd = now|date_modify('5:00 +' ~ var ~ ' weeks')|date('c') %}

{% set startDateParam = 'and, >=' ~ rangeStart ~ ', <' ~ rangeEnd %}


Define a dynamic 'basePath' environmental variable without the locale So in my general config file I've defined an environmental variable called basePath (as per the Environment-Specific Variables documentation). I'm using the getcwd() function to get the working directory.

return array(
    '*' => array(
        'environmentVariables' => array(
            'basePath' => getcwd(),
        )
    ),
);

I'm using this for a few reasons:

I work in an environment where many people can be working on the same project at the same time. So their local basePath is always different.
My different siteUrls for my setup use trailing locales in the url: 'siteUrl' => array( 'en' => 'http://www.website.com/', 'fi' => 'http://www.website.com/fi/' ). So when it comes to targeting environment-specific locales, things get messy.
$_SERVER['DOCUMENT_ROOT'] is ok locally, but fails on a live server.

So my problem is when using getcwd(), the locale is included in path. Is there a way to trim this out dynamically?

Or is there a way to strip out the current locale from this path on-the-fly? rtrim(getcwd(),"fi")

Maybe there is a more reliable way to get the working directory?

Check out craft-multi-environment; even if you don't use it, you might crib some of the ideas from it.

For instance, how the basePath is determined.


Uploading Assets w/ Immediate Save? Heyo - I have an entry form in which you select/upload assets (photos). The asset has a caption/copyright (custom)field attached to it, so ideally I'd tell them…

Click "Add Asset" and upload/select your photos
When the pills show up in the entry form, double-click them to add captions/copyright

But, I find that if you do the above, you won't see the caption/copyright field (just title and file name) unless you save the entry between steps one and two.

I can see why this could be … the images are probably in a holding position until you save the entry(?). But just wondering if someone can confirm I'm not mucking something up, or maybe has a workaround?

It seems weird to have a note on the entry form that says "Reminder: 'Save and Continue Editing' to add captions to the images.

Same issue also comes up when you need to upload assets in a field, then in a subsequent field choose one of the assets (say, an entry form where you upload a group of images, then want to select one of the images to be the group's thumbnail).

Any ideas? Tks in advance.

So, thanks to @carlcs for verifying it was my setup…

turns out I had set the asset's Default Upload Location to include the slug (i.e. /photography/{slug}) and restricted uploads to that folder. This way images would end up in a folder whose name matched the entry slug, making it easier to clean out unused assets from time-to-time.

But that approach was the source of the problem. Once I removed {slug} from the default upload location it all worked as expected, the caption field appeared immediately after adding the asset.

Of course, in retrospect this makes total sense — there's no {slug} until you save the entry.


Using Element API, how do I get the next entry? return [
    'endpoints' => [

        'journal/<entryId:\d+>.json' => function($entryId) {
            return [
                'elementType' => 'Entry',
                'criteria' => ['id' => $entryId, 'section'=>'journal'],
                'first' => true,
                'transformer' => function(EntryModel $entry) {
                    $nextEntry = $entry->getNextSibling();
                    // also tried getNext()

                    $upNext = [];
                    $upNext["title"] = $nextEntry->title;
                    // errs out here ...
                }
            ];
        }
    ]
];

I feel like I'm missing something obvious, but how do I get the next sibling of an entry using Element API?  Would it be easier/better to pass both the current entry ID and the next entry ID (which I have available) into the criteria to make it easier to grab?

Thanks!

Depends on what you mean by “next”.

If the entry is within a Structure section and you want whatever entry is positioned after it, you’d use getNextSibling().

$nextSibling = $entry->getNextSibling();

Otherwise you want getNext(). But you need to keep in mind that which entry is next can vary in infinite ways, so you really need to supply that $criteria argument here.

The point of the $criteria argument is to define a collection of entries in a specific order, in which $entry is one of them, and Craft uses that to determine which entries come immediately before and after it.

Your example code shows that you are returning Journal entries, so I’ll assume that you want $nextEntry to be the journal entry that was written after $entry – so the entries should be sorted in chronological order. If that’s the case, here’s the code you should use:

$nextEntry = $entry->getNext([
    'section' => 'journal',
    'order' => 'postDate asc'
]);

As far as what you can pass into that argument, all of the craft.entries parameters are fair game here, with the exact same value syntax. Just keep in mind that it’s PHP code and not Twig, so instead of something like:

.postDate('<= 2013-06-04')

it would be:

'postDate' => '<= 2013-06-04',

You can also pass in an actual ElementCriteriaModel object, with its values set ahead of time:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'journal';
$criteria->postDate = '<= 2013-06-04';
$criteria->order = 'postDate asc';

$nextEntry = $entry->getNext($criteria);


Is there a way to prevent Craft from backing up the database before updating? When Craft tries to apply an update, it tries to back up the database. Although that's great in general, backing up a large database using PHP requires a lot of memory and resources that might not be available in the hosting environment or the client does not have enough access to make any related adjustments.

Is there a setting of some kind that would prevent Craft CMS from backing up the database when updating? I already use a command line script to backup the database before applying an update.

Yes you can use the backupDbOnUpdate config setting:

https://craftcms.com/docs/config-settings#backupDbOnUpdate


Trouble Installing Craft 2.5 on Windows 10 Using Wamp 2.5 I am trying to install Craft CMS 2.5 on a Windows 10 machine using WAMP 2.5.

I just downloaded both Craft and WAMP this morning — so both are fresh installs.

I believe I have done everything properly, but when I navigate to localhost/sitename/public I get the following message:

  Service Unavailable

  Our site is temporarily unavailable. Please try again later.

If I try navigating to localhost/sitename/public/admin OR localhost/sitename/admin I get the following message:

  Not Found

  The requested URL /sitename/admin was not found on this server.

  Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 80

These are the steps I took when setting up:

Created a folder in wamp/www called sitename
Copied the craft and public folders into the sitename folder
Changed htaccess to .htaccess (using windows command line)
Created database in phpmyadmin
Updated db.php in craft/config folder

(the only change I had to make was to add the database name — I left server as localhost, user as root and password blank.  I did change the tablePrefix to five different letters — i.e., no numbers or special characters)

I did NOT change the permissions on any of the app, config or storage folders for the simple reason that I do not know how to do that on Windows.

Unless the permissions are the problem, then I do not know why I am having this problem.

Any ideas?

Alec Ritson's comment solved the problem.  His advice was to try

localhost/sitename/public/index.php/admin

In other words, I had to add index.php to the URL (after public but before admin) and then everything worked fine.


How can I run the Control Panel from a separate domain? Is it possible to separate the public site and the Control Panel on separate domains (i.e. www.domain.com and admin.domain.com)?

With baseCpUrl you're able to force the admin URL to admin.domain.com, but is it possible to also remove the redirect from www.domain.com/admin and completely remove all possible ways to access/redirect to the CP from www.domain.com?

(I guess setting cpTrigger to a random string would be one way, but then you also end up with the admin address similar to admin.domain.com/hjkads78ads5ads785ads68ads67)

You can use the baseCpUrl config setting to tell Craft to always generate CP URLs pointing to http://admin.domain.com, and you can create a .htaccess redirect on http://domain.com pointing all requests to /admin* to http://admin.domain.com/admin/*, but it is not currently possible to get rid of the CP Trigger segment at this time. Craft relies on that to determine if the current request is a CP request.


Craft and lat/long search I've used expression engine but not Craft. I am looking for a CMS more flexible than WordPress. I need to have admins enter location or addresses of meetings and then allow site users search for locations close to them or close to a specific address. Part of the use case is that meeting locations would be posted if the meeting is open or just a contact if the meeting is closed.

Would Craft be a good CMS for this? What about the geo stuff?

Yes, Craft would be a great solution for that!

For the proximity search feature, check out the Smart Map plugin. (Disclaimer: I'm the author.) It allows you to input addresses for each location, then your users can conduct a search to find the closest locations.


How to set error message in element action? I call a service function inside the performAction method of custom element-action and I'd like to show an error message to user if the service function returned false.

I was able to set success message by using:

$this->setMessage($this->getParams()->successMessage);

But I don't know how to set an error message i.e. with red background.

I know this is a late reply. I hope it will help others.

You need to return false; so that the background color is red.

Example:

     if (count($criteria->ids()) > 1)
     {
         $this->setMessage($this->getParams()->warningMessage);

         return false;
     }


Available Shipping Methods Returns Null I have created a shipping method in the CP but when I output cart.availableShippingMethods a null value is returned. I've checked my database and the shipping method is there.

Is there something I'm missing?

Does your shipping method have any conditions set? Like a country or region? I think getAvailableShippingMethods() takes into account your shipping address (if any) and only shows shipping methods that apply to the current shipping details.

Second thing to check: does your shipping method have at least one shipping rule? Commerce needs a shipping rule to be checked against your order.


Pass a variable array to a macro I try to pass a variable from to a macro:

{% set syName = {
   x: { name: "Schön"},
   y: { name: "Leicht bewölkt"},
   z: { name: "Stark Bewölkt"},
    }
%}

{% macro prognose(symbol, syName) %}
   <img src="test/{{ symbol }}.png">
   {% for alt in syName %}
      {{ alt.name }}
   {% endfor %}
{% endmacro %}

{{ _self.prognose(  '1' , syName ) }}

So far so good. But this passes all the content from the variable into the macro. I want to trigger x, y, z individually.

So I tried to write it like this: {{ _self.prognose(  '1' , syName.x ) }}

This gives the error:

  Impossible to access an attribute ("name") on a string variable
  ("Schön")

How do I have to write this?

The first example makes sense because you are passing a multidimensional  array (syName), looping through that array, assigns each array within to alt allowing you to then access the values through dot notation ({{ alt.name }}), because alt is an array.

In your second example you are passing through just one array, so when you loop through it, the value in name is assigned to alt as a string. (the value in the array) so you can echo it out just by doing {{ alt }}

So your code could look like:

{% macro prognose(symbol, syName) %}

   {% for name in syName %}
      {{ name }}
   {% endfor %}
{% endmacro %}

{{ _self.prognose(  '1' , syName.x ) }}

This will output Schön

To make things even easier for yourself, if you are passing just one array i.e syName.x You don't even need the loop as you can just access the value through dot notation:

{% set syName = {
   x: { name: "Schön"},
   y: { name: "Leicht bewölkt"},
   z: { name: "Stark Bewölkt"},
}%}

{% macro prognose(symbol, syName) %}

    {{ syName.name }}
{% endmacro %}

{{ _self.prognose('1', syName.x) }}

This will output Schön


Add custom element criteria attribute without a field type? Is a custom field type and making use of modifyElementsQuery the only way to add my own craft.entries element criteria model attribute to modify the elements query?

What if I do not want to add a new field to each entry type I want to use my  attribute with? The field would be a hidden pseudo field anyways, as I'm only working with other fields' data.

My current solution is passing the element criteria model with all other params set to craft()->elements->buildElementsQuery() using a template variable. It works, yes, but I would really like to avoid this (pagination not possible and some other disadvantages).

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( //...
    }
});


loop through responsive images in matrix with imager plugin I have a content block in a matrix field where I'm trying to output a loop of three sub images.

I can get it to work using the following code:

{% case "secondaryImage" %}

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

    {% for image in block.image %}

    {% endfor %}

    {% endif %}

However, I want to output responsive sizes and like to use the Imager-Craft plugin with the Craft-FocusPoint plugin for this on my other images which works really well. But, I'm running into an issue whereby it's only outputting the first image three times with the following code:

{% case "secondaryImage" %}

    {% set image = block.image.first() %}
    {% set transformedImages = craft.imager.transformImage(image,
      [
          { width: 1440, ratio: 6/4 },
          { width: 1024, ratio: 6/4 },
          { width: 750, ratio: 4/3, jpegQuality: 60 },
      ],
      {
          format: 'jpg',
          allowUpscale: false,
          mode: 'crop',
          jpegQuality: 100,
          position: image.focusPctX ~ '% ' ~ image.focusPctY ~ '%',
          interlace: true
      }
    ) %}
    {% if image | length %}

    {% for image in block.image %}

    {% endfor %}

    {% endif %}

I think the issue is on the line src="{{ transformedImages[1].url }}" but I can't find what to change it to, to output the different images. The first thing I tried was removing the [1], but that doesn't work and gives an error of Key "url" for array with keys "0, 1, 2" does not exist.

Hopefully someone can help, otherwise I'll have to take it out of the matrix field and create a field for each image. But would prefer to keep it in the matrix if possible?

You’re currently passing in the image model you queried for using first() into the craft.imager.transformImage function, but you actually need to pass in the models that you get when looping through all images added to your block’s field.

There’s no reason to do the first() at all, and it would add additional queries.

{% if block.image|lenght %}
    {% for image in block.image %}
        {% set transformedImages = craft.imager.transformImage(image, transforms, options) %}

        <img src="{{ transformedImages[1].url }}"
            sizes="33vw"
            srcset="{{ craft.imager.srcset(transformedImages) }}">
    {% endfor %}
{% endif %}


Best way to find sectionId by slug What would be the best way of finding a sectionId by its slug within my plugin?

This should work:

$section = craft()->sections->getSectionByHandle('sectionHandle');
$sectionId = section->id;


Set User Password Manually Can I manually set a user's password?

I know I can change it but it is asking for the current password which is null at the moment.

The current password it is asking for when you change it is not the password of the user who is having their pasword changed, but the password of the admin (you) who is doing the changing.


FeedMe Inner field mapping According to the CraftCMS FeedMe 4 docs we should be able to import inner element field data when importing content via FeedMe.

I have a section we'll call Parent, which has two fields that need importing; ImportId (text field) and ChildEntry (Entry relationship). Child Entry has two fields, Title and Body.

I am able to map Parent->ImportId and ChildEntry->Title I am unable to map to ChildEntry->Body.

My JSON looks like this:

{
  "data": [
    {
      "title": "secrets",
      "import_id": "UUID-9-3/4",
      "child_title": "Harry Potter",
      "child_message": "Is in a dream",
    },
    ...
  ]
}

Is this expected functionality, or am I reading the documentation correctly?

You should nest the child's details like so:

{
    "data": [
        {
            "title": "secrets",
            "import_id": "UUID-9-3/4",
            "child": {
                "child_title": "Harry Potter",
                "child_message": "Is in a dream"
            }
        }
    ]
}

Then make sure you you choose data as your Primary Element when mapping your feed and check Create entries if they do not exist for the relational field.


Caching ElementCriteria Lookups In Craft CMS Plugins Two recent sites I’ve built have plugins built to handle filtering through projects based on some categories and related entries.

For example the lookups look similar to this:

# Get element criterea for searching projects
$projectCriterea = craft()->elements->getCriteria(ElementType::Entry);
$projectCriterea->section = 'projects';
$projectCriterea->limit = null;
$projectCriterea->relatedTo = $relatedElements; # This is an array of categories and related entries.
$projects = $projectCriterea->find();

All these lookups aren’t particularly fast, and there aren’t that many different variants. Is there a way I can add some caching into these lookups?

I had a bit of a look into the CacheService but I'm not sure how to apply that to this.

Thanks

I have figured it out, but am not sure if this is the best way so could still use some advice.

# Get a unique hash of your search criteria (still figuring this out).
$hash = md5(json_encode($projectCriterea));

# Look up the cache
$cache = craft()->cache->get($hash);

# Did we find this search criterea in the cache already? If so, return it.
if ($cache) {
    return $cache;
}

# No cache? Do searchy business
# ...
$projects = $projectCriterea->find();
# ...

# Save to the cache
if ($cache === false) {
    craft()->cache->set($hash, $projects, 604800); # Cache for 1 week
}

return $projects;


Enable single line item mode on Commerce Pro Is there a config option or something that would enable the 1 line item limit in cart. That means once customer adds second line item to cart first one would be removed so that only one would be left. I believe that's how Commerce Lite works. I need similar functionality on Pro licence.

There is no existing config option for this behaviour with Commerce Pro.
You'd need to write a relatively simple custom module to do this.
You'd probably listen to something like this event:
https://craftcms.com/docs/commerce/3.x/events.html#beforeaddlineitemtoorder
...and remove anything else in the cart before the new item is added.
or, thinking about it, you might want to first make sure the new item has been successfully added, and only then remove the other items from the cart, in which case:
https://craftcms.com/docs/commerce/3.x/events.html#afteraddlineitemtoorder


Add field to /settings/sites/new (multi-site) I would like to add some fields to the site creation on the control panel settings. I know you can add globals for each site, but I think it would be a better process if I could add additional fields.

For example, I'd like to add a select for whether a site (location) is a franchise or corporate.

Is this possible?

If I'm following you correctly, there currently isn't a way to do this.

Sites are a concept that doesn't support things like fields and field layouts like other elements (Entries, Categories, Matrix Blocks, Tags, etc.).


How do I get tags to only display on posts that have that tag? I’m trying to add tags to my blog posts.

I’ve created a tags group with the handle ‘default’.

In Setting/Fields I’ve got a field called bodyElements which is setup as a matrix, and within bodyElements I’ve added to the Configuration a block type called Tags with a handle of ‘tags’, and then within that there’s a field called Tags with a handle of ‘blogTags’ and this is set as the Field Type of “Tags” and the Source is set as “Tags”.

Now when I go to a blog post, I can type in my content and click the button to add a Tag. I can then type in a tag and it attaches to that particular entry.

The issue I’m having is that when I view the blog posts on the front end, the tags are showing up on every single post, even though they don’t have those tags attached to them.

On https://craftcms.com/support/active-tags it says to insert the following code to display only the tags that are in use

{% set entries = craft.entries.section('news').limit(null) %}

    {% for tag in craft.tags.relatedTo(entries) %}

{{ tag.title }}

    {% endfor %}

but that doesn’t display the tags at all.

My blog section has a handle of ‘blog’, so in the above code I tried replacing ‘news’ with ‘blog’ and still no tags appear.

The only way I can get tags to appear on my posts is by using the following code:

{% for tag in craft.tags.group(‘default’) %}

{{ tag.title }}

{% endfor %}

but the above code caused the tags to appear on every single blog post, even if they’re not tagged with anything.

How do I get the tags to only appear on the posts the tags are attached to?

Thanks.

The code you're using at the moment is trying to output the tags that are in use on any/all entries:

{% set entries = craft.entries.section('news').limit(null) %}

If I understand you correctly, you want to output the tags only for the current entry, right?

This is explained with very useful examples in the documentation.

Solution

Assuming you already have the entry variable set, you could do the following:

    {% for tag in craft.tags.relatedTo(entry) %}

{{ tag.title }}

    {% endfor %}

Another example adapted from the docs:

{% set tags = entry.tagsFieldHandle %}

{% if tags | length %}

        {% for tag in tags %}

{{ tag.title }}

        {% endfor %}

{% endif %}

You first set the variable tags to the tags related to your entry. Then, you check if there are tags related to the entry. If there are, you iterate over them.


Is it possible to use Update Asset Indexes on a target subfolder or subfolders? I have a folder with 10GB of files that I need to sync with Craft. It has 12 subfolders, one for each year:

/1999
  /01
  /02
  /03
  /...

It's possible to run Update Asset Indexes on the top-level folder but this process takes several hours and can't be interrupted. If things get interrupted, for whatever reason, some of the sub-folders are successfully imported but the other subfolders aren't, and there is no simple way to pick things up where they left off without restarting the full process. Ouch.

Is it possible to sync a specific asset subfolder, or list of subfolders? How would I approach this programmatically?

It seems I may want to call the AssetIndexTool::performAction method but only pass in the subfolder IDs or something like that. I haven't interfaced with the Tool classes at all. Is this a reasonable direction to consider or am I not considering another potential direction?

There is no good solution in Craft 2.x, but you probably can put together a plugin or a console app that does what you want it to do. Here's all the background info you, hopefully, need.

The whole indexing process is controlled by javascript as well but let's just pretend you've instantiated the AssetIndexTool class and are operating on that via performAction()

Craft Asset indexer operates strictly on the data in craft_assetindexdata table. When you start an indexing task, the very first thing it does is query the Asset Sources for all the actual files that are there, stores a list of them in the said table and from that point on uses that table to reference what files have been indexed and which not. As it does it, Craft also creates all the folders already (because, apparently, a long time ago it seemed like a good idea to me).

After that, the tool returns an array for each of the steps it needs to take, where one step is generated per file and also an additional "overview" step at the end. Each array entry basically contains parameters that you should throw back at the Index Tool.

What you're interested in each of those "step" arrays (if you want to understand how the whole process works) is sessionId variable there to track the indexing session in the indexing table, the sourceId variable so you know which source you're operating on and the offset variable that tells the Index Tool which file in the indexing table to look up and actually index.

You should definitely also follow through with the last overview step. Never mind that it presents the user with a HTML dialog for all the files that are in the DB but are not present in the source, but, more importantly, it cleans up the asset indexing table and removes the obsolete data in there.

The great news is that it will be significantly less convoluted and way more accessible programmatically in Craft 3.


How would I show a message and define where the user is redirected after changing their email through a front end form? I have a profile form where a user can update their email.

Upon doing so I would like to:

Show the user a message saying they must check their email to verify the new email address.
After they click the "Verify Email" address in their inbox, redirect them to a url preferably with a Flash Message letting them know they'e successfully updated their email.

Possible?

Based on Brad's response I created the following controller in a plugin:

<?php
namespace Craft;

class Myplugin_SaveUserController extends BaseController
{
    protected $allowAnonymous = true;
    /**
     * Handle the save user form request.
     */
    public function actionSaveUser()
    {
        $this->requirePostRequest();
        $email  = craft()->request->getPost('email');
        $userId = craft()->request->getPost('userId');
        $user   = craft()->users->getUserById($userId);

        if ($email !== $user->email)
        {
            craft()->userSession->setFlash('changedEmail', 'changed email');
        }
        $this->forward('users/saveUser', false);
    }
}

I then check for it in my template:

{% if craft.session.getFlash('changedEmail') == 'changed email' %}

This seems to do the job.

For anyone who may be using this in the future, it's worth noting that I also had to change the "action" hidden input in my form:

<input type="hidden" name="action" value="myplugin/saveUser/saveUser">


Get product type on event handler I'm working on a plugin to calculate price based on width and height but struggling to get the product type of each product into the 'onPopulateLineItem' event.

So far, I've looked into the purchasables and lineItems arrays to get the information, and although I can see the typeId under the $event array, I just can't get this value.

Can anyone point me in the right direction for this please?

** UPDATE **

I've managed to get something with the below, but this feels really hacky. Is there a better way I should be doing this?

$lineItem = $event->params['lineItem'];
echo $lineItem['snapshot']['product']['typeId'];

Very minor change to Brad's approach, and with a bit more checking to avoid issues like the product being deleted while the code is looking in that direction, etc. (based on Luke's advice).

foreach ($cart->lineItems as $item)
{
    // check the purchasable has not been deleted in the meantime
    if ($item->purchasableId)
    {
        // get the variant and the actual product so we can get to custom fields
        $variant = $item->purchasable;

        // If there is no product associated with this purchasable, it's a digital virtual product so just skip it
        if (!isset($variant->product))
        {
            continue;
        }

        // get the actual product element from the purchasable
        $product = $variant->product;

        // How to get a regular field on the product
        $title = $product->title;

        // How to get the product type - use handle rather than name, as this is less likely to change
        $productType = $product->type->handle;

        ...etc
    }
}


Does Craft Commerce support multi-currency? After looking at the Features page for Craft Commerce, I didn't see anything regarding multi-currency support. Is this something that's available for certain payment processors?

Not at this time (version 1.1), but Pixel & Tonic has indicated in Craft Slack that it is on the roadmap.


Output descendants of current structure I hope I worded the title correctly. I'm trying to output whatever structure's page I'm on - I want the descendants of whatever page that is. I'm currently using this, which at first appeared to work, but then my css styling doesn't get applied to any of the other entries.  See below:

  {% set messages = entry.getChildren() %}
     {% if messages | length %}

        {% for entry in messages %}
          {% for image in entry.seriesArtwork %}

          {% endfor %}

{{ entry.title }}

 {{ entry.postDate|date('M j, Y')}} • {{ entry.speaker }}

      {% endfor %}
{% endif %}

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


Add custom attribute to standard element from plugin Developing plugin for Craft 3, I want to add extra property to Assets (data being pulled from other table)

I am able to pull in the data by extending element query:

Event::on(
            ElementQuery::class,
            ElementQuery::EVENT_AFTER_PREPARE,
            function(CancelableEvent $e) {
                if ($e->sender->elementType == 'craft\\elements\\Asset')
                {
                    $e->sender->query->addSelect('linkstats.downloads');

                    $subQuery = (new Query())
                        ->select('assetId, SUM(downloads) AS downloads')
                        ->from('{{%my_plugin_table}}')
                        ->groupBy('assetId');

                    $e->sender->query->leftJoin(
                        ['linkstats' => $subQuery], 'assets.id = linkstats.assetId'
                    );
                }
            }
        );

However when trying to display the asset I get error:

  Setting unknown property: craft\elements\Asset::downloads

Question, how do I register this new property/attribute for Assets? I cannot find any event to do that, is it possible at all?

Another approach is to use the following event to attach a behavior

Event::on(Asset::class, Asset::EVENT_DEFINE_BEHAVIORS,
function(DefineBehaviorsEvent $event) {
    $event->behaviors[] = MyBehavior::class;
});

The behavior could look like

class MyBehavior extends Behavior {
    public $downloads;
}

This way you won't receive an exception and can access your property via

$asset = Assets::find()->all();
$asset->downloads;

You can as well manipulate the value of downloads in the Behaviors init function in order to return the file or something like this


Customizing CP Entries section template First, which template does the actionGetElements use to generate a response?

Second, how can I customize the template for a single entry section?

First, there isn't a single specific template that ElementIndexController's actionGetElements uses to return data.

It implements IElementType's getIndexHtml method which BaseElementType provides a default implementation of, but any ElementType (Entry, User, Asset, custom plugin ElementType, etc.) is free to implement that method with their own logic.

Second, it sounds like you want to hack core files in the craft/app folder, which I definitely wouldn't recommend.

You might be able to make the modifications you're looking for with something like the CP CSS and CP JS plugins.


Restrict user editing permissions within a user's group? I'm setting up a site for a charity with a national branch and several sub-chapters. I'd like users of a particular chapter to be able to add/modify users, but only within their chapter's user group. It seems like with the current structure of admin permissions, I'm only able to say whether or not a user can add/edit users, and not restrict that to a particular group.

Is this possible and I'm just not seeing a setting somewhere? If not, does anyone know of a plugin that provides this functionality?

Thanks.

This is not currently possible through the CP (as far as I know anyway). You would need to write a plugin; and I haven't seen any plugins on straightupcraft that address this particular need, but have a look. You could also contact someone through the professionals section that might be able to help.

If you were to write your own plugin you might have a look at the documentation on hooks and events. In particular the onSaveUser event, where you could potentially force a user into a particular group, based on specific conditions that you establish.

In your plugIns init function you could create a listener for the onSaveUser event.

public function init()
{
    parent::init();
    craft()->on('users.saveUser', function(Event $event)
    {
        $user = $event->params['user'];
        if ($allMyConditionsAreMet)
        {
            if($allMyGroupConditionsAreMet)
            {
                $groupId = 1;
            }
            else
            {
                $groupId = 2;
            }
            craft()->userGroups->assignUserToGroups($user->id, $groupId);
        };
    });
}


Uploaded .gif only loops once instead of infinitely Having a problem where uploading an infinitely looping gif only loops once.

I've tested it with and without image transforms and get the same issue.
I know there there was an issue previously stated here
Specify number of loops for animated GIF (ImageMagick)? and that was fixed in a recent release. Any thoughts on what the issue could be?

Craft CMS 2.6.2931 (multilingual)

ImageMagick 6.7.7-10 (dev)

ImageMagick 6.7.8-9 (staging)

We have the same problem here. I downgraded to version 2.6.2922 for testing purposes and the gif loops infinitely again. I suspect the bugfix in 2.6.2923
"Fixed a bug where animated GIF loop limits were not being respected." to be responsible. Unfortunately a downgrade on production is currently not possible for us, since the Schema version changed...


Install license key for plugin can someone explain how I can install the license of a plugin in my installation?

concretelly I have the craftql license key in https://id.craftcms.com/licenses/plugins and I want to setup that into my installation.

If you click link your CraftID to your install, all of your plugin licenses should be automatically configured;  more information at the following:

https://docs.craftcms.com/v3/plugins.html#managing-plugin-licenses


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

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

and

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

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

{% set offset = offset ?? 0 %}

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

{% for entry in entries %}

    ----Entry Stuff----

{% endfor %}

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

Load More

  </button>
{% endif %}

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

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

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

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

</IfModule>

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

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

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

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

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

Sprig will use whatever your site's base URL is set to, to construct the action URL. Ensure in Settings → Sites that the base URL is either set to an absolute path starting with https://, or if an alias or environment variable, that it is defined as an absolute path starting with https://.
Also be sure to either force the www subdomain or force a naked domain. in your example above I see one with and one without www.


Using categories to filter assets I am new to Craft and have a decent handle on the basics, but I am struggling a little getting this to work.  Here is what I would like to do:

I have a banner with bxslider which will be looping through images in a matrix field.  This is for a church site and this template will be used for all their ministries.  Each ministry will have it's own photos, but right now assets is returning images for all entries.

Here is my code:

{% elseif craft.request.segment(2) == "crosstrainers" %}

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

        {% for block in entry.slider %}

                    {% for image in block.sliderImage.limit(1) %}

                    {% endfor %}

{{ block.sliderHeader}}

{{ block.sliderText}}

{{ block.sliderButtonText}}

        {% endfor %}

        {% endfor %}

Any suggestions on how to limit the asset results to each ministry.

From your example, it is a bit hard to tell how your site is organized, but it sounds like you want to set up content specific to each ministry (which is stored in the top-level of your "site_content" structure?), which will be shared across all of that ministry's sub-pages. Regardless, you will essentially want to retrieve the entry where the slider data is stored, and loop through the matrix data from there.

{% if craft.request.segment(2) == "crosstrainers" %}
    {% set entry = craft.entries.section('site_content').slug('crosstrainers') %}
    {% for block in entry.slider %}
        {# prevent error if no slider image is defined #}
        {% if block.sliderImage|length %}
            {% set image = block.sliderImage.first() %}
            <img class="slider-image" src="{{ image.getUrl }}" alt="{{ entry.title }}" />
            ...
        {% endif %}
    {% endfor %}
{% endif %}


Adding tel: links using Redactor Is there a way to add tel: links in the Redactor WYSIWYG?
I tried Link > Insert link to enter tel:+43123456789 as URL,
but all I got was <a>+43123456789</a>. The href is missing.

Under your Rich Text field settings, if you uncheck the "Purify HTML?" option, the tel: reference will stay in tact.


How do I output a matrix block type only once when looping through entries? My matrix field has a block type called photo. When looping through entries I only want to output the first instance of this block type (although it will have been used multiple times), i.e. the first photo.

The code below loops through the entries, but for each entry it's outputting every photo for the entry - not just the first.

What do I need to change to get just the first photo of each entry output.

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

    {% for block in entry.tactics %}

        {% if block.type == "photo" %}

                {% set photo = block.photo.first() %}

                {{ entry.title }}

        {% endif %}

    {% endfor %}

{% endfor %}

You can output the first matrix block of it's type using .type(blockHandle):

{% for entry in craft.entries.section('mySection') %}
    {% set photoBlock = entry.tactics.type('photo').first %}

    {% if photoBlock %}

            {% set photo = photoBlock.photo.first() %}

            {% if photo %}

            {% endif %}

            {{ entry.title }}

    {% endif %}
{% endfor %}


Craft throwing an SQL error on Save when Matrix field has a lightswitch Since updating to 2.2.2587, anytime I edit an entry by adding a block on certain Matrix fields, it throws the following error:

Internal Server Error

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'field_text_markdown' cannot be null

It seems to throw the error if any of the blocks in that field contain a lightswitch field. It doesn't matter if the block with the lightswitch is actually added to the entry or not. In this case, my Matrix contains two switches, which are off by default.

Throws the error whether the blocks with the switches are present or not… and doesn't seem to matter if I add the blocks with the switches and turn them on or off.

Cheers!