How to export 1 Entries type ("news") from Craft to Wordpress

Most people are going the other way. Is there a particular reason you want to downgrade? ;-)

Being serious though...

If you need the entries in a CSV format then yes you could use an export plugin such as Sprout or Export. Or you could make a template that outputs your content in the format required.

If you choose a plugin, then you'd need to read the documentation to find out how to set that up.

As for importing into Wordpress. That's dependent on your Wordpress setup and what you are using to do the import and is probably outside the scope of this particular Stack Exchange site.

But bear in mind that Craft is incredibly flexible so if the reason you're wanting to switch is related to particular functionality it could almost certainly be achieved with Craft.


I'd simplify the entry like so

   {% set entry = craft.entries.id(5) %}
   {{ entry.title }}


Craft is piggybacking off of Yii's caching functionality for 99% of this and their cache classes don't expose any type of TTL functionality.  My guess is that because of all the different caching providers they support (memcache, xCache, WinCache, ApcCache, etc.), it looks like Redis is the only one that has this sort of functionality.

There isn't a clean way for us to add this to Craft itself, so I think a proper fix would be to add it to Yii, but considering Yii 1 is in bug fix more and not getting any more enhancements and Yii 2 has dropped support for Redis, that seems unlikely.


How can I let JS UI building to field type plugin?

You can quite easily set up asset and text fields to be fed into a owl-carousel template. Or you could create a matrix in which one of the blocks would automatically produce owl-carousel html and again pass asset and text fields in the matrix block to produce the images and captions.

If you want further assistances try to be a little more specific in your question.


Matrix field input error from within the control panel

There's about a 99% chance you're bumping into your php.ini file's max_input_vars value and/or its post_max_size. If you bump those to higher values, it should start working as expected.

Note that you may have to restart your web server for the settings to take affect.


How can I get field's value of entry in other site locale in my element-api endpoint?

Okay I found a way to do it if it can help someone:

$description_fr = ($entry->summary) ? $entry->summary : ($entry->body) ? $entry->body : '';
$entry_en = Entry::find()->id($entry->id)->siteId(2)->one();
$description_en = ($entry_en['summary']) ? $entry_en['summary'] : ($entry_en['body']) ? $entry_en['body'] : '';
$entry_de = Entry::find()->id($entry->id)->siteId(3)->one();
$description_de = ($entry_de['summary']) ? $entry_de['summary'] : ($entry_de['body']) ? $entry_de['body'] : '';


Why is using the cache tag more expensive than outputting static text?

Since the {% cache %} tag solely stores its information in the database, it has a guaranteed minimum of one database call to make to see if what's inside of it has already been cached.

If you're just doing this:

{% cache %}
    Hi. I'm static text.
{% endcache %}

That's quite a bit more overhead than simply:

Hi. I'm static text.

With no real benefit.


Can you prevent upscaling when using Craft's image transforms?

As found here, this actually seems to be a requested feature that is not yet implemented. However, in the link given, Brandon also supplied a workaround for the time being:

{% set transform = {
width: min(150, image.width),
height: min(100, image.height)
} %}

<img src="{{ image.getUrl(transform) }}">


How could I load content from one Craft install into a template of another

I think your idea of RSS or JSON would work fine.

The only reason I can think of to use RSS over JSON would be if there was a possibility you wanted RSS readers to be able to consume the content as well.  Otherwise, I'd just stick with JSON and expose it over a web accessible API.


Is Craft suitable for these specific document management goals?

If Craft is good enough for the AP, it'll be good enough for everyone. ;)
I have little experience with EE, other than migrating away from it, but I have built enough in WordPress so here's my experience with that, as compared to Craft.
Don't be afraid of the "coding" part. Twig is pretty easy to learn and you'll learn to love it. Throwing together a plugin is harder but with Craft's decent MVC structure, it'll be much more easier to maintain—more so than trying to get WordPress to bend to your will. Creating plugins that look and feel native are much much easier, since you're just extending Craft's already built-in stuff.
(1) Create relationships between docs
I'd go so far as to say this is Craft's most killer feature. Try to do this in WordPress, for example, and you end up throwing plugins at the problem or convoluted sql queries to get it to do what you want. ACF is great but Craft's engine is fast, built-in, and it works within all elements.  After you've used Craft's relations, it's hard to use something else.
Especially if you store actual documents, like PDFs or Word docs, assets are WordPress' achilles heel. By default, WP stores files in year/month directory structure—which makes sense for blogging but not for any kind of database.  Assets in Craft are first-class citizens, right down to the fact you can even add custom fields to them.
So, let's say you want to store the document you've copied from a Word doc. Why not store the original document as well? You can do that easily and if you ever have to refer back to the "archived original" it's just a relationship away. You could store that relationship either on the asset itself (refer back to the document) or on the entry that refers to the asset. Either way, Craft knows about it and you can use the relationship.
(2) Ajax based filtering system
My experience with WP plugins is hit and miss. They either will work as advertised or they won't. But that's it. Stray from that beaten path and you might as well be writing it yourself. This reddit thread (contains NSFW language, obviously it's reddit) has some good reasons why rolling your own can more productive in cases like this. Craft is so easy to query and add parameters to; AJAX is really just another layer. You need a solid base and WP is not going to cut it here. Craft's UI is so intuitive, it's an easy choice, especially when you have end users to support.
(3) Document import/export
Hard to say what you want to do as far as import—there's a whole cottage industry built on trying to parse Word and PDFs to html etc.—but when it comes to exporting out the data, like you mentioned, since Craft stores in discrete fields, you can get at just the data you need. You'd want to use something like ACF in WordPress but it's not as nice to query, especially when it comes to relationships. Having that built-in to Craft is a huge advantage.
(4) Document Version System
Craft has entry revisions built-in and it's one of the best implementations I've used. You can publish over current versions, have multiple drafts of the same document, name them, etc. To do this inside WordPress takes a fair amount of effort. The only thing WP has that Craft does not is a built-in diff viewer so you can see what changed. That's harder to do on a field-by-field basis. You'd also need to roll your own "publish status" in Craft though. WordPress has a slight leg up here but really, emphasis on slight.
What else?
Multiple languages built-in. Again, WP users love to throw plugins at this problem but it really needs to be built into a CMS' DNA. Craft Pro has this ready to go. Even if you don't buy the Pro version, Craft stores it in a future-friendly way, so when you are ready to go, you're not jumping through hoops. Brandon Kelly mentions this and he's absolutely right.


How can I translate static text in my templates that have accents?

We are in the process of translating one of our client sites into 16 (yes that's 16!) languages and we haven't had any issues with accented characters.

The only thing I can suggest off the top of my head is to ensure you are using UTF-8 character encoding. Pop this in your <head>:

<meta charset="utf-8">

Hope that helps.


You use setContentFromPost method on the UserModel if you are posting to your plugin, like so (this is what happens when you save your profile in the control panel):

$user->setContentFromPost('fields');

There is also a setContent method, which takes a ContentModel or an array:

$user->setContent([ 'fields' => ['field1' => 'value'] ])

Behind the scenes, that runs the setAttributes method.


Internal Server Error while migrating to new server

It ended up being an unserialization issue. After exporting the sql file, I updated it with the new domain. The serialization part within the craft_info table needs to have the correct character length in front of the domain. Fixing that fixed my problem.


I did the trick so here is the code if it can help someone else

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

   $matrixData = array();
   $matrix     = $event->params['user']->getContent()->children;

   foreach ($matrix as $block){

      $block->getContent()->childrenDateOfBirth = '2000-10-10';
      $matrixData[$block->id] = $block;

   }

   $event->params['user']->getContent()->children = $matrixData;

}


How can I only allow authors to edit their own entires via front-end?

You can check if the current entry's author is the currentUser.

{% if entry.author.id == currentUser.id %}
    {# User can edit entry #}
{% endif %}


How do I cache with the ElementAPI plugin?

The ElementAPI plugin itself doesn't seem to offer a caching solution, but there is a fork from a guy which has implemented a caching option cache and cacheTime:
https://github.com/theolampert/ElementAPI

Update: They have introduced a new cache option in the official ElementAPI plugin (version 1.5).


Worldpay Gateway not redirecting to Customer Order screen on successful transaction

Are you testing from a local domain or on a remotely accessible server?

If it is a local domain then the return cannot work since Worldpay doesn't know where 'local' is.

If this is a remote server then:

Is the site turned 'on'? i.e. do you need to be logged in to view the front end
Do you have http auth in place (for instance to stop robots crawling a staging site).

If either of the above is true then it's likely that Worldpay can't get to the site.

Finally, do you have CSRF protection turned on? Try turning it off. If that solves the problem then you will need to bypass it in some way in order for Worldpay to work.


Categories in a RelatedTo - How do I not list the parent if there is a child?

You could just use what you got, loop through the categories and try to grab the descendants for each of them.

{% set entries = craft.entries.relatedTo(category) %}
{% set allMarkets = craft.categories.group('markets').level(1).relatedTo(entries) %}

{% for market in allMarkets %}
    {% set descMarkets = market.getDescendants() %}

    {% if descMarkets %}
        {% for market in descMarkets %}
            {% include '_includes/partial' %}
        {% endfor %}
    {% else %}
        {% include '_includes/partial' %}
    {% endif %}
{% endfor %}

Another good approach is to "collect" element IDs.

You would basically do the same as in the output loop of the above example, but instead of having the conditionals and extra queries in the output loop, you’d work with element IDs that you merge into an array. You can then query for the categories nicely using the id param in a craft.categories criteria model.

{% set entries = craft.entries.relatedTo(category) %}
{% set topMarkets = craft.categories.group('markets').level(1).relatedTo(entries) %}

{% set allMarketIds = [] %}

{% for market in topMarkets %}
    {% set descMarketIds = craft.categories.descendantOf(market).ids() %}

    {% if descMarketIds %}
        {% set allMarketIds = allMarketIds|merge(descMarketIds) %}
    {% else %}
        {% set allMarketIds = allMarketIds|merge([market.id]) %}
    {% endif %}
{% endfor %}

{% set allMarkets = craft.categories.id(allMarketIds) %}

{% for market in allMarkets %}
    {% include '_includes/partial' %}
{% endfor %}

Update:

One more approach! I just noticed, that you can simply test whether a category has descendants or not. This should probably be best from a performance point of view.

{% set entries = craft.entries.relatedTo(category) %}
{% set allMarkets = craft.categories.group('markets').relatedTo(entries) %}

{% for market in allMarkets %}
    {% if market.getDescendants().total() == 0 %}
        {% include '_includes/partial' %}
    {% endif %}
{% endfor %}


What is causing Craft CP assets(JS/CSS) to appear in front-end pages?

those CP files are included by CpAsset asset bundle.

if your plugin asset bundle depends on CpAsset:

class YourPluginAsset extends AssetBundle
{
    public function init()
    {
        $this->sourcePath = __DIR__ . '/dist';
        $this->depends = [
         CpAsset::class,
        ]
     //....
    }
}

and if you register your plugin asset in frontend or backend template:

{% do view.registerAssetBundle("ns\\prefix\\YourPluginAsset") %}

or via controller:

 $this->view->registerAssetBundle(YourPluginAsset::class);

those file are added to that page automatically.


Problem with switch statement in language picker - [Solved]

I forget to update locale template code with the same switch statement. Now problem solved.


If you want to login a user, you need to use the login function

craft()->userSession->login($loginName, $password, $rememberMe))


"Fatal Error 'OAuth\Common\Storage\Session' not found" when trying to connect to connect to Google or Vimeo

Hey Daniel and sorry for the lack of response. Please get in touch at ben@dukt.net and I'll be happy to offer you the license hoping you'll accept my apologies for the huge delay in my reply.

Regarding your issue, it looks like some classes haven't been loaded (OAuth\Common\Storage\Session). Can you please check if Session.php file is present in OAuth plugin's folder under oauth/vendor/lusitanian/oauth/src/OAuth/Common/Storage.

Also, you might consider get a fresh copy of the latest release of the OAuth plugin and try to unzip/re-upload the files, I'm thinking you may just have some missing files and that could fix the problem, otherwise we'll dig further.


Craft paginate not working in merge Queries

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 %}


Route to entry in Arabic not working but category route is OK

So it looks like I made some false assumptions.
In Chrome the Arabic URLs displayed are reversed in segment order.
However, I assumed the same was true for Craft routing - the UI behaves in a RTL fashion when editing Arabic text in routes editing interface. But this is not true - it seems that Craft routes don't reflect the browser behaviour for RTL languages. Craft still keeps the normal order of segments when processing the route. So weirdly the URL is reversed in browser but Craft seems to 'see' the route match as left to right. Once I adjusted the route to 'normal' left to right segments the routing worked fine.


they updated the sourceNodes cycle since this config, you will need to update the schema first doing something like this:

An example using the body hook if you need it:

createSchemaCustomization({ refresh: true }).then(() => {
    sourceNodes({ webhookBody });
});


Commerce - Email users on new product input

There is this plugin https://plugins.craftcms.com/craft-commerce-back-in-stock
Although I haven't used it, it sounds like it will do what you need.
Always worth having a look for things at https://plugins.craftcms.com


Sprout E-mail: 400: HTML Content URL Required - Campaign Monitor


Update an order custom field after order complete in Craft 3

What I wrote is correct. I debugged it, and I had a problem in another place where the order did not get completed in the first place. silly me LOL.
So my answer is:

Event::on(Order::class, Order::EVENT_AFTER_COMPLETE_ORDER, function(Event $e) {
    $order = $e->sender;
    $order->setFieldValue("customFieldHandle", "My value");
});


Redirects or Routing for Landing Page URL's?

You can either set the URL Format of the landing pages channel to {slug} (the same as your normal pages)

Or you could try putting the landing pages in the normal pages structure, but give them a new entry type so you can use different fields.


If a simple timestamp is unique enough, you can use:

{{ now|date('YmdHis') }}

Which will give you something like:

20150723170500


Trying to Add a Specific Menu Depending on User Group

OK, so enabling the devMode helped point me in the right direction.

First, I needed to change it to

{% if currentUser and currentUser.isInGroup('advisors') %}

Otherwise I was getting an error message when nobody was logged in ("Impossible to invoke a method ("isInGroup") on a null variable").

Then I discovered that the user I was testing wasn't added to any groups!  I could have sworn I set up the user with a group assigned, but apparently not.  :(


Output error of the current password correctly

Change:

{{ errorList(account.getErrors('password')) }} //Current password

To:

{{ errorList(account.getErrors('currentPassword')) }} //Current password


How do you setup CloudFront in P&T S3 plugin & how do you know if it works?

I wrote up an article that might be helpful for future-people looking for step by step instructions on setting this up: Setting Up AWS S3 Buckets + CloudFront CDN for your Assets


Looks like you want to implement a feature to vote for entries. Have a look at these plugins, they make this really easy for you.

https://www.doublesecretagency.com/plugins/upvote
https://github.com/dukt/craft-like

If you want to implement something yourself, I would look into adding the button behavior using JavaScript, listen for click events and send the data over XMLHttpRequests to the entries/saveEntry controller.


Commerce - Advanced shipping cost calculations

products that don't require shipping costs are (obviously) included in the order total which means the shipping costs are higher than they should be.

It sounds like you're only using one shipping class? Commerce can provide multiple ways to ship (methods) but also how to handle different categories of products (shipping categories).
What I'd do is create 2 shipping classes: one that includes shipping, another without.
Then set the products that have the shipping costs built-in to only use the Shipping Included in Price category (whatever you've named it).  That takes care of excluding costs for the products that already include shipping.

You mention the cost for the other products is based on the total of the order. One way to handle this would be to set a percentage per item since those items will end app as the total (ignoring the other products that already have shipping cots.)
You can set this up in the shipping Costs panel. So in the General category in the example below, I set the shipping cost to be 10% of the item (0.1) but you could also do weight or a flat per item. You can also set a minimum or max shipping costs depending on what you're trying to do.

Custom adjustment types are deprecated but the doesn't affect shipping, discount, and tax adjusters—basically items that Commerce knows about.


Change the javascript of the asset file to something like this and it will work

$(function(){
    $(".field .input .elementselect .element:not(.linked)").each(function(){
        var $this = $(this);
        if (!$this.data("url")) { return false; }
        var $a = $("<a class='icon'> </a>")
            .attr("href", $this.data("url"))
            .attr("title", "Download")
            .addClass("download")
            .addClass("sharebtn")
            .addClass("icon")
            .attr('download', $this.data('label'))
            .appendTo($this);
        $this
            .addClass("linked")
            .prepend($a);
    })
});


Return all cache records, delete caches with prefixed keys

Not without some brute-force cracking.

The keys you pass into CFileCache's set and get methods are an md5 hash of your key prepended with your Craft installation's appId (which by default is a randomly generated string).

So with a key of testKey, that could end up as a value of 3f8b3c45a9c6f395d02b930f18910a92.  For CFileCache, that value ends up being the file name of the cache file and gets put in craft/storage/runtime/cache/3f8b3c45a9c6f395d02b930f18910a92.bin.

Later, when you call get and pass in the key of testKey, it goes through the same process and checks to see if a file named 3f8b3c45a9c6f395d02b930f18910a92.bin exists.  If it does, it knows there is a match.

As you can see, there's no way to find that match without knowing the key ahead of time (unless you brute-force cracked md5, which is doable, but probably not practical for your use-case).


How can I create a loop to cycle thru each category and the the entries within each category?

First you loop through the categories then use the category to loop through all the entries related to that category.

{% for category in craft.categories.group('categoryGroup') %}
  {% for post in craft.entries.section('posts').relatedTo(category) %}
    {# your markup #}
  {% endfor %}
{% endfor %}


It seems to be what you need is Twigs extend functionality. What you have here is a very common template structure so there is nothing out of the ordinary!

Firstly, going from your code I'd recommend your main layout template file looks something like this. The idea here being that these elements will not change for each page, but the content or information displayed inside them will. This template file is where you would also load in your CSS, Javascript etc.

    {% include 'components/header' %}

        {% block content %}{% endblock %}

    {% include 'components/footer' %}

Say you have a page that will sit on www.yoursite.co.uk/about. You could create a template file in your templates folder called about.twig, and to use your base template file it would look something like this:

{% extends "path/to/main/layout" %}

{% block content %}

The content for your about page

{% endblock %}

Hope that clears it up for you!


It does not work because the function does not accept slugs. Not sure what to answer here. It only accepts objects of type Element and ids as identifier.

You can see the magic here

foreach ($elements as $element) {
if (is_numeric($element)) {
    $relElementIds[] = $element;
} else if ($element instanceof ElementInterface) {
    $relElementIds[] = $element->id;
} else if ($element instanceof ElementQueryInterface) {
    foreach ($element->ids() as $id) {
        $relElementIds[] = $id;
    }
}

These are all kind of things that the relatedTo can use/work with. If you want to get a relation by slug you have to fetch the element first.

.relatedTo(craft.categories.slug('municipal').one())


Copy a Craft 3 site to my local machine (MAMP)

From what I see in your screenshot, it looks like you stumbled upon a Craft 3 installation, in which case neither a Craft nor Public folder exist.

Craft 3 specific

The public folder is now called web, so that's where you should point your MAMP documentroot (or whatever that's called in MAMP). The Craft code is now located in composer's vendor folder, that should magically appear after running composer install. Craft's source would then be in vendor/craftcms/cms.

You can read more about the overall structure of a Craft CMS 3 project in the Setting up a New Craft CMS 3 Project article.

Frontend build tools and JS dependencies (package.json, webpack.mix.js)

Further more, I see that Laravel Mix is used for frontend (js, css) automization, meaning that you have to install JS dependencies by running npm install or yarn install, after which you can use the command defined in package.json to run Mix. I guess this is something like npm run watch (when developing) or npm run prod before you push anything to production.

Modules

And: I see a modules folder, that would most likely mean that a custom module was used for this specific site. Modules are a (poorly documented ;)) Craft 3 way of extending your site without building a plugin and trying to get that to work through composer. They are essentially a wrapper for Yii2's modules.

It's very possible that the Module is just vestigial, however, since that folder is created by default if you do composer create-project -s RC craftcms/craft PATH. You can read more about Modules in the Enhancing a Craft CMS 3 Website with a Custom Module article.

Environment settings

Last but not least: copy .env.example to .env and use that to set credentials for your environment (db settings and stuff).


<a href="{{ page.getUrl }}" {{craft.request.getSegment(2)|lower==page.slug|lower ? 'class=is-active'|e : ''}}>
    {{ page.title}}
</a>

You can use something like this, only you compare your getSegment() with the related Title field instead of page.slug if your page in your url has the pagetitle name.


I'd use a Matrix field with a block for each floor. Adding a block provides fields for an Asset for the floorplan and a text box for the dimensions.

The dropdown is purely javascript based, and I'd suggest you put all the floors in the HTML on page load, then switch between them using the values of the dropdown field.


Why are variables persisting inside of my for loop?

This is totally normal and expected behavior. In fact, it's critical for some looping situations, and pretty standard across programming languages. Wouldn't you expect to find this same behavior in PHP?

Think about situations where previous loops build on each other. Here's an example of a situation where loop values need to be retained...

{% set totalPets = 0 %}

{% for petOwner in craft.entries.section('petOwners').find %}

    {% set totalPets = totalPets + petOwner.numberOwned %}

{% endfor %}

This group of people owns {{ totalPets }} pets total.

Ultimately, this is a simple scope issue. Generally speaking, for loops don't exist in their own scope... they are a part of the scope created by the parent script.

If you want to ensure that your logic takes place in a separate scope, take a look into Twig macros... A macro would probably be very helpful in your situation.


Plugin variables class versus twig functions/filters class

The following answer is all personal opinion of course, but here's a key quote from the docs:

  Many of your template variable methods will likely be simple wrappers for your service API methods.

If you look at Craft's built-in Variables, they're all about exposing data. Personally, I like to think of Variables as template APIs.

Twig Filters, on the other hand, is all about modifying data (e.g. capitalizing strings, rounding numbers, formatting dates, sorting arrays etc). If you compare Craft's built-in Variables to its Filters, I think the distinction between the two starts to become fairly clear.

To exemplify:

Bad use of Variables:

{% set sortedEntries = craft.myPlugin.sortByAwesomeLevel( entries ) %}
{{ craft.myPlugin.makeEntryTitleAwesome( entry.title ) }}

The above template code use Variable methods to modify data already present in the template. It works, but it looks pretty convoluted and doesn't really make sense, neither from a Twig nor Craft point of view. Here, using Filters would be much more appropriate:

{% set sortedEntries = entries | sortBy( 'awesomeLevel' ) %}
{{ entry.title | makeAwesome }}

Good use of Variables:

{% set awesomeEntries = craft.myPlugin.getAwesomeEntries %}
{% set sortedAwesomeEntries = craft.myPlugin.getAwesomeEntries( { 'sortBy' : 'awesomeLevel' } ) %}

Here, MyPlugin exposes a "template API" method called getAwesomeEntries. The only thing it does, is to pull entries that are awesome, optionally taking an arguments object for sorting or the like. Obviously, this would not be feasible to implement as a Filter:

{% set awesomeEntries = entries | getAwesomeEntries %}

In short – if you need to expose data, use a Variable. If you need to modify data, use Filters.


If you're just looking to get the author of an entry, it's a simple as:

{% for entry in craft.entries.section('blog').limit(1) %}

    {{ entry.title }}

    {{ entry.author.firstName }} {{ entry.author.lastName }}

{% endfor %}

If you're looking to get every user associated with every Users field for an entry, your relatedTo syntax will work:

{% for entry in craft.entries.section('blog').limit(1) %}

    {{ entry.title }}

    {% set allRelatedUsers =  craft.users.relatedTo(entry) %}

    {% for user in allRelatedUsers %}
        {{ user.firstName }} {{ user.lastName }}
    {% endfor %}

{% endfor %}

The reason that returned nothing in your original question is because the "author" field isn't a proper Users field type - it's more of a special case user field.


Is it possible to find what Matrix Block aren't being used

Nothing native, but it can easily be done with an SQL query – something like this should work (note that all the queries assume that your dbPrefix setting is set to 'craft_'):

SELECT bt.id, bt.handle, f.handle as field
FROM craft_matrixblocktypes bt
INNER JOIN craft_fields f ON bt.fieldId = f.id
LEFT JOIN craft_matrixblocks b ON bt.id = b.typeId
WHERE b.id IS NULL

The above query would output a table with the id and handle for all block types that aren't used, in addition to the handle for the Matrix field they belong to, i.e.

id  | handle             | field
------------------------------------------
13  | someMatrixBlock    | someMatrixField
4   | anotherMatrixBlock | someMatrixField

To actually execute the SQL query, you can use a free tool like Sequel Pro or phpMyAdmin – or write a custom plugin that uses the QueryBuilder.

Edit

Upon request in the comments below, here's a query that will list all block types that are in use (i.e. there are blocks for each particular block type). The number of blocks for each type is listed in a count column:

SELECT COUNT(bt.id) as count, bt.id, bt.handle, f.handle as field
FROM craft_matrixblocktypes bt
INNER JOIN craft_fields f ON bt.fieldId = f.id
LEFT JOIN craft_matrixblocks b ON bt.id = b.typeId
WHERE b.id IS NOT NULL
GROUP BY bt.id

...and here's a query that will output a table with all blocks, sorted by block type, with the ID and URI for the entry which "owns" each particular block:

SELECT b.id as blockId, bt.handle as blockType, bt.id as blockTypeId, e.id as entryId, i18n.uri as entryUri, f.handle as field
FROM craft_matrixblocks b
INNER JOIN craft_entries e on e.id = b.ownerId
INNER JOIN craft_fields f on f.id = b.fieldId
INNER JOIN craft_matrixblocktypes bt on bt.id = b.typeId
LEFT JOIN craft_elements_i18n i18n on i18n.elementId = e.id
ORDER BY bt.id

Note that for Craft 3, you'll need to replace the craft_elements_i18n table with craft_elements_sites:

SELECT b.id as blockId, bt.handle as blockType, bt.id as blockTypeId, e.id as entryId, sites.uri as entryUri, f.handle as field
FROM craft_matrixblocks b
INNER JOIN craft_entries e on e.id = b.ownerId
INNER JOIN craft_fields f on f.id = b.fieldId
INNER JOIN craft_matrixblocktypes bt on bt.id = b.typeId
LEFT JOIN craft_elements_sites sites on sites.elementId = e.id
ORDER BY bt.id

If you want to limit that last query to only list the blocks for a particular block type, you can replace the ORDER BY statement with this:

WHERE bt.id = 2

Where 2 is the ID for the block type you want to list, obviously.


Showing different field layouts for entries within the same structure

The only way to do this is to create multiple entry types for your structure section.
Each entry type has its own field layout (can have different fields from the other entry types in that section).
Sadly, it's not possible to restrict entry types to a particular level in a structure – i.e. if you create "Landing Page" and "Sub Page" entry types, there's no way in Craft to make sure that the level 1 and level 2 entries actually use those entry types, according to their level. So, ideally you should a) make sure whoever edits the content in that section makes sure that they should be careful to use particular entry types for particular structure levels, and b) design and create templates that are flexible enough to work even if, for example, somebody publishes a "Sub Page" entry at level 1.
Most likely, you should change your current templating setup with something like this, if you go down this route.


Accessing global field values in site loop

Finally solved with the following code:
    <select  class="form-control " name="sites" id="company-select">
    <option value="" class="small text-muted">Please select your company</option>
    {% for site in allSites %}
        {% set siteId = site.id %}
        {% set groupId = site.getGroup().id %}
        {% if groupId == '5' %}
            {% set setForSiteId = craft.app.getGlobals().getSetByHandle('siteInfo', siteId) %}
            {% if setForSiteId.showInDropdown == '1' %}
            <option value="{{baseUrl ~ '/' ~ site.handle }}">{{site.name}}</option>
                {% endif %}
        {% endif %}
    {% endfor %}
    </select>


Make entry in nav not clickable and reroute

You can use the level method to determine which iteration of the nav you are on and change the behavior:

    {% set pages = craft.entries.section('page') %}
    {% nav page in pages %}

            {% if page.level == 1 %}
                {{ page.title }}
            {% else %}
                {{ page.getLink() }}
            {% endif %}
            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

    {% endnav %}

of if it's only one particular entry, then you can create a conditional to check for that entry (using slug, id, title, or any other attribute or field value).

    {% set pages = craft.entries.section('page') %}
    {% nav page in pages %}

            {% if page.slug == "myPage" %}
                {{ page.title }}
            {% else %}
                {{ page.getLink() }}
            {% endif %}
            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

    {% endnav %}

If the url is accessed directly you can add a redirect to the template.

{% if entry.level == 1 %}
    {% redirect siteUrl %}
{% endif %}


My Solution uses:
1. LJ Dynamic Fields Plugin
2. 1 Structure I called SiteMenu

What I did is:
1. Install LJ Dynamic Fields
2. Setup a MenuLinkPage Field of fieldType Dynamic DropDown
    - In the Drop Down Options is like this because am pulling links from entries and category

{% set menuIds = craft.entries.section('siteMenu').ids()%}
{% set menuIdsString = menuIds | join(', not ') %}

{ "value":"#","label":"Select Page"},
{%for category in craft.categories.limit(null) %}
      { "value":"{{category.id}}" , "label":"category-{{category.group}}--{{category.title}}"},
{%endfor%}
{%for entry in craft.entries.limit(null).id('and, not '~menuIdsString).order('type ASC')%}
      { "value":"{{ entry.id }}" , "label":"{{entry.type}} - {{ entry | raw }}"
      }
      {% if not loop.last %},{% endif %}
{%endfor%}

Setup a SiteMenu Structure on its layout I added MenuLink Field.
Then added Pages I need for my Menu by selecting from MenuLinkPage field.
Call the menu in my _layout template like this

{% block menu %}

{% set pages = craft.entries.section('siteMenu').level('<=2') %}

 close menu

{% cache %}
  {% nav page in pages %}

        {% set entryId = page.menuLinkPage %}

        {% if entryId > 0 %}
          {% if craft.categories.id(entryId)|length %}

{{page.title}}
          {% else %}

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

{{page.title}}

        {% endif %}

            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

    {% endnav %}

{% endcache %}

{% endblock menu %}

I hope this helps


How to add dynamic watermarks to images in Craft/Twig

You'd definitely need a plugin for this. Craft's native abilities don't cover watermarks.

I've never attempted it myself, so these are just "best guesses"... but give the following plugins a shot:

https://github.com/fruitstudios/AviaryImageEditor/
http://michaelrog.com/craft/imagesmith

As always, you can find a full list of existing plugins here:

  https://straightupcraft.com/craft-plugins

If none of those work for you, you may need to develop your own custom plugin to handle it.


Craft 2 JS error in CMS since upgrade to 2.7.0

Try reinstalling Craft. I believe there was another report from a user that had similar JS errors. Try replacing the core Craft files in craft/app and see if that helps.

Craft 2.7.1 was also recently released.


Is it possible to output message on successful save with Guest Entries?

You could append a query string on your redirect url that you can then query for in your template. I've used this to display different messages for a new post or an edited post.

<input type="hidden" name="redirect" value="my-photos?message=photo-added">

{% set message = craft.request.getQuery( 'message' ) %}

{% if message|length and message == 'photo-added' %}

Thank's for uploading your image

{% endif %}

To use fields from the saved entry you could use a plugin and watch for the entries.onSaveEntry event that will fire when using the Guest Entries plugin.

craft()->on( 'entries.onSaveEntry', function( Event $event ){
  // Grab the entry from post request
  $entry = $event->params['entry'];

  // Add some conditionals so you only perform the redirect for the section you're posting to in the front end

  $name = $entry->getContent()->fieldName;

  // Render a template and pass the $name in
  //( not sure how to do this? )
});


I've given up on this, from what I've looked at it's not going to be easy without a migration that creates the fields first (don't really want to do this for updatability issues). I've changed the scope of the plugin to be more bare-bones, and I think it's better for it.


Create a new row every 3 items in a matrix

To my understanding this should work for a matrix field (called imageLinkBoxes) that contains only one type of block (imageLinkBox) that has 3 fields (imageLinkBox.linkText, imageLinkBox.linkUrl and imageLinkBox.text)

{% set aboutInfo = entry.imageLinkBoxes %} {# get all the blocks in the matrix #}

{% if aboutInfo|length %} {# check we have at least one block in the matrix #}

    {% set infoGrouped = aboutInfo|batch(3) %} {# group them in groups of 3 blocks #}

    {% for group in infoGrouped %}  {# loop through all the groups #}

        {% set row = 'row--' ~ loop.index %} {# set the class #}

 {# open the row #}

        {% for block in group %} {# loop through all the blocks in current group #}

                            {{ block.linkText }}

{{ block.text }}

        {% endfor %}

 {# close the row #}

    {% endfor %}

{% endif %}

If for some reason you have more than one type of block in the matrix, then you would need to do a change:

Replace:

{% set aboutInfo = entry.imageLinkBoxes %}

With:

{% set aboutInfo = entry.imageLinkBoxes.type('imageLinkBox') %}

That would filter the blocks to only those of the type imageLinkBox.


You're not far away by combining what you already have with the example in the docs! You just need to pass in the category (.relatedTo(category)) and number of entries (.limit(10)) to show on each page.
{% set query = craft.entries()
    .section('mySection')
    .relatedTo(category)
    .limit(10)
%}

{% paginate query as pageInfo, pageEntries %}

{% for entry in pageEntries %}

{{entry.title}}

{% endfor %}

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


Why is craft adding a rel attribute with inline styles in my textarea?

Looks like this was a Redactor bug they fixed back in 10.1.

The latest version of Craft (2.4.2684) is currently running Redactor 10.2.2, so make sure you're Craft installation is up-to-date.


Redactor plugin not found: imagePosition Craft 3

The reason you get the error is probably that you had the Redactor Image Position plugin installed in Craft 2. If the plugin was available for Craft 3, you'd just need to update to it. But since it's not available, you're kinda out of luck.

To remove the error message though, you only need to remove 'imagePosition' from the list of enabled plugins in your redactor config files, they're located at config/redactor and works the same as in Craft 2.


Loop through structure entry types and matrix blocks

If I was building a single page website I might create a matrix field with different blocks for each "page".

{# Navigation #}
{% for block in entry.contentBlock %}

{{ block.title }}

{% endfor %}

{# Content #}
{% for block in entry.contentBlock %}

     {{ block.body }}

{% endfor %}

This will allow someone to re-order "pages" easily under one entry. You can also create several different block types with different fields in if these "pages" needed to be different.


Redirect to url based on current year/month

You never use {{ echo tags within other Twig tags. What you have to do instead is to use string concatenation.
{% redirect "calendar/" ~ now.year ~ "/" ~ now.month %}


As far as I know, (currently) the only way to filter matrix blocks is to use the type method to filter by block type or to limit the amount of returned matrix models with limit.

Here's what I'd do:

{% set searchString = 'sitelogo' %}

{# Search for potential matrix blocks #}
{% set foundBlocks = attachmentGlobals.globalFiles.type('files').search(searchString) %}

{# Loop through the result and output the right one #}
{% for foundBlock in foundBlocks %}

    {% if foundBlock.fileId == searchString %}
        <img src="{{ foundBlock.fileAsset.first.url }}" alt="{{ foundBlock.fileAsset.first.title }}">
    {% endif %}

{% endfor %}

You can't use search('fileId:sitelogo'), because that would filter for entries with  fileId:sitelogo and not entries with a matrix block fileId:sitelogo.


If they can live at different URL's, you could setup multiple routes under Settings->Routes. Give them different URL structures like so:

blog/slug loads mytemplatefolder/blog_template
another-url/slug loads mytemplatefolder/another_template


Assets, Multi Locale and 'Target Locale'

The "Target Locale" setting under the Asset field's settings is referring to which locale do you want to select assets in.  When it's set to "Same as source", then, for example, if you're viewing an entry in German, the Asset selector modal will only display Assets assigned to the German locale.  And if you were viewing the entry in Dutch, it would only show Assets assigned to the Dutch locale.

If you change the "Target Locale" from "Same as Source" to a specific local (i.e. German), then no matter what local you're viewing an entry in, only Assets assigned to the German locale would show.

When saving a new entry in locale 1, Craft "copies" content data (anything stored in the craft_content table in the database) over to the other locales for fields marked as translatable as a starting point for the other locales.  All relational fields (Assets, Entries, Users, etc.) aren't "content" and they are stored in the craft_relations table and Craft currently doesn't copy that information over.

Ironically, if you uncheck the "This field is translatable?" checkbox in the Asset field settings, it would show up on the other locales, because in that context the Assets aren't stored on a per-locale basis.


The cause of this issue with a 90% likelyhood are your craft settings

Before you try any of the below steps, try clearing your cache first!

Sometimes some leftover cache is all that needs to be removed to fix an issue...
rm -rf runtime/* or ./craft clear-caches/all

3 Settings which you may have set wrongly:

All of the below mentioned settings should basically be pointing towards my_current_website.com, a reference to that or something more relative like a simple /.

There are 3 Places where you should check if you have my_live_website.com set as your current host/site.

.env's SITE_URL, BASE_URL or anything else that has  SITE or URL in it's name
config/general.php's siteUrl Value(s)
Your Craft Control Panel Settings, my_current_website.com/admin/settings/sites (URL may differ based on config/general.php's cpTrigger value)


Non-numeric characters in number field producing errors

Just tested this on a local Craft3 setup and here's what I discovered...

If the decimal points setting on the number field is set to 0, adding text in the number field will display the pretty errors below:

If the decimal points setting is set to anything else, you get the Twig error mentioned in the title of this post:

  number_format() expects parameter 1 to be float, string given

I'd recommend opening an issue in the Craft CMS repo as I imagine the number field ought to display the pretty errors no matter if decimal points is set or not.


Using Symbolic Links for Very Large Image directories

Am I missing something or is there a better/easier/default way to do handle large numbers of images/assets across DEV & LIVE environments when they are on the same server/account?

Ideally you'd move them to a cloud-based solution (S3, etc.), but locally using a symlink is a perfectly fine option, too.  Just make sure that Apache is configured to follow symlinks.

Wither either the symlink or cloud-based solution, just remember if you've got dev and live using their own databases and you perform an Asset operation on one (upload a file, delete a file, rename, etc.), then the other database will be out of sync and you'd need to run the "Update Asset Indexes" tool to pick up the change.


How can I display the related posts (by category) at the bottom of each post?

This can be accomplished using Craft's Relations.

My example code assumes you know the blog categories slug, and that you are pulling posts from a single category.

First, you'll have to get a reference to the category ElementCriteriaModel object pointing to the category of the blog post.

{% set category = craft.categories.slug('your-category-slug').first() %}

With a reference to the category model, you'll be able to find related entries.

{% for post in craft.entries.section('blog').relatedTo({targetElement: category}) %}
    {% if post.id != entry.id %}

{{ post.title }}

            {{ post.body }}

    {% endif %}
{% endfor %}

The if statement makes sure you aren't including the current post with the related posts.


Put the force parameter to true

MyPlugin::log("Errors:\n\n" . print_r($fieldsData, true), LogLevel::Error, true);

Custom Log in Craft


How to receive email notification when an error or bad request happens?

I'd recommend using a service like Sentry or Bugsnag that are tailored exactly for this situation and include some Craft integrations as well:
https://plugins.craftcms.com/search?q=sentry
https://plugins.craftcms.com/search?q=bugsnag


How to create sub-nav when using a structured navigation heirarchy?

There is an nice recipe on the craftcookbook.net site from sprocketeer that explains exactly this.

{% set topEntry = craft.entries.depth(1).slug('information').first() %}

    {% nav subEntry in topEntry.getDescendants() %}

{{ subEntry.title }}
            {% ifchildren %}
{% children %}
{% endifchildren %}

    {% endnav %}


Accessing the raw post data from an $event

You can just grab whatever you need either from $_POST or, more preferably, craft()->request->getPost().


Order related entries by number of categories they have in common with current entry

You can use the Similar plugin for this. I don't know that you can do it natively otherwise.


Whats the best way to place content without using a lot of categories?

There is no definite answer to your question but I think you can get pretty much what you want using just two types of categories.
Section setup

create 2 category groups:

device types (with the deviceTypes)
post types (with the postTypes)

create an Articles section (with the article handle)
configure you section with the following Entry URI format: {articlesDeviceType.slug}/{articlesPostType.slug}/{slug}
on the entry type of the articles section (you just need one entry type), add the following required custom fields:

Device type (with the articlesDeviceType handle)
Post type (with the articlesPostType handle)

Your entries should now have the URL structure you wanted.
Archive page
Now if you want an archive of all smartphone related tips, you can get the entries with the following entry query in a template:
{% set tipsCategoryId = craft.categories().group('postTypes').slug('tips').ids() %}
{% set smartphoneCategoryId = craft.categories().group('deviceTypes').slug('smartphones').ids() %}

{% set entryQuery = craft.entries().section('articles').relatedTo([
    'and',
    { field: 'articlesPostType', targetElement: tipsCategoryId },
    { field: 'articlesDeviceType', targetElement: smartphoneCategoryId },
])

This should return an EntryQuery matching all entries related to both smartphones device type and tips post type.


This question is from a long time ago, but nowadays there's a great 3rd-party plugin that lets you do this: https://github.com/engram-design/SuperTable


Imported entries showing wrong post date

Try using the date Twig filter instead

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

If the post dates on your entries are stored as datetime objects then the above should work.


Local MAMP site keeps redirecting to live production site

There was a rule in my .htaccess to remove www that was redirecting to the live production site. Once I removed that I needed to delete my browser cache.


Solved it by just serving the file within a controller action like this:

public function actionCacheCraftServiceWorker () {
    $serviceWorkerFile = Craft::getAlias('@skayo/cachecraft/assetbundles/cachecraft/dist/js/CacheCraftServiceWorker.min.js');

    return Craft::$app->getResponse()->sendFile(
        $serviceWorkerFile,
        'CacheCraftServiceWorker.min.js',
        [
            'mimeType' => 'application/javascript',
            'inline' => true
        ]
    );
}

and using this event to register the front-end url:

Event::on(
    UrlManager::class,
    UrlManager::EVENT_REGISTER_SITE_URL_RULES,
    function (RegisterUrlRulesEvent $event) {
        Craft::debug(
            'UrlManager::EVENT_REGISTER_SITE_URL_RULES',
            __METHOD__
        );
        $event->rules['cache-craft-service-worker'] = [
            'route' => 'cachecraft/frontend/cache-craft-service-worker',
            'suffix' => '.js'
        ];
    }
);

Now I can just access it with https://example.com/cache-craft-service-worker.js which works perfectly fine.


How can I clone a specific Site in Craft, not the default?

I've come across this issue and imagine there will be a better solution in the future, but for now you can change your default site to the one you want to duplicate.


Show tags in tag group only being used on live entries

Your mention tags, but it seems like you're merging Categories and Tags together and trying to loop through the results.

If you leave Categories out of the equation it's as simple as this.

If you want Categories and Tags, you'd repeat that process twice and merge the results.

Note that using |merge on full-fledged arrays of objects is sketchy, though, since it's difficult for PHP to know how to compare the objects for equality.  You'll be much better off merging on something primitive, like an array of element IDs.

Something like:

{% set categoryIds = craft.categories.group('storiesCategories').ids() %}
{% set tagIds = craft.tags.group('storiesTagGroup').ids() %}
{% set elementIds = categoryIds|merge(tagIds) %}


How can I prevent "spam" user registrations?

Plugins:

Snaptcha (private beta)
Works with the User Registration Form, Contact Form Plugin and Sprout Forms Plugin
Invisible Captcha (private beta)

.

Config:

If you don't mind having a few spam-users in your list. Just add purgePendingUsersDuration to your config.

This will purge all users which haven't been activated for x time.


If someone still is looking for an answer:

{% block locale__switch %}
    {# Loop through all of the site locales #}
    {% set otherLocales = craft.i18n.getSiteLocaleIds() %}

    {% for locale in otherLocales %}

        {# Check if site is category or Entry #}
        {% if category is defined %}
            {% set siteLocale = category.locale(locale) %}
        {% elseif entry is defined %}
            {% set siteLocale = craft.entries.id(entry.id).locale(locale).first %}
        {% endif %}

        {# Make sure that it's actually localized to this locale #}
        {% if siteLocale.locale == locale %}

            {# Output a link to it #}
            {{ locale }}{% if not loop.last %} |{% endif %}
        {% else %}

            {# Output a link to the hompage #}
            {{ locale }}
        {% endif %}
    {% endfor %}
{% endblock %}


entry.ancestors returns an ElementCriteriaModel (→ getAncestors() in the Craft docs) prepped to return the entry's ancestors.

entry.ancestors.level(3) makes it return only entry ancestors which are at 3rd level of the structure.

As you well pointed out in the comments, an entry can only have one ancestor on a particular structure level. So you can now use the first() method to get this one entry. Keep in mind that if there's no ancestor at that level, the method won't return anything (null).

{% set ancestorL3 = entry.ancestors.level(3).first() %}

{% if ancestorL3 %}
    {{ ancestorL3.title }}
{% endif %}


Image Transforms adding white to edges of image

As @BradBell says, using Imagick fixed this for me.
Following https://stackoverflow.com/a/16154605/662826 I uncommented the Imagick extension, reuploaded and the compression was much better and white line gone.


Without knowing if this a channel, structure or single and no provided code I can't give you a detailed answer, but I think you are looking for Craft's redirect tag.

Redirect Tag


Refused to display/connect when previewing entry on multi-site setup

X-Frame-Options

The problem is that your site's .htaccess file prevents unicorn.com from viewing all-your-base.com in an iframe because the X-Frame-Options header has not been configured for allowing this.

Securing Craft mentions that you have to add headers for:

Strict-Transport-Security
X-Frame-Options X-XSS-Protection
X-Content-Type-Options
Content-Security-Policy
Public-Key-Pins

So although the following .htaccess-code doesn't add all of these headers, they together make the "refused to connect" go away, by allowing the frame-ancestor to be unicorn.com even when previewing content on all-your-base.com in an iframe (which is how the preview works).

# Unset X-Frame-Options that has been previously set possibly by Craft
Header unset X-Frame-Options

# Allow unicorn.com to request itself in iframes (for live preview)
Header always set X-Frame-Options "ALLOW-FROM https://unicorn.com/"

# Allow unicorn.com to request all-your-base.com in iframes (for live preview)
Header set Content-Security-Policy "frame-ancestors unicorn.com"

These headers are simply strings that are attached to - you guessed it - the header of the HTML-page that is transmitted from the server.

It's up to the  browser how to interpret them. Content-Security-Policy is for instance not supported on IE11.

In this case, Content-Security-Policy is used by Chrome and X-Frame-Options is used by IE11 and others.

Access-Control-Allow-Origin

You might also get error messages in the console because Access-Control-Allow-Origin is missing. Here is an example of setting that header. Note that it doesn't support multiple domains, so here I serve the local development address together with the production site address using the SetEnvIf command:

SetEnvIf Origin "http(s)?://?(unicorn.com|unicorn.local)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header merge Vary Origin
Header set Access-Control-Allow-Credentials "true"


For HTTP the default port is 80 and for HTTPS it's 443,
obviously.
If port is omitted in the site URL, then the default
one is used.
If you want to use a different port, you must
specify a different port in the URL.

So, the logical conclusion is that the port must be present in the URL. When building URLs to entries, for example, the site URL is fetched to generate the final URL. So, unless that URL has port specified in it, you'll get URLs with the wrong port. That's exactly how it should work.

The best way to approach this, however, would be to use Craft multi-environment settings to set it up. That way you won't have to dig into the config files whenever you deploy your site.


Query all categories once and get individual categories from array

Your issue is that as soon as you call .find(), your ElementCriteriaModel returns an array of elements. In other words, the ElementCriteriaModel is gone, and it's no longer possible to add parameters (i.e. id()) or call other methods that you'd otherwise be able to call on that object (i.e. .first()).

On the other hand – like you say in your description; if you don't use .find() (keeping the ElementCriteriaModel around) you'll hit the database every time you use the .id() method.

A workaround could be to loop over the categories and add them to an indexed array (using the category IDs as keys) and then pull your individual categories from that index instead of the original array.

Important: One gotcha to note is that the |merge filter will actually renumber numeric keys, so you have to add an arbitrary character to the ID to retain the actual ID values (the example below uses an underscore prefix):

{# Get the categories #}
{% set categories = craft.categories.group('products').limit(null).find() %}

{# Create category index #}
{% set categoryIndex = {} %}
{% for category in categories %}
    {% set categoryIndex = categoryIndex|merge({('_'~category.id): category}) %}
{% endfor %}

{# Do your thing #}

{{ categoryIndex['_102'].title|raw }}

{{ categoryIndex['_126'].title|raw }}

Note that when you want to pull a category from the index, categoryIndex['_102'] and categoryIndex._102 will both work – I just find that the former looks a bit cleaner, with the underscore in front of it (obviously you can use any character, it doesn't have to be an underscore).

Edit

As pointed out by @carlcs in the comments below, another approach to creating the index is to use the group filter. With this approach you'll avoid the underscore hack and the for loop. The gotcha here is that this filter will actually create an array of arrays, meaning you'll have to use categoryIndex[102][0] (note the [0] at the end) to access a specific category (you could also use categoryIndex[102]|first, of course):

{% set categories = craft.categories.group('products').limit(null).find() %}
{% set categoryIndex = categories|group('id') %}

{{ categoryIndex[102][0].title|raw }}

{{ categoryIndex[126][0].title|raw }}


There's an example of this in the Twig documentation: https://twig.symfony.com/doc/3.x/tags/for.html#iterating-over-keys-and-values

In your example, it would be:

{% for key, value in hash %}
    {{ value }}
{% endfor %}


Any cloud providers hosting and securing Craft as a service

I'm not aware of any PaaS service that also keeps Craft up-to-date for you automatically.

There are some like Fortrabbit, that are PaaS and are very familiar with Craft installs, but you'd still be on the hook for updating Craft.

There are some more traditional, managed, non-PaaS hosts like ArcusTech that are also very familiar with Craft installs, and they keep the OS configured and secured for you are responsible for installing and updating Craft as well.

There is some more discussions about hosting options for Craft here:
Recommended hosting company for a Craft site?


Fixed order with limited set, then resume normal order

Isn't news/test-article just an example of news/{slug}? And is this for a plugin (hence the PHP) or a template (hence the templating tag for your question)?

Perhaps what you want to do is start by grabbing the slug from the URL and getting the entry you're after:

{% set entry = craft.entries.section('news').slug(craft.request.lastSegment).first %}
// output

Use that to display the first entry, then get the rest of the news entries but filter out the active:

{% set otherEntries = craft.entries.section('news').id('not ' ~ entry.id) %}
{% for otherEntry in otherEntries %}
    // output
{% endfor %}


Since it sounds like you're rolling-your-own, and can afford a relatively simple implementation, I'd recommend checking out the seq(…) Twig function that Craft provides.

{% do seq("ad-impressions-#{ad.uid}") %}

Then, if you have a dashboard of some kind for advertisers/partners, you could display those tallies by iterating over their “owned” advertisements:

{% for ad in ads %}
    {{ ad.title }} views: {{ seq("ad-impressions-#{ad.uid}", null, false) }}
{% endfor %}

Here, the third argument tells the function to read the value, but not increment it.

  Of course, this is extremely crude. It assumes you only need to count the number of times an ad is rendered into a page, and makes no guarantees about how many times it’s actually seen. It also won't increment if the page is cached.

Overall, I'd recommend outputting the ad with some kind of identifying information, and firing a custom Google Analytics event… or—time permitting—write a custom controller to ping via AJAX when an ad is actually displayed in a browser. Keep in mind that somewhere in here, you're apt to be able to deliver a better product with an existing plugin!


Help! My plugin is sending my email twice

So, this was being caused by selecting my action url from Chrome's url complete suggestions. Apparently, this submits the page twice. If the action url is typed in, pasted in or hit by my Chron job it works as expected. Firefox url suggest selection causes no problems.


How do I do routing for something like {city}/pricing, {city}/how-it-works, etc. while loading the same template and dataset?

Is the problem you're not getting the segment from the URL?

{% set locationSlugInUrl = craft.request.getSegment(1) %} or {% set locationSlugInUrl = craft.request.firstSegment %} should do that for you.

Or you're not getting the entry? In which case you need to either specify the template in that section's settings or do something like {% set entry = craft.entries.section('pricing').first %} or whatever the section slug is (assuming it's a single).

And what kind of field is entry.pricingPlans? If it is a matrix field, what type of field is plan.location?


I got it using the 'group' filter at : http://buildwithcraft.com/docs/templating/filters#group

Thanks to Steve Abraham for pointing me in the right direction. My code that seems to work is:

{% set companyHistory = craft.entries.section('about').slug('company-history').first() %}
{% set allEntriesByYear = companyHistory.children.type('history') | group('date.year') %}

{% for year, entriesInYear in allEntriesByYear %}

{{ year }}

    {% for moment in entriesInYear %}

{{ moment.title }}

    {% endfor %}
{% endfor %}

Let me know if there is an even better solution.


Changing product type for products in Craft Commerce

I personally think mucking with the schema here is bound to get you in trouble.  Very easy to miss something.

If you don't have much data in yet, simply start again, and chalk it down to learning/experience.  (Personally I think there should be a 'Start This Way' page in the Commerce docs that  emphasises Data Modelling for product types is where you should begin!).

If you do have a lot of data in, best to export & then re-import your data using e.g. FeedMe - https://sgroup.com.au/plugins/feedme/getting-started/introduction

(You will need the Pro version which support Products)


The performance aspect is difficult to answer. On every pageload, Craft pulls all your global sets, which can be a performance hit, especially if you have many huge, complex global sets with a lot of fields. Any Single used in place of a global could be pulled on a need-to-use basis, i.e. not on every page, although the extra call to the EntriesService would also come at a price. In any case, I wouldn't really worry too much about it one way or another.

As for other pros and cons – in my opinion, the pros would mainly be related to usability for your content editors.

Some people may find it easier to work with Singles because they live inside the Entries section of the CP, i.e. together with the bulk of the site's content. This is especially relevant if the global content in question is only displayed on certain pages, e.g. a tagline which is used in the homepage's header – in which case most content editors would look at the homepage single before anywhere else, I reckon.

The Expanded Singles plugin even lets you list your singles in the left sidebar, making it even easier for your editors to find them.

The most obvious con to using singles over globals would the fact that you would have to write Twig to pull the appropriate Single anytime you needed its data, whereas any global set will always be available everywhere – i.e. writing {{ settings.tagline }} is way simpler than {{ craft.entries.section('mySettingsSingle')|length ? craft.entries.section('mySettingsSingle').first.tagline }} or the like – unless, of course, you add the Single(s) to the global Twig context or implement a template variable, but that would require writing a custom plugin.

Also, there's no way to turn off URLs for singles – so any single you create in place of a global, you're going to have a "stray" URL in your system. Not a huge issue, but still.

Personally, I believe that opting for a Global Set is generally the Right Thing To Do if the content doesn't really have a place in any existing Single – rather than creating what is essentially "bucket" or container Singles to accommodate it. If your content editors find Globals hard to use/find, consider using the CP Nav plugin to rename the "Globals" tab in the CP to something a little less technical – e.g. "Settings" or "Misc. content". Using CP Nav, you can even add tabs for specific Global Sets, with your own titles – in your case I'd consider creating a set called "Listing settings", adding the fields for the header image and introductory text to that set, and finally creating a tab in CP Nav called "Listings" or the like (or even "Wine Listing" if you want to get really specific), pointing to that particular Global Set. Personally, I think Globals – if done right – is actually better for usability than Singles pretending to be something they're not.


What's the function of the Stalled Tasks menu option?

What is the function of the Stalled Tasks menu option?

To let you know there is currently a stalled task, to show all of the subsequent tasks that stalled task is blocking and in some scenarios, give you a chance to restart the task.

  What is it supposed to do when clicking on it?

Show a modal with the stalled task and (potentially) other tasks that it is blocking.

  Is it normal for it to be there... all the time?

Nope. The underlying reason that task stalled should be debugged and fixed. https://craftcms.com/support/stuck-tasks

  Is it normal for the browser to freeze when I click on it?

Nope.


Using elementSelect for third-party elements

If you are referring to a custom field to select products, one already exists:

If you are building a general attribute field for a plugin, taking a look at the B BaseElementFieldType.php within the craft/app filder (that the product field above extends) will give you clues on how to recreate the UI to select products (or any other element).

The key file being craft/app/templates/_includes/forms/elementSelect.html which will show you how to instantiate the Craft.BaseElementSelectInput js class.

Hope that points you in the right direction. I am not sure if there is a full guide out there on how to useCraft.BaseElementSelectInput js, but hopefully the above will get you most of the way there by looking at the code.


Best Practice on how to build a Pricing Page on CraftCMS

I've done something similar to this recently, and I went through the same though process as you've done!
I initially added a new Channel for plans, and built each plan as an entry in that channel. These were then selected in an Entries field for the pricing page entry. However, after building this solution locally, I felt like it was overkill for my particular use case.
In the end, I asked myself 'Will I need to reuse any of the data that's shown for each pricing plan anywhere else?' and the answer was 'no'. I removed the plans channel and ended up using a Super Table field in my pricing page entry type, with fields for the plan details inside the Super Table.
This was specific to my use case though, where I knew I wouldn't need to surface the plan data on any other pages. If you do need to reuse plan data elsewhere - and you probably will - then I'd stick with my original solution of defining the plans in a Channel as entries that can then be selected in an Entries field in your pricing page entry type. This way, the data for each plan is held in a single place and you get all the standard entry functionality (like draft entries, date expiry etc.) for your plans, which can be helpful.


How could I make related entries load faster?

You could use a template hook to eager load the related data from a plugin and cache the results for future requests.


Can access admin page (now), but not any site pages...yii not found http execption

I am presuming Craft 3 because of composer, but you didn't say.

To start with look in your craft templates folder. I would suggest that you simply don't have the template that Craft is looking for.

If you visit the root of your site this is normally templates/index.twig make sure this is present and has no further includes in it (just until you get it working)

Also try looking in storage/logs/web.log for errors.


Yes, you can totally do this with categories, but then you have to assign a city category to each entry manually. Another idea would be to use a structure section for all of your entries, with top level entries being entries for the cities and child entries for the stories (you can make use of different entry types).

Your cities index page to promt the user for their preferred city would list the categories or the top level entries of your structure. Use a conditional in this page's template that retrieves a cookie and does the redirect in case. To set a cookie you'd need to make a custom plugin or make use of Lewis Jenkins' "LJ-Cookies plugin".

For your per-city stories index page you would make your new-york/ template list the city specific stories by adding the category relation / the city parent entry as a criteria to the ElementCriteriaModel.

If you choose to use categories, see here how to set up a category template (tick "Categories in this group have their own URLs"). Additionally you probably want to make your categories field required (so that you have to select a city) and set the limit to 1 (max. allowed cities) in the field settings.

For the structure solution you may want to read through this article in the docs, to learn how to give entry types individual templates.


Retrieve entry data from an Entries field in a Matrix Block

You’re off to a great start here, in the way that you are first assembling the $menuBlocks array, and then finally returning the main array with the title and menu keys. For the section items, you just need to take the exact same approach:

'transformer' => function(EntryModel $entry) {
  // Note: you should also make sure you define the $menuBlocks
  // array, to avoid a PHP error in case there are 0 blocks.
  $menuBlocks = [];

  foreach ($entry->menu as $block) {
    // Now start by defining an $items array:
    $items = [];

    // And loop through your sectionItems field just like
    // you are doing with the menu field.
    // (Note - you can’t name the individual item entries "$entry",
    // because that would override the other $entry variable.)
    foreach ($block->sectionItems as $itemEntry) {
      $items[] = [
        'title' => $itemEntry->title,
        // ...
      ];
    }

    $menuBlocks[] = [
      'id' => $block->id,
      'menu_id' => $block->fieldId,
      'name' => $block->sectionName,
      'description' => $block->sectionDescription,

      // Now insert that whole $items array here:
      'items' => $items,
    ];
  }

  return [
    'title' => $entry->title,
    'menu' => [
      'sections' => $menuBlocks
    ]
  ];
},


How do I get a random entry's URL from a Entries field?

It is possible to have the query pick a random entry.
From the Craft Entries Fields docs we see that entry.entriesFieldHandle is a shortcut for

craft.entries({
  relatedTo: { sourceElement: entry, field: "entriesFieldHandle" },
  order: "sortOrder",
  limit: null
})

And what we want is to order the entries randomly, and then limit the number we retrieve to only one:

craft.entries({
  relatedTo: { sourceElement: entry, field: "entriesFieldHandle" },
  order: "RAND()",
  limit: 1
})

So to retrieve one random entry and get its url:

{% set randomEntry = craft.entries({
      relatedTo: { sourceElement: entry, field: "entriesFieldHandle" },
      order: "RAND()",
      limit: 1
    }).first()
%}
{% if randomEntry %}
  {% set randomUrl = randomEntry.url %}
{% endif %}


Craft 3 knows about available plugins via the vendor/craftcms/plugins.php file, which stores info about all Composer packages that were installed with type: craft-plugin in composer.json.

If that file doesn’t exist or is just returning an empty array, then make sure that the craftcms/plugin-installer Composer package is installed, and try re-requiring each of your Craft plugins. As they are (re-)installed, they should get added to plugins.php.


Craft 3 front end form file uploads not saving if filename exists?

That's a bug. The Asset wasn't saved because it would not be validated due to conflicting filenames. Thankfully, it's fixed now.


What you could try is putting the "if statement" as a condition in the for loop like this:

{% for premiereItem in entry.kompositonsart if premiereItem.value == 'ua' %} //the checkbox loop starts
    // only return checked value with 'ua'
    {{ countPremiere }}
{% endfor %}

I'm not really sure what you are asking but if my thoughts are right this should do the trick. This way it wont effect any other regular loop functions like a loop.index if you are going to use it.


Front End Form with Dropdown in Matrix - Adding New

Your Code has two errors:
1.  was missing.
2. The way you were fetching options was wrong.

Here is the correct code:

<input type="hidden" name="fields[emergencyContact]" value="">
<input type="hidden" name="fields[emergencyContact][new1][type]" value="contact">
<input type="hidden" name="fields[emergencyContact][new1][enabled]" value="1">

    <fieldset class="cell small-3">
        Name<input type="text" name="fields[emergencyContact][new1][fields][contactName]">
    </fieldset>
    <fieldset class="cell small-3">
        Relationship
        {% set matrixField = craft.fields.getFieldByHandle('emergencyContact') %}
        {% set blockTypes = matrixField.getFieldType.getSettings.getBlockTypes %}
            {% for blockType in blockTypes %}
                {% if blockType.handle == "contact" %}
                     {% for field in blockType.getFields() %}
                       {% if field.handle == "contactRelationship" %}
                          <select>
                          {% for option in field.settings.options %}
                             <option value="{{ option.value }}">{{ option.label }}</option>
                           {% endfor %}
                           </select>
                        {% endif %}
                      {% endfor %}
                 {% endif %}
              {% endfor %}
    </fieldset>
    <fieldset class="cell small-3">
        Phone<input type="text" name="fields[emergencyContact][new1][fields][contactPhone]">
    </fieldset>
    <fieldset class="cell small-3">
        Email<input type="email" name="fields[emergencyContact][new1][fields][contactEmail]">
    </fieldset>

I hope it helps you.


The category field returns an ElementCriteriaModel, which means you can use all the methods that you'd usually use to get a specific category on it.

For instance, if the category field is named entryCategories, and you know the slug of the category you want to test for, you could do:

{% if entry.entryCategories.slug('my-category-slug').total() %}
    Do something
{% endif %}

Or you could use the idthe same way.

Please note, this does not work if the entryCategory field was eager-loaded, since entry.entryCategories would then return an array. In that case you could just loop over the array and have a check inside for loop that checks the category you're looping over is the correct one. A bit dirty, but it does the job.


How to access Craft classes within plugin?

craft() is just a wrapper for the singleton instance of the WebApp class and you can call its methods directly like you're doing with getSiteUrl().

You'll notice that getSiteUrl() actually isn't in that list of WebApp methods, though.  That's because it (along with other methods) live in AppBehavior, which is a Yii behavior and is very similar to a trait that gets it's methods "mixed-in" to the class that wants them (in this case, WebApp).

Stand-alone classes that are't attached to WebApp (craft()), like DateTime, you can instantiate like:

$dateTime = new DateTime();
$dateTime->format(...);

Or if they are static classes (like the Helpers), you can use directly like:

$lowerCaseString = StringHelper::toLowerCase('ABC');


Is it possible to change the default text for a Charge plugin checkout button

Developer of Charge here.

Yes - you absolutely can control the label generated for the checkout button.

When setting the details for the checkout option, you just need to pass a sub-array called checkout, along with the extra parameters that get passed straight down the modal js.

Specifically you'd want do some thing like this :

{% set options = {
    planAmount : 99.99,
    description : 'This is an optional description for the modal',
    checkout : {
        name: 'Company Name ltd.',
        image: 'https://s3.amazonaws.com/stripe-uploads/hSYxIZGM3U0DbmPKsJszRHm3OU3D4CtHmerchant-icon-641868-add-on-icon.png',
        label: 'Pay with Stripe Checkout'
    }
 } %}

 {{ craft.charge.setCheckoutOptions(options) }}

In that above example you can see we're passing values for name, image and label to the Checkout modal.

That'll return a button that looks something like this :

The full details of all the configuration options you can pass through to the checkout modal are detailed in the Stripe Checkout documentation. Just pass the values you want within that checkout array in the twig.

NB. We're working on updating the docs on this usage right now, and they'll be up shortly too here


unserialize(): Error at offset 0 after attempting to download and install plugin within control panel

I think what ended up working was restoring backed up composer.json and composer.lock files, deleting everything in /vendor directory, and then running composer install


You could use the getNext() and getPrev() methods on your entry like this:

{% set params = craft.entries.section('yoursection').order('postDate asc') %}

{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}
{# to access url, I use #}
{{ prevEntry.url }}
{# to access title, I use #}
{{ prevEntry.title }}

NOTE: I've shamelessly pinched this code from the answer here.

You need to setup the params variable so that it would create a list of entries which would include your current entry and the next/prev entries you expect. So include your ordering by postDate etc.


Display only entries relevant to users' country

One nice way to handle things like this is to collect the ids for all the entries you want, use those ids for the ElementCriteriaModel you need for the pagination, and then paginate.

Collect the ids (use merge to create an array of the ids):

{% set ids = [] %}

{% for entry in craft.entries.section('news') %}
  {# loop through regions  #}
  {% for region in entry.regions %}
    {# loop region's countries  #}
    {% for targetCountry in region.countries %}
      {% if targetCountry == currentUser.country %}
        {% set ids = ids | merge([entry.id]) %}
      {% endif %}
    {% endfor %}
  {% endfor %}
{% endfor %}

Get the entries for pagination:

{% set unpaginated = craft.entries({
  id: ids,
  limit: 10
}) %}

Finally, the pagination:

{% paginate unpaginated as pageInfo, pageEntries %}
...


Setting a field search variable after main entries variable changes values

This is because of the way Element queries are in Craft 3.

In Craft 2, each time you called a setter method (search() here) it would clone your ElementCriteriaModel, use that value on the clone and return the cloned object leaving the original alone.

In Craft 3, when you call a setter method, it gets set on the current element query.

So if I understood correctly, you should use clone (docs):

{% set entries = craft.entries().section('yourSection') %}
{{entries.all()|length}}

{% set hasTopic = clone(entries).search('dataTable_topic:*').all() %}
{{entries|length}} | {{ hasTopic|length }}


EVENT_REGISTER_TABLE_ATTRIBUTES not working in Craft 3

You don't need to return anything in an event. As you can see how the Event is triggert

Event::trigger(static::class, self::EVENT_REGISTER_TABLE_ATTRIBUTES, $event);

It does not expect any return value. So you don't add something by returning an array. Instead you'll have to manipulate the properties of your event

When you take a look at your RegisterElementTableAttributesEvent it contains the following property

/**
 * @var array List of registered table attributes for the element type.
 */
public $tableAttributes = [];

In order to add attributes you have to do

Event::on(
    Element::class,
    Element::EVENT_REGISTER_TABLE_ATTRIBUTES,
    function(craft\events\RegisterElementTableAttributesEvent $e) {
        $e->tableAttributes['foo'] = [
            'label' => "Foo"
        ];
});

It's the same for your SetElementTableAttributeHtmlEvent. It has the properties

// Properties
// =========================================================================

/**
 * @var array|null The table attribute associated with this event.
 */
public $attribute;

/**
 * @var string|null The HTML to represent a table attribute.
 */
public $html;

You can var_dump the $event to see the current properties to get to know which structure you have to include. Usually you would do

Event::on(
    Entry::class,
    Element::EVENT_SET_TABLE_ATTRIBUTE_HTML,
    function(craft\events\SetElementTableAttributeHtmlEvent $e) {
        if($e->attribute === 'foo'){
            $e->html = 'FOOOOO';
        }
    }
);


Unexpected token "punctuation" of value "." ("end of statement block" expected)

I see three problems here.

One of them is the - in membership-type. plandata.membership-type does not mean the membership-type field of plandata, but more something like (plandata.membership) minus (type). So you will either want to use membershipType or membership_type, or the less readable twig attribute function: attribute(plandata, 'membership-type').

The second problem is that the twig merge filter operates on arrays, and you are passing it a string. This won't work: |merge(amenity.title), this will: |merge([amenity.title])

The third problem is that the twig set assigns values to variables, and plandata.membershipType.items is not a variable. The only way (in twig) to "assign" to a field of an array is with the merge filter. So you will need something like this:

{# create your amenityTitles array #}
{% set amenityTitles = [] %}
{% for amenity in entry.availableAmenities %}
  {% set amenityTitles = amenityTitles|merge([amenity.title]) %}
{% endfor %}

{# merge those amenityTitles with membershipType (somehow preexisting) #}
{% set membershipType = membershipType | merge({items: amenityTitles})}

{# merge that membershipType with plandata #}
{% set plandata = plandata | merge({membershipType: membershipType}) %}

If you can figure out a less deeply nested structure than that plandata you will probably be happier given the limitations of twig.


Use default field type(s) within my plugin

All the default field types are exposed as template macros in /craft/app/templates/_includes/forms.html. Here's how you could easily create a DateTime input field:

{% import '_includes/forms' as forms %}

{{ forms.date( {
    id : 'myDateField',
    name : 'myDateField',
    value : myDate | default
} ) }}

Note that for the date field, value needs to be a valid DateTime object.

Other input types – such as a plain text field – are created in a similar manner:

{{ forms.text( {
    id: 'myTextField',
    name: 'myTextField',
    value : myValue | default,
    placeholder : 'My Placeholder',
} ) }}

Also note that as _includes/forms is outside the frontend templates folder, it will not be easily accessible outside the CP. If you want to include the form macros in a frontend template, see the following SE thread – I'm partial to Mike Pepper's answer, myself.


Tag to fetch URL and Title of a entry when supplied it's ID

This is all you need:

{% set linkedEntry = craft.entries.id(42).first() %}
{{ linkedEntry.title }}

If you use this in many places you can also make a macro.

{% macro linkToEntry(entryId) %}

    {# Get the entry with the selected ID #}
    {% set linkedEntry = craft.entries.id(entryId).first() %}

    {# Make sure the entry exists and output the link #}
    {% if linkedEntry %}
        {{ linkedEntry.title }}
    {% endif %}

{% endmacro %}

It's nice to have macros in a separate file and import it into your templates. I really love using macros for this kind of code snippets, very useful and DRY.

{% import "macros.html" as macros %}

{{ macros.linkToEntry(42) }}

{{ macros.linkToEntry(17) }}

{{ macros.linkToEntry(20) }}


Data cached in plugin controller via CacheService won't expire

Looks like a bug in the plugin.

The 3rd $expire parameter when calling set states:

  The number of seconds in which the cached value will expire. 0 means never expire.

But it's passing in the PHP time format notation.  I'd suggest contacting the author of the plugin.


If URL Contains x Then Do Y in Twig / Craft Template?

If the string you're looking for is part of the URI segment, then something like:

{% if (craft.request.getSegment(3) == 'mySpecialKey') %}
    <meta name="robots" content="noindex, follow">
{% endif %}

(Adjusting the 3 for whichever part of the segment it's actually in.

Or if it's part of the querystring, then use craft.request.getParam('mySpecialKey').


No plugin exists with the handle "contact-form-extensions"

Try running ./craft project-config/rebuild from your terminal.


Pass the rendered template HTML string to an external function

You would need to build a plugin that fetches the HTML string and then passes it on to cURL or whatever you choose.

For a specific solution on how to get a template HTML string with all the parameters you need check out this answer


Export static html including images, CSS, JS etc

I see 3 options, none of which warrant the creation of a plug-in:

Get Craft to output all your URLs as a simple, unformatted list. Easy enough to do this with Twig templates, right (ask if not!)? Save this as pages.txt
Install wget. Simple to do on Linux (apt-get install wget probably), if you're on a Mac you can install it using brew install wget.
wget -i pages.txt
You should now have all the pages as lovely static .html files.

Get Craft to output pages as a big .json data file. Again, easy enough to do with Twig templates.
Use a 'Static CMS' to read in this JSON and use it to build out a reproduction as a static website. Personally, I'd use Middleman or Assemble.io if I was doing this - but I guess it depends if you're more comfortable with Ruby or Node.js respectively.

Ask yourself why you're doing this? Is it performance? Security? Maybe if you get up to date with use of the {% cache %} tags you'll have a much easier time!


How to assign entries to static positions such as footer?

This sounds like a perfect use case for an Entries field in a Global.

I'd create a field called "Footer Links". At the bottom of the field settings page, expand the Advanced area and enable Manage relations on a per-site basis. This will allow you to have different links for each of your sites, if you wish.


Using Element API, how do I get the next entry?

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);


How can I set an entry title automatically, based on a related entry?

I believe this is in regards to the Title Format feature, so just to be explicit in what I'm referring to, Craft Documentation calls this a Dynamic Entry Title.

The syntax you are looking for can take two forms:

1) Long form object syntax

Just as on the front end your entry is available via the {{ entry }} variable, within your Title pattern on the back end, the current entry is available via the {{ object }} variable.

So I believe the following should work, assuming you are using the actual field names:

{{ object.eventBooking.first().title }} - {{ object.userBooking.first().username }}

You need to use the first() method here because Relations fields return an array by default. Since you need to output your content directly, you need to make sure you are accessing the title and username properties via the Model they are associated with in that array.  If your fields are required, you can safely assume that the first item will exist in the array.

2) Short hand syntax

If what you are doing is simple, Craft gives you the option to make the syntax a bit easier and omit the object variable.  So the above could also be written with single curly braces as such:

{eventBooking.first().title} - {userBooking.first().username}


Performance issues in CP with +60k articles database

Doing further research i noticed the performance impact is mainly due to sorting on the default publication date. When sorting on the title field all the performance issues are gone.


Start Matrix loop from item that contains todays day

Do you really want to start the Matrix loop from the week day offset?  Or do you just want to only start printing when that offset matches.  The former seems like a bit of a micro-optimization.

For the latter, something like this completely untested code should do it:

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

    {% for menuItem in entry.menuEntries %}

{{ menuItem.title }}

            {% set offset = false %}

            {# Matrix blocks #}
            {% for item in menuItem.weeklyMenuItems %}

                {% if item.dayOfTheWeek == now|date('l') or offset > 0 }}
                    {% set offset = loop.index0 %}

{{ item.dayOfTheWeek }} - Matched

{{ item.itemTitle }} - Matched

                {% endif %}
            {% endfor %}

            {% if offset == false %}
                {% set offset = 0 %}
            {% endif %}

            {# 2nd pass #}
            {% for item in menuItem.weeklyMenuItems|slice(0, offset) %}

{{ item.dayOfTheWeek }} - Matched

{{ item.itemTitle }} - Matched

            {% endfor %}

    {% endfor %}

{% endfor %}


That's because Craft follows the standard procedure of hashing passwords with what's called a "salt" as a security measure.

Think about it this way - if a password were hashed without a salt, every instance of the same password would result in the same hashed value.

Example:

Suppose there are two users, Foo and Bar. They both choose password123 as their password. When hashed without a salt, their passwords would look the same after hashing, which is a security flaw.

We can see this by testing it with any hash algorithm:

(I'm using md5 here for readability because it gives a shorter result - do not actually use md5 for anything secure)

password123 becomes 482c811da5d5b4bc6d497ffa98491e38, and - without using a salt - would be stored that way for every user with the password password123.

The implication here is that the system is now vulnerable to a variety of attacks, like Lookup Tables and Rainbow Tables, which depend upon every instance of a password yielding the same hash.

Enter Salts. Salts are psuedo-random strings attached to the user's password prior to being hashed and stored.

In our Foo and Bar example, that would look something like this:

Foo chooses password123. The system generates a psuedo-random "salt" of pg7n6yVBzWJbaxfF, combines them into pg7n6yVBzWJbaxfFpassword123, and then hashes that result to get d026a6847c743e23195cf37db2a66ae9. In addition, Foo's generated salt is stored in the table, so that it can be used to test login attempts.

Bar does the same, but the system generates Am6g4n0JEFdE1poH as his salt. When combined with password123 and hashed, it then yields a different result: 5e7b0bb4842ee8315105a62922c32894.

Both users have the same password, but the final hashed result now has no traceable relationship to the original password in either case. If a malicious party were to try and search for password123 by scanning the database for its hashed equivalent (in our example 482c811da5d5b4bc6d497ffa98491e3), it wouldn't find anything.

The same principle applies to resetting your password - even if you choose the same password, that new instance of the password is re-salted, re-hashed, and stored as something distinct.


Licensing a multi-lingual site using different domains

I got the official answer from Brandon, here is the summary for anyone that might be in a similar situation:

I can do what I need with only one pro license

the main portal (acme.com) will run the "en" locale
additional domains will use different locales (en-uk for UK, etc.)
this will work even better in Craft 3.0 - there will be a support for "portal" and separate locales
each domain can have its own URL, templates and content
I will need to access all administration from a single domain (content editors in another country will have to use acme.com for editing their acmelocal.co.uk)

I will develop on a separate domain first (acme.com is currently live with old site), but I can transfer the license easily to acme.com when site is finished.

I can use any local domain for development with this license - more detail here.

Thanks, Brandon!


Can you remove the `translatable` option to a matrix field without losing locale content?

This isn't a direct answer but one possible path if an easier option doesn't surface.

Sprout Import supports importing content into a Matrix field and multiple imports can be created to handle multiple locales while still matching things back to the parent entry.

Example of importing content to a Matrix field
Example of importing content for multiple locales
Example of how to generate a JSON Import file in your Craft templates. While this example uses fake data, you could update the loop to output the content you need to re-import.

It's likely you'll have a handful of relationships in your content that you'll need to make sure resolve correctly as well if you re-import your content, so depending on how your content is set up there may be a few more tricky parts to work through. But this is one possible path if other options seem like the may require a lot of manual steps.

Be sure to test this in a development environment and make the appropriate backups before modifying any live content.


How to display a featured image in the list of entries

{% for element in elements %}
    {% set asset = element.assetFieldHandle.one() %}
    {% if asset is not null %}
        <img src="{{ asset.getUrl()">
    {% endif %}
{% endfor %}

Take a look at ElementQueries and how to handle errors


How to browse uploaded assets on the front end?

For Craft 3, there is UploadIt, a  front end asset uploader.


FreeForm: Adding attributes to the honeypot field

It looks like this isn't something that's currently possible. The code that generated the honeypot field isn't able to be extended vendor/solspace/craft-freeform/src/Services/HoneypotService.php::240

I ended up doing some js magic, like this:

if(this.formHoneypotName) {
    let stickyFingers = form.target.querySelector('#' + this.formHoneypotName)
    params.append(this.formHoneypotName, stickyFingers.value ? stickyFingers.value : '')
}


How to disable the Javascript "actions/queue/run" on frontend?

If you set runQueueAutomatically to false in your config/general.php file, that will disable that behavior.