texts: How do I differentiate between entries after merging an array?

texts:
I'm trying to plot entries from two different Solspace Calendars and an Entries section on one map, and use different markers for all types. Alll of the events are related to the current Entry through a field set on the Event, and a field set on the Entry. I have:

E Waste - Solspace Calendar
Community Events - Solspace Calendar
Disposal Sites - Craft Entry

All three of those above have address fields, and I'll be plotting them on a Smart Map. Currently, I'm doing this:

{# Get all eWaste events related to material #}
{% set eWaste = craft.calendar.events({
calendar: 'eWaste',
    relatedTo: [ 'or', { targetElement: entry.materialCategory }, { targetElement: entry } ],
    rangeStart: now|date('Y-m-d'),
    rangeEnd: now|date_modify('+3 months')
}) %}

{# Get related sites #}
{% set sites = craft.entries.section('sites').relatedTo([ 'or', { targetElement: entry.materialCategory }, { targetElement: entry }]) %}

{# Merge events and entries #}
{% set locations = eWaste|merge( sites ) %}

{{ craft.smartMap.map(locations, options) }}

That gets events from one calendar, and the entries in to a single array so I can plot them on one map, but I can't work out how to differentiate between the types in order to give them different markers. As an example, entry.type doesn't work, and neither does {% if entry.eventField is defined %}

Am I going about this the wrong way? How do I achieve what I'm after? Will the above approach also work for two different calendars + entries?


texts: Is there some way to create sections inside static translations? (craft v3)

texts:
At the moment I'm converting a website from a different CMS to Craft v3. The 'old' CMS had a convenient way to set a hierarchy for static translations in yaml files so that we could split translations into groups per section on the website.

Like this:

  PageNavigation:
    PrevPage: 'Previous'
    NextPage: 'Next'
    GotoPrevPage: "Goto previous page: '{prevPageTitle}'"

Now I can't find anything like that on the documentation and google search on Craft CMS. At the moment this is what I got instead:

<?php

return array(
    'PageNavigation.PrevPage' => 'Previous',
    'PageNavigation.NextPage'=> 'Next'
    'PageNavigation.GotoPrevPage' => "Goto previous page: '{prevPageTitle}'"
);

So every translation-item has a group supplied to it as a prefix, followed by a dot and then the translation-itemID. But this gets ugly soon and is not as convinient as what I was used to in the other CMS.

1)
Does anybody here perhaps knows if CraftCMS has a better way of setting hierarchy to static translations? So to group translation items to sections/elements on the website?

2)
Is there a way in Craft CMS to have a placeholder inside the translation-string being replaced by a variable inside the template?

In the 'old' CMS I could replace a placeholder like {placeholder} inside a translation-string by a dynamic variable inside the template. So a translation string like "Goto previous page: '{prevPageTitle}'" would come out as "Goto previous page: 'all about craft blog title'". Is there some functionality build in Craft that could replace a placeholder in the translation-string by a dynamic string?

Thanks in advance!!


texts:
I have a plugin that does a little work after a user has been saved in the CP based on the user groups they are in.

The $event->params['user'] object seems to be partially up to date when the event is handled. The username and general info is the recently entered values, however the groups is not current, it is always what is was before


texts: How can I upload multiple new entries into Craft 3?

texts:
I want to create a few dozen new entries from an Excel or .csv import.  Does this capability exist in Craft 3?  There was a plugin for Craft 2.  But, I need to prepare for the switch to Craft 3 and this is a critical (time-sensitive) need.

Alternatively, is there another way to import a large number of new entries (using another file format, etc.)???

Thanks


texts: Populating Matrix Blocks with JavaScript

texts:
I need to populate a matrix block field with JavaScript in the control panel. I've got the data ready, but i can't figure out how to add it.
I've located a function called addBlock() in MatrixInput.js but I can not figure out how to call it from my JS code. I've explored both the global Craft and Garnish - without finding the function. I could recreate the entire html of the element, but that seems unnecessary when there are helper functions that I could reach for.
Looks like craft is creating one var for each block available on the page with the following code:
var matrixInput = new Craft.MatrixInput("...")
var matrixInput = new Craft.MatrixInput("...")

It would also be great to have the arguments that needs to be passed to the function - is there any documentation or anyone who struggled with this previously that can point me in the right direction?


texts:
I have a Structure Section, with the following settings:

Entries in this section have their own URLs = Checked
Entry URL Format = recommendations/{slug} & {parent.uri}/{slug}
Max Levels = 2

This worked for the first few entries (both Parent and Child) I created but after saving and returning to the Structure page (from Entries), the entries are no longer nested and the 'move' icon is missing. And, 'Create a new child entry' is created but also not nested when created.

Another Structure Section I have set up is working correctly.

I've tried clearing both browser and Craft cache. Not sure else what to try.

Craft CMS 2.6.2949


texts: Licence error and update issue cause of same plugin name / handle

texts:
We developed a plugin with the name "poll" (composer.json: webhub/poll) for one single project. Now we get the licence error in the control panel, cause there is a plugin to buy which has got the same name (https://plugins.craftcms.com/poll).
First Problem: ./craft update all wants to update our plugin: poll 0.0.1 => 1.2.5 but we really do not have a version 1.2.5.
Second Problem: at the control panel plugins page, we have our plugin listed, but with an licence-code-input-field and the error message, that we don't have a licence.
The Reason for all of this is, that we picked the wrong name for our plugin, but renaming it is a pretty dirty task. Does anyone has a got a better idea?
The composer.json looks like this:
{
  "require": {
    "aws/aws-php-sns-message-validator": "^1.6",
    "carlcs/craft-redactorcustomstyles": "3.0.4",
    "cavellblood/craft-string-base64": "1.0.1",
    "codemonauts/craft-instagram-feed": "1.0.5",
    "craftcms/cms": "3.5.3",
    "craftcms/redactor": "2.7.0",
    "doublesecretagency/craft-matrixcolors": "2.0.1",
    "ether/seo": "3.6.6",
    "hybridinteractive/craft-position-fieldtype": "1.0.16",
    "meyfa/php-svg": "^0.9.0",
    "mildlygeeky/craft-redactor-script-buttons": "1.1.1",
    "mmikkel/cp-field-inspect": "1.2.0",
    "percipioglobal/craft-colour-swatches": "^1.2",
    "studioespresso/craft-dumper": "2.0.0",
    "topshelfcraft/environment-label": "3.2.0",
    "verbb/expanded-singles": "1.1.3",
    "verbb/super-table": "2.6.0.4",
    "vlucas/phpdotenv": "^2.4.0",
    "webhub/poll": "0.0.1",
    "webhub/super-sticker-generator": "^0.0.1"
  },
  "autoload": {
    "psr-4": {
      "modules\\laravelmixmodule\\": "modules/laravelmixmodule/src/"
    }
  },
  "config": {
    "sort-packages": true,
    "optimize-autoloader": true,
    "platform": {
      "php": "7.0"
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ]
  },
  "repositories": [
    {
      "type": "path",
      "url": "./plugins/*"
    }
  ],
  "require-dev": {
    "codeception/codeception": "^3.1"
  }
}


texts: Grabing data from another channel associated to an entry displayed using category

texts:
I have a page that shows a listing of entries (called products) by category. Those product entries have related content (reviews) stored in another channel that are tagged using a relations field.

On the category page, I want to show the overall rating (the sum of all ratings)for each individual product shown.

I'm calculating and showing the overall rating currently on the product profile page with no problems. But on the category page, I'm having trouble showing that overall rating also. I think my problem is where I'm using the relatedto field (in my queryParams variable) to associate the reviews to the product entry associated with the category.

Any help is appreciated.

<!-- get category from URL -->
{% set category = craft.categories.group('productCategories').slug(craft.request.lastSegment).one %}

<!-- display craft product entries related to category-->

{% set entries = craft.entries.relatedTo(category)
    .limit(30)
    .orderBy ('dateCreated desc')
    .all() %}

<!-- set variable to grab the associated reviews -->

    {% set queryParams = {
        section: 'userProductReviews',
        relatedTo: 'entry'
    } %}

{% set reviewQuery = craft.entries(queryParams).all() %}

<!-- overall rating code -->

{# set sum of product ratings per entry#}

    {% set sumOverallratings = 0 %}

    {% for entry in reviewQuery %}
        {% set sumOverallratings = sumOverallratings + entry.overallRating %}
    {% endfor %}

{# the actual number of reviews related to product entry #}

  {% set reviewCount =  craft.entries(queryParams).total() %}

{# set the average for the rating #}

    {% set productOverallAverage = sumOverallratings / reviewCount %}


texts: Specify which template/layout to use based on URI segment

texts:
I have 3 level structure for my entries with separate template for each level.

/artists/artist-name/ uses artists/_types/artists.html template

/artists/artist-name/section-name/ uses artists/_types/section.html template

/artists/artist-name/section-name/project-name/ uses artists/_types/project.html template

What I need to do is to specify additional layout for level 3 entry so depending on URI I can display one or another.

This is the additional URI I want to use:
/artists/artist-name/section-name/project-name/thumb and I want to load the artists/_types/thumb.html template


texts:
I need to set an asset field's dynamic subfolder path to the User ID.

The field is within a matrix.

The matrix a field in a User profile.

Setting it to {currentUser.id}, {owner.author.id}, {object.author.id} results in an invalid path message when trying to upload to the asset field.


texts: Check if the first block in a Matrix field matches one of an array of types

texts:
I need to check if the first block in a Matrix field matches one of an array of types. Here's a simplified version of my code:

{% if entry.newsArticleContent.one().type in ['fullWidthImage', 'imageGroup'] %}
    yep
{% else %}
    nope
{% endif %}

{{ entry.newsArticleContent.one().type }} outputs fullWidthImage, but the above conditional outputs nope.

The following outputs yep:

{% if 'fullWidthImage' in ['fullWidthImage', 'imageGroup'] %}
    yep
{% else %}
    nope
{% endif %}

so I know it's not a problem with the if statement or the fact that I'm checking the value against an array.

Is there a reason why the value of entry.newsArticleContent.one().type can't be used in this context?

Thanks!

EDIT: Thought I should mention that I'm looping through all blocks in the Matrix field later on in the same template. Just in case that's relevant.


texts: How can you crop an image and output from a Matrix field?

texts:
Trying to output a matrix field image so that it crops the thumbnail. However, I can't seem to get it to work.

Here's what I have:

{% for block in entry.servicesItems.type('images') %}

        {% if block.image|length %}

            {% set thumb = {
                mode: 'crop',
                width: 229,
                height: 172,
                quality: 75,
                position: 'center-center'
            } %}

{{ block.imageTitle }}

{{ block.imageContent }}

        {% endif %}

{% endfor %}


texts: I am unable to successfully submit guest entries

texts:
I am trying to submit a guest entry it keeps returning a fatal error. This is my code

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

Title
<input id="title" type="text" name="title">

Body
<textarea id="body" name="fields[body]"></textarea>

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


texts: Craft 3 Image doesn't change after save when editing from matrix

texts:
when I edit an image in the image matrix block and save the asset, the changes doesn't affect the image thumbnail preview. The thumbnail preview changes only If I save the page.

Video of the issue.

Craft version: 3.1.24

Thanks for the help.


texts: Setting a variable assets field, depending on the URL?

texts:
How can I set different assets fields depending on the URL?

I tried:

{% if craft.request.getSegment(1) == 'special' %}
   {% set assetfield = variantfield1 %}
{% endif %}

{% for asset in entry.assetfield %}
     ...
{% endfor %}

But that doen't change entry.assetfield?


texts:
We have some content that needs to display a log of changes (legal docs, terms etc)

Could I use version history for this?

I found this for Craft 2 but doesn't work on 3...

How can I display entry edit history on the front end?


texts: Add new error to macro errorList - User Registration

texts:
Using CraftCMS example registration form in the docs.

How would I add a new error message to the macro errorList in the registration form:

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

                {% for error in errors %}
                    <span>{{ error }}</span>
                {% endfor %}

        {% endif %}
    {% endmacro %}

    {# Output if true #}

    {% if user is defined %}
        {{ _self.errorList(user.getErrors('email')) }}
    {% endif %}

I added a checkbox and need to create a validation for it. I can create an error like this: Craft::$app->getSession()->setError(Craft::t('app', 'Check box is not checked')); which works, but how will I add an error to the macro errorList so I can use it the same as the other errors eg, firstname, password, etc.

CraftCMS: 3.4.6.1


texts: How to include external JavaScript in place?

texts:
We include an external script from a vendor and the URL doesn't end in .js. It returns JavaScript that creates a widget in place. I was able to fake it out by adding a '&js=.js' parameter but it still rendered with the other scripts.
Is there an option for {% js %} to render in place? A {% js at right-here %}?


texts:
we are currently working on a website with an event calendar on it. The events should be filterable by categories and dates of course. Some of these events are repeated on another date. Now we are looking for a strategy to add the same event on another day without duplicating the entry and just modifying it's date. Is there a way to add an entry with it's own date but it inherits the contents and relations of another entry? These "virtual" entries should behave like "real" entries, so if the calendar is being filtered by the category "concerts" for example, all entries/virtual entries related to "concerts" should be listed. Any hint on that matter?

Thanks for your support!


texts: How can I make an oversized chalkboard organiser?

texts:
I found this ( http://www.pbteen.com/products/oversized-chalkboard-organization/ ) on PB Teens and Pinterest and fell in love. It's perfect for me but at a price of around £200 is a bit ridiculous! Anybody got any ideas on how I might DIY this?

Thanks in advance :)


texts: What will happen if we change the field type in the fields (settings -> fields) in Craft 3?

texts: I am a beginner in Craft CMS. I just want to know, what will happen if we change the field type in the fields (settings -> fields) in Craft 3?


texts:
So Right now I am working on https://munisense.com/sound, and since a week or so the Image Transform functionality seems to be working in another way (ever since the last mandatory update).
The strangest part is that in my local/offline version of the website, the paths to the transformed images are working correctly. But online, the image paths point to the fullsized versions.
For examples, take a look at the 'services' paragraph, each of those three images isn't scaled down by Craft. Right now I solved the problem temporarily with some CSS rules, giving the images a fixed width. Just turn them off to see what it looked like when I checked it out this morning.

The syntax I am using is the following:

{% for image in services_info.image %}

{% endfor %}

But this syntax hasn't changed for a long while now, so I think the problem is somewhere else. Also because locally the correct paths are working.

So how can it be that Craft is not applying the paths of the resized versions of my images? Where do I need to look instead to fix this?


texts:
Any recommendations as to whether it is better to use Apache or Nginx for a Craft website?

If the answer is "it depends", could you please delineate some of the advantages and disadvantages of each option?


texts:
Background & Problem

I've taken over our company website which was created using Craft. I've never worked with Craft and I'm beginning to like it, but the higher-ups want it done ASAP and I'm struggling understanding some things.

I've been tasked to add a page for our clients (AKA Client Portal). Each one of these pages will look and feel exactly the same with the exception of three areas (Discovery, Website, Assets) where the project manager will need to add tasks. These tasks will be a brief description and will be a link to some outside page (Dropbox or something else...).

Progress

I've created a Channel and called it Client Portal which works great! I can create a portal for each client and so far so good. The problem is I need to add these sections (not sure the proper Craft term) where they can add a Discovery task, Website task, Assets task. These are unique to the client, but will be styled exactly the same, but the content (text) will be different for each task/card. I'm not sure where to start with these sections (or whatever Craft calls them).

Can someone point me in the right direction on how I would create these sections?

I've created a JSFIDDLE to give someone a visual on what I'm trying to achieve.

https://jsfiddle.net/9goqgabp/


texts:
I try to implement a User Registration Form with Sprout Forms for hours, but it doesn't work ...

I have replaced the value for the action from "sproutForms/entries/saveEntry" to "users/saveUser".

How should I create the fields (username, password, email, first name, last name), that the user are stored.

In a further step, I will add custom fields for the users.


texts: Questions about Craft 4 release and licenses

texts:
Being busy rethinking an existing website to rebuild in Craft I just found out Craft 4 was announced september last year. Some of the new features, like nestable Matrix fields in particular, are very welcome and chances are I'd rather wait for Craft 4 to come out to convert a big amount of data to the new CMS than to rebuild the website in Craft 3 to have another data-migration(/rebuild?) for new fields etc. in Craft 4 later.

So I'm having the following questions:

1) Is there anything to say about a release date for Craft 4? And about around what time Pixel and Tonic consider it a stable release to be used in production?

2) What will happen to the support and updates for Craft 3 once Craft 4 is out? Is there any roadmap showing support/update-cycles for Pixel and Tonic products?

3) Will Craft 3 work with the announced Craft Cloud or will the cloud only work from version 4 up?

4) Is there anything to say about how difficult it will likely be to migrate from v3 to v4 and what that would be about?

5) What about existing paid licenses when a customer upgrades from version 3 to 4? Is it under the same license after the upgrade? Or are licenses bound to a major version and need a customer buy a new license for version 4?

Thanks in advance!


texts: Cache not invalidated on publishing new entry

texts:
I'm using {% cache %} to cache pages, but it seems that the caches are not invalidated after posting new content, which is what I thought should happen.

I've investigated the situation and what I think is happening is this:

Post a new entry
Caches are then deleted (this process takes a looong time: I noticed that templatecacheelements table was up to something like 450,000 rows)
The page in question is accessed by a visitor while the cache is being invalidated, and so the template is cached again before it has been purged

Because Craft doesn't know about the access to the template during emptying of the caches, I suppose it never will until the cache is purged manually.

Is there anything I can do to improve this situation?


texts: How can I use    within a redactor/rich-text field?

texts: We need to be able to add super and sub-text to a rich text field without having the client dive into the markup. Has anyone successfully added this as a redactor or Craft plugin?


texts: Responsive Images Srcset and Sizes based on Image Transform

texts:
So I have setup a macro based on the excellent article here;
https://straightupcraft.com/articles/responsive-images-with-twig-macros

{% macro responsive(asset, options={}) %}
{% import _self as self %}

{% set options = {
    alt: '',
    class: [],
    style: 'default'
}| merge(options) %}

    {% set transform = {
        mode: 'crop',
    } %}

{% set nativeWidth = asset.getWidth(false) %}

{% set config = {
    default: {
        srcsetWidths: [300, 600, 1000,],
        sizes: [
            '(max-width: 47.5em) 100vw',
            '50vw'
        ],
        defaultWidth: 600
    },

    cards: {
        srcsetWidths:   [345, 600, 700, 905, 1000, 1200, 1400],
        sizes: [
            '(max-width: 47.5em) 100vw',
            '(max-width: 60em) 50vw',
            '33vw'
        ],
        defaultWidth: 600
    }
} %}

{% set params = config[options.style] %}
{% set srcset = [asset.getUrl(false)~' '~nativeWidth~'w'] %}

{% for width in params['srcsetWidths'] %}
    {% if width < nativeWidth %}
    {% set srcset
         = srcset|merge([asset.getUrl(transform|merge({width: width}))~' '~width~'w'])
    %}
    {% endif %}
{% endfor %}

<img
    {# src attr: transformed only if necessary #}
    {% if nativeWidth <= params['defaultWidth'] %}
      src="{{ asset.getUrl(false) }}"
    {% else %}
      src="{{ asset.getUrl(transform|merge({width: params['defaultWidth']})) }}"
    {% endif %}

    srcset="{{ srcset|join(', ') }}"
    sizes="{{ params['sizes']|join(', ') }}"

    alt="{{options.alt}}"
    {{ self._classAttr(options.class) }}
/>
{% endmacro %}

However, I want to be able to generate each individual responsive set based on different transform parameters. The first instance I have is created a series of card images images for a 1x3 row of feature cards. These will be a fixed ratio which I want the system to handle and not the user. These cards have the following sizes for each srcset width;

1400 x 875
1200 x 750
1000 x 625
905 x 566
700 x 438
600 x 375
345 x 216

I have created an image transform in the Control Panel called Card Image that has been set to crop and the width/height set to the largest size (1400x875). I wondered if I could use this handle in the macro, but I run into errors;

  The merge filter only works with arrays or "Traversable", got "string" as first argument.

As I will have different use cases and create different 'responsive images' throughout the site, I want the flexibility of setting up different transforms, I thought it was perhaps sensible to keep these all in the control panel under the Image Transforms section, as these are easily referable and editable. Then pass in the required handle into the Macro.

Does anyone have a better approach or solution, and any ideas how I can overcome the error mentioned?

Thanks.


texts: Site url is not generated correctly when using environment variables

texts:
I'm working on a multi-site setup (for a localized website). In my .env file, I have defined a SITE_BASE_URL variable. Then, in the control panel, I set up each site's base url with that environment variable (e.g. http://$SITE_BASE_URL/en, http://$SITE_BASE_URL/nl, etc. for each language).
However, when I need to generate urls in my Twig templates, this environment variable doesn't seem to get parsed; I get generated html that looks like this ....
Example from a twig template:
{% set pages = [
    craft.entries.section("services").one(),
    craft.entries.section("products").one(),
] %}

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

This gives me URLs like http://$SITE_BASE_URL/en/services, http://$SITE_BASE_URL/en/products, etc.
This setup was working fine for me when using the @web alias in the CP. Why doesn't it work with the env variable? The only reason I switched to env variables is that it is not recommended to use the @web alias due to cache poisoning.
I've already looked at https://github.com/craftcms/cms/issues/3719 and baseUrl outputs environment variable
Neither have solved my issue...


texts: Multilingual blog, but only for some entries in a section, otherwise default to English

texts:
My client has an English blog but wants a few of the posts to be available in German too.

How would I set things up so that the German version of the blog shows the German version of a post where available, but otherwise defaults to the English version?

(If “Propagate entries across all enabled sites?” is turned off, the German blog is effectively empty and they don't want to copy/paste all the old posts over from English to German if it can be avoided)

URLS are using a /en or /de prefix.


texts:
I'm trying to create a form that adds a cookie so that someone who has submitted the form can see content on the thank you page to protect the download.
Currently I've got this:
{{ craft.freeform.form('handle').render() }}

{% set formcook = craft.freeform.form('handle') %}

{% if formcook and formcook.submittedSuccessfully %}
   {# Cookie Will go here #}
{% endif %}

This doesn't seem to be working, although I've seen something very similar working on a different project.
Freeforms has very little in their documentation regarding this unless I'm missing something very obvious.
Anyone spot where I've gone wrong?


texts:
I want to move some permanent routes from the admin to my routes config file so that they can be version controlled.

in the admin...
news-sort/month/<year>/<month> ....
news-sort/tag/<tag> ....
news-sort/author/<*>

Do these look ok, not 100% sure on the variable and regex etc.

'news-sort/month/(?P<year>\d{4})/(?P<month>\d{2})' => 'news-sort/index',
'news-sort/tag/(?P<tag>[a-zA-Z0-9._%-]+)' => 'news-sort/index',
'news-sort/author/(?P<author>[a-zA-Z0-9._%-]+)' => 'news-sort/index'


texts: Running plugin migrations when other plugin is installed?

texts:
I'm creating a plugin (A) that has optional support for another 3rd party plugin (B). When my plugin A is installed, I create a number of tables. If plugin B is also installed my migrations create further tables specifically for plugin B.
The problem is if someone installs plugin A, then only installs plugin B afterward, my custom tables are never created.
How can I create tables/run migrations only when a plugin (B) is installed?
EDIT
I've been able to get this working with the following:
Event::on(
  Plugins::class,
  Plugins::EVENT_AFTER_INSTALL_PLUGIN,
  function (Event $event) {
    if ($event->plugin->handle == "pluginB") {
      $migration = new migrations\m201031_120401_add_pluginB_support();
      $migration->safeUp();
    }
  });


texts:
Impossible to invoke a method ("getUrl") on a null variable

That's the error message generated by a blank search and some searches.

Fuzzy search is enabled in config/general.php, and it works.  The search template is straight from the Craft CMS "search form" tutorial.

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

Search Results for "{{ query }}"

{% if entries|length %}
    {% for post in entries %}

{{ post.title}}

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

    {% endfor %}
{% else %}

You search for "{{ query }}" didn't retun any results

{% endif %}

{{ post.postImage.first().getUrl('thumbImage')}} works without error every place else.

Any ideas on what I am missing?


texts:
How would you go about pulling a selected entry from one channel into another entry using Craft variables?

For example, I have a page with an author channel field that allows a user to select the author from entries in an author channel. Once selected, I am wanting the page to display the author content from the selected Author entry.

I have tried using the following but have gotten no output.

{% if entry.authorTeamMember|length %}
    {% set myEntry = entry.authorTeamMember.first() %}

    {{entry.authorName}}
    {{entry.authorDescription}}
{% else %}

No Author

{% endif %}


texts:
Starting on a second site which is an almost like for like copy of the first, except it has different content. I cant use locales to manage it because there may be the possibility of multiple languages on the second site.

I have dozens of field & entry types I want to transfer over to the second site. Is there an automated way of deleting all the content?


texts: What is the proper way to fetch items from a custom db table and output them in twig?

texts:
My main issue is perhaps not totally understanding the unique idioms of Yii, but I need to output data from my custom data tables in a template. So obviously I have a MyPluginVariables class and a MyPluginService to handle to actual business logic.

Using my MyPlugin_FooRecord I can use ActiveRecord to fetch some data. But this obviously returns the actual record objects, when I really just need a model passed to the template. From what I understand, I should use models not the records themselves. Is this correct?

Also, how exactly should I build a chainable syntax, similar to fetching entries in a template?

For example, I am trying to get this to work:

{% set rows = craft.myPlugin.someMethod().limit(10).order('some_col').sort('asc') %}

So relating this syntax back to my original question, how would I build this and return an array of models? The ElementCriteriaModel will automatically execute the find() method when it's used an array, should I just overriding the __toArray() method?

I have been searching and looking through the docs, so perhaps I missed something. I have also been looking through the code in Craft, but due to the abstractions and not being familiar with Yii core classes, I am getting a little lost in figuring out how this works.


texts: Paginate entries based on related status

texts:
So, let's assume I have two channels. events and movies, being events the screening time of each movie. In the admin, in the event entry, you can select one movie.

The movie could be disabled. The agenda page, a chronological list of the events shows up. I want to paginate the events, but only the ones with an enabled movie.

I've tried some stuff (see below), but ended up with the same result: A list of events, and some of them with an empty movie attribute.

So I want to exclude the events with no show from the result to paginate.

I've tried:

{% set entries = craft.entries({
    section: 'events',
    with: [
        ['show', { status: 'live' }],
    ],
    limit: 10,
}) %}

and:

{% set entries = craft.entries.section('events').with('show') %}

And to paginate:

    {% for entry in pageEntries %}

            {{ entry.show[0].title }}

    {% endfor %}

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


texts: How Do I Select the second instance of a certain block type

texts:
We use a matrix field for the article content on our site. We have different blocks for different content (text, images, embed etc..) and we have optional fields that are outside of the matrix that  only need to be defined once, like a related article or place.

My current code to output the matrix is as follows

{% for block in entry.postBody %}

{% include 'blog/blocks/_' ~ block.type ignore missing with {"block":block} only %}

{% endfor %}

I want to float my related related restaurant section (which is optional) after either

the second instance of a text block

or

the last text block.

Some of my blocks are elements that take up the entire width of the section, so I want to attach it to a text block so that it floats neatly alongside the text.

How would I select the second or last instance of a certain block type within my for loop?


texts: Craft admin login infinite redirect in cluster

texts:
We're having a problem logging in the Craft admin tool @ https://www.clearlabs.com/admin when we have more than one server in the cluster.
After submitting credentials, Craft seems to keep 302-bouncing infinitely between https://www.clearlabs.com/admin/login and https://www.clearlabs.com/admin/dashboard.
The few times we are able to log in, we seem to get kicked out of our session back into an infinite redirect loop.
Note this does not affect our website, but only the admin web app.

Upon review of the literature, we tried to set overridePhpSessionLocation=false, but it doesn't seem to help.

Can someone please confirm the configuration requirements for Craft clustering and/or give us some thoughts on what might be going on?
Thank you,
Cyril


texts:
I have a collection of entries in a structure, and each entry can be in multiple categories.

Is it possible to sort the entries seperately for each category?

So it would look something like this:

Category 1: entry 1, entry 2, entry 3
Category 2: entry 3, entry 2, entry 4

There seems to be lots of very similar questions here already, but none that are exactly like this, and I can't figure out how to do it. Can someone please help?


texts: Is there a way to populate a drop-down with the templates files in a folder?

texts:
When I have a folder setup for template partials, is there a way I could automatically populate a drop-down with the list of templates in that folder?

This would be useful in the case where I have a complex matrix field set, and would like to select a partial to render or include along with the block's content.

If the drop-down were automatically populated, it would eliminate a lot of time setting up the drop-downs in the backend, and would make it much easier to deploy new feature sets across many Craft based sites as they are developed or improved.


texts: Sprout Forms -- How to link to individual entries on the front-end

texts:
I'm trying to build a front end to display entries collected through Sprout Forms. I want to create a list of all entry titles that can be clicked through to see the full entry.

I can list a single entry, or all entries:

{% for formEntry in craft.sproutForms.entries.formHandle('entry') %}
  {{ formEntry.title }}
{% endfor %}

But when I try to create a link, {{ formEntry.url }} doesn't work. I'm not entirely sure if this is a Sprout Forms issue or a Craft routing issue, or if I'm just missing something obvious


texts: How do I display a list of assets with the entries they are related to?

texts:
Given a list of assets, for each asset, how do I display a list of entries that relate to this asset? So, for instance, if asset A is selected as asset in entries 1 and 2, I want a list to be displayed like this:

Asset A:

Used in entry 1
Used in entry 2

Asset B:

Used in ... etc.

With this ...

{% set content = craft.entries.section('content').find() %}
{% set usedFotos = craft.assets.relatedTo(content).find() | group('id') %}

... I can see if certain assets are used, but now I want to see what entr(y/ies) they belong to.


texts: What is the proper way to set an asset's upload location using the slugs/ structure path of the entry it is selected from?

texts:
I'm working on a site with a structure containing products that are nested within "category"(not actually using craft's categories, just an entry type) pages. On each category or sub-category page I display each product within as a card with an image and title. The image is selected/uploaded from an asset field on the entry.

In the interest of making the image folders as clean as possible I'm trying to set the asset upload locations based on the path of the entry it is uploaded from.

For example: I have a product at the following location: mysite.dev/products/doors/wood. When I upload the image to be used in the product list view I'd like the path to be mysite.dev/assets/img/products/doors/wood/imagefilename.jpg.

My default image upload location is set to mysite.dev/assets/img/.

Is there a simple method I have missed in the documentation to pull the path of the entry as the asset field upload location?

Or is it necessary to make a loop to go through the parent entries' slugs one by one, and if so what is my point of reference when creating the loop? Am I acting on the asset or the entry when I use a variable like {slug}?

I'm tinkering with it and testing, but it is tedious since I must upload the image each time I try something new, and I feel like I might have missed something in the documentation.

Edit:

After a bit more tinkering I was able to get something that almost works. By setting upload location with the Images location in the dropdown and then {parent.uri}/{slug} I get something like mysite.dev/assets/img/doors/wood/imagefilename.jpg. This is missing the structure slug products at the beginning.


texts: Table button missing in Rich Text fields?

texts:
I updated to Craft 2.3 and noticed that the Table button is now missing from my Rich Text fields?

How can I get that button back?


texts:
I have the following

$criteria = craft()->elements->getCriteria('Commerce_Product');
$criteria->search = 'unquieId:' . $result['id'];
$criteria->status = null;
$product = $criteria->find();

The unique result returns a product if it's there and ideally empty if it's not. The odd behavior I'm seeing is if the product is marked disabled in Craft Commerce then the product is returned empty. I thought the status null may help but I don't think they equate. Any thoughts?


texts: Can multi-environment configuration be used in 'index.php'?

texts:
On my local dev sever, as well as the production server, the craft folder is one level above web root, so $craftPath in index.php is set like so:

$craftPath = '../craft';

On the staging server, the craft folder is two levels above web root, so $craftPath needs to be:

$craftPath = '../../craft';

Can this be accomplished in a single index.php file? Something similar to the multi-environment array in config/general.php and config/db.php perhaps?


texts:
I'm using the Store Hours plugin to output store hours like this:

{% set days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] %}
{% set daysShort = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] %}

  {% for dayHours in entry.hoursOfOperation %}

{{ days[loop.index0] }}

    {% if dayHours.open|length and dayHours.close|length %}

{{ dayHours.open|date('h:i a') }} - {{ dayHours.close|date('h:i a') }}

    {% else %}

Closed

    {% endif %}
  {% endfor %}

This works okay and outputs like this:

But what I really need is to be able to group the days if the hours are the same so that it looks like this:

It's also important that I can set an attribute tag on the
 of content="Mo,Tu,We, 10:00-17:00" So how do I group days of the week and output the hours the way my client wants it to look?


texts:
Brand new Craft user.  Second day playing with it, and so far, loving it!

I believe the Solo license allows a Freelancer to roll off personal (for her own use) implementations for free -- even if those sites have a commercial purpose.

I understand this to mean I may power more than one site for free under the terms of the Solo license.

Question: Does this Solo licence freedom extend to paid plugins?

For example, I want to purchase the commercial Enupal Backup plugin.  I would like to use it on my two Solo-licensed Craft websites.  Can I do it, or must I purchase the plugin twice?


texts: Looping through returns nothing after using dynamic routes to get the entry type and category

texts:
I'll explain a bit of the structure of the content and then proceed to the issue.

So i have a website with a shop in it with the url mysite.com/shop/,
it is an channel section, and its template is located at craft/templates/shop/index.html.

The shop is divided in to 2 categories - "new", and "used",
the url for each is mysite.com/shop/(used or new), and its template is located at craft/templates/shop/category.html.

The section(channel) shop that is mentioned above also has multiple entry types, for example "televisions", "consoles", "computers"... and each one has a required category field to chose one of the above(new or used), and the url for those entries is 'shop/{condition.first().slug}/{type}/{slug}'
(the condition field is the category).

Now to what i'm trying to do, and whats the issue.
I want the user to be able to filter through entry types within the category template. what i mean is that te used could click "show only tv's"
and a url with the new filter will load but with the same template, so the url would look like that:
mysite.com/shop/used/television/

To accomplish that i've made a new dynamic route by adding the nex line to my routes.php:
'shop/(?P<segmentCategory>(new|used))/(?P<segmentEntryType>[a-z]+)' => 'shop/category',

And the template goes like this(the twig part only):

{% if segmentCategory is defined %}
    {% set category = craft.categories.slug(segmentCategory).first() %}
    {% set entries = craft.entries({
        type: segmentEntryType,
        relatedTo: ['and',
            { sourceElement: category },
            { targetElement: craft.entries.type(segmentEntryType).status(null).first }
        ]
    }) %}
    {% if not entries %}
        {% exit 404 %}
    {% endif %}
{% else %}
    {% set entries = craft.entries.relatedTo(category) %}
{% endif %}

{% for entry in entries %}
    {{ entry.title }}
{% else %}
    There are no entries matching you criteria right no, please try again in a few days.
{% endfor %}

I'm having two issues with this code.

First: {% if not entries %} never executes, even if i enter complete nonsense in the url.
Second: the array entries is never outputs anything...

Thanks ahead!


texts:
I have an Freeform entry field {{ pageForm }} where the user can select a form to display on the page.

And then in the page template I load the form in to the page using {{ entry.pageForm.render() }}. Cool.

I also want them to be able to choose the return URL from an Entries field e.g {{ entry.formThankyouUrl }}. Is there any way to pass that formThankyouUrl to the renderTag? E.g the below setup would be ideal..

Page template:

{% if entry.formPageForm|length %}
   {% set thankyouUrl = row.formThankYou.one() ?? null %}
   {{ entry.formPageForm.render() }}
{% endif %}

Form template:

{{ form.renderTag({
  returnUrl: thankyouUrl
}) }}

The reason I ask is that the default Return URL functionality in freeform is quite limited in that you have to paste in the URL, would be good to select it form a entries dropdown

Thanks


texts: can i used craft.entries.section into my Controller

texts:
I am new in Craft CMS and this is my first plugin. Below is my code to get products.

{% craft.entries.section('products').limit(9) %}

This code is working fine but can I use this code in my controller for getting products?

Thanks


texts:
I have run into a problem of file sizes maxing out on 256MB.

On PHP side I have
upload_max_filesize & post_max_size set to 1GB

I've created a simple PHP script to test upload size and managed to upload 800MB file. So everything points to Craft having some limits.

In Craft CMS config file I have:

'maxUploadFileSize'     => 1073741824

Yet if I try to upload files larger than 256MB I get a modal message saying file size exceeds 256MB.


texts: Display related entries across different entry types using tags in different tag groups?

texts:
I'm working on a site that has two different entry types (e.g., "blog" and "photos"), and each type has it's own tag group. When viewing a particular entry, I'd like to display related entries found in both entry types.

So, for example, let's say that I've written "Entry A" and "Entry B" -- "Entry A" is in "blog" and "Entry B" is a "photos." They both have the same tag ("foo"), but that tag exists in each entry type's respective tag group.

If I view "Entry A," can I display a list of related entries that includes "Entry B" even though the tag that they share isn't in the same tag group?


texts:
How can a user create an entry that is only enabled for 1 locale?

I would like a German user to only be able to publish an entry in the de locale.

I have set the permissions for the user to only publish in the de locale, but, when this user saves a new entry, the locale is then enabled for every locale.

I have tried disabling each locale in the channel settings, but, then the user is required to enable it for their own locale when publishing.

Similar question here, but no answer yet.


texts: Embedding video using Craft 3 'Video Embedder' plugin

texts:
In the example from the documentation on Craft 3 'Video Embedder' plugin:

{% set embed = craft.videoEmbedder.getEmbedUrl('https://www.youtube.com/watch?v=6xWpo5Dn254') %}

{% if embed | length %}
    <iframe src="{{ embed }}"></iframe>
{% endif %}

Can someone please give me full (i.e. total beginner!) instructions on how to get the URL to load.


texts:
I have events that are presented by month.  Right now they are being separated by Month but the heading for each chunk shows January as the month for each one.  Not sure why, or how to fix it, am interested in understanding both.  I am somewhat new to craft.

{% if entry.heading is defined %}
{{ entry.heading }}
{% endif %}

{% set allEntries = craft.entries.section('tours').find() %}
{% set allEntriesByMonth = allEntries|group('entryDate.month') %}

{% for month, entriesInMonth in allEntriesByMonth %}

{{entry.entryDate|date('M')}}

        {% for entry in entriesInMonth %}

{{entry.entryDate.month}}.{{entry.entryDate.day}}.{{entry.entryDate.year}}&nbsp;&nbsp;-&nbsp;&nbsp;{{entry.locationCity}}, {{entry.locationState}}&nbsp;&nbsp;&nbsp;register

        {% endfor %}
{% endfor%}

I am trying to adjust the h2 with |date('M') in order to display the date as text.  If I do not do that it displays the correct month number, but when I try to format it it breaks and displays the same month for all entries even though it is still ordering them.  So how can I format this to show month as text without breaking it?

Any attempt to format the date breaks it. The dates below should be september and october.


texts: Using Asset folder variables with Sprout Forms

texts:
Is it possible to use auto-generated subfolders within an asset field? Each time I've tried, I get errors upon submitting the form that seem unrelated and nothing posts.

I'm just trying to do a simple job application form on our website and I'd like to have the file dumped into the subfolders: {jobID}\{email} (jobID is passed in as a hidden field), this way I know there won't be any issues uploading files unless the same person applies multiple times to the same position in which I guess I could put a timestamp on there as well.

I've tried those simple variables mentioned above, and I've also tried {object.jobID}\{object.email} but no luck.

Any help would be appreciated! Thanks!


texts:
I've noticed the HTML option above Rich Text Fields for entries is now gone in Craft 2.5, regardless of being configured as Default, Simple, or Standard.

Is this a feature that has been removed from Craft in v2.5+? I currently have a ton of content that relies on custom HTML outside of what's available in the format bar, so this would be pretty devastating.

Am I overlooking where this option is now?


texts: How could I have a plugin hook into when I edit or update a post?

texts:
What I am trying to do is have my plugin know when I edit a post that is part of a particular section - let's call it "parts" - which then checks to see if a field is filled out in the form and then hits up an API and then pulls information from it and inserts it into empty fields in the entry.

So to clarify, here is a flow of what I'm looking to do:

I create an entry in the section "parts".
Upon saving, it checks to see if the part number field is filled in.
If the field is filled in it will access an external json api and I'll pull a certain value (or in some cases multiple values) from the array.
I then want to have it fill in/update/replace the values in fields that I specify that are part of this entry.

So essentially I am trying to figure out how to: Have my plugin trigger once an entry in a specific section is edited or added and then how I can (off of this trigger) have the plugin insert a value (or multiple values) into specific fields in the entry.


texts: How to search based on a Multi select category field in Craft 3?

texts:
I have a blog section with multi select categories. I want to filter all the blogs based on that multi select categories in the website. When I tried

 .search('category:ui-ux OR category:web-designs')

the result blogs are not accurate.

Category is a multi select field. So multiple category may assigned to one blog. I will list all these categories in my front end and need to filter blogs based on that.

How I will do this search?


texts:
So I have a Structure like that

Item

Subitem | inactive
Subitem | inactive

why is item.hasDescendants() true ?

How would I do something like that the right way:

<li class="{% if nav_item.hasDescendants() %}more{% endif %}">


texts: Is it possible to have multiple locales that use different domains instead of subfolders?

texts:
Instead of:

example.com/en
example.com/de

I'd have:

example.com
example.de

Can I do this with craft? I see this has been discussed, but a complete solution hasn't been posted.


texts: Help with tags input field on a front-end entry form

texts:
I need to make a "keywords" field on a front-end entry form that can create tags in the cms (Craft 2).  I am fully aware of existing tickets regarding this issue like Brandon Kelly's but they're a little too ambiguous for me.

This is the classic tag field where you type a word, press spacebar, and a new tag appears, etc.  I am aware that when my form submits, despite what's visual on the page, the submitted html needs to look something like this:

<input type="hidden" name="fields[fieldName]">
<input type="hidden" name="fields[fieldName][]" value="{tag 1 id}">
<input type="hidden" name="fields[fieldName][]" value="{tag 2 id}">
<input type="hidden" name="fields[fieldName][]" value="{tag 3 id}">
// etc

I've looked into many jquery plugins and they don't output this html pattern. Instead, they all basically create a single hidden input field with all your tags entered in the value attribute separated by commas like value="tag1, tag2, tag3, etc", (tag-it is one exception but it is outdated, buggy, and it always prints the tag's text in the value).

I'm not entirely sure how this all should work, but I'm guessing I need to write custom ajax so that when a tag is created, an ajax call uses the createTag action to create the tag in the database before the form submits, since the saveEntry form submission itself won't create the tag but merely link an existing tag to that entry.

Then, just as it's shown in Brandon's original answer, my js adds the hidden input formatted correctly in the successful response. If the user deletes a tag, I have to use the jquery plugin's removeTag callback (or whatever the callback is) to then remove that hidden input.

However, where I'm getting confused is on these points:

When a user deletes a tag on the front-end (let's say they made a typo), the js deletes the hidden input in the html, but the tag is already created in the database. Do I need to then somehow delete that tag in the database via ajax or just let my db rack up a bunch of unusable tags?
Is it better to just do away with the hidden input approach, use a plugin to accept the comma-separated tags from one hidden input and do all the creating/checking for existing tags/etc on a entries.onBeforeSaveEntry as Ben seems to suggest in this ticket?

Can anyone offer up actual examples of what they did to handle tags on the front end? Maybe also some suggestions of solid jquery plugins in 2018 (many seem janky and not up to date)?  And is my process of thinking outlined above incorrect in any way (I have very little idea what I'm doing)?

Current examples online are either for listing out existing tags the user can choose from with checkboxes or a multiselect (which is usually not the case on a form), or just showing some basic ajax. Any help and clarification would be greatly appreciated (and hopefully help someone else down the line).


texts: Images Uploaded in CMS not showing on mobile [desktop is fine]

texts:
Just want uploaded images for entries to show for desktop AND mobile

{% set assets = entry.galleryImage %}

{% if assets | length %}

{% for asset in assets %}
    {% if asset.kind == 'video' %}
        <video class="vid" preload="none" controls="false" loop webkit-playsinline muted>
            <source src="{{ asset.url }}" poster="{{ asset.url }}" type="video/mp4">
        </video>
    {% else %}
        <img class="gallery_img_1"  src="{{ asset.url }}">
    {% endif %}
{% endfor %}


texts: Use getCriteria with OR condition on multiple fields

texts:
I am filtering users in my CP by adding a new user source.
I know how to get users for specific criterias.

But in this case I want to make a OR condition on those two users fields :
$user_criteria->emailLogo = true;
$user_criteria->webLogo = true;

public function modifyUserSources(&$sources, $context)
{
    if ($context == 'index')
    {

        // LISTING USERS
        $sources[] = array('heading' => 'Stats Users');

        $user_criteria = craft()->elements->getCriteria(ElementType::User);
        $user_criteria->group = 'myMembers';

        // THIS WILL MAKE A -AND- CONDITION (I WANT A -OR-)
        $user_criteria->emailLogo = true;
        $user_criteria->webLogo = true;

        $sources['users:memberBranding'] = array(
            'label'    => Craft::t('Logo'),
            'criteria' => $user_criteria,
        );
    }
}


texts:
I am using a structure for all of my site's pages (single pages and channel index pages). The structure settings are as follows:

URL for Top-Level Entries:
{slug}

URL for Nested Entries:
{parent.uri}/{slug}

Entry Template:
_pages/_entry.html

Additionally I set up multiple entry types for the structure to relate the pages with individual templates (basically as described in the FAQs). This is my _entry.html:

{% include '_pages/_types/' ~ entry.type %}

This all works great for me [*], but now I'd like to further improve the template setup by adding my site's home page to the structure, too. With a single section I can simply trigger the option "this is the home page" in the section's settings, but how can I tell an entry of my pages structure to be my home page?

[*]: I can generate my site's main navigation from this structure (nice!) and all channels' index pages have entry slugs now, which is incredibly helpful in a multi-lingual Craft setup, if you want to translate your slugs.


texts: How do I iterate over a categories field in an entry

texts:
I'm using the Scout plugin to sync my entry data to an Algolia search index. In the transformer for the scout.php config file, I need to iterate over all of the categories in a category field on each entry.

How would I do this to output the category at each level like so:

"categories": {
    "lvl0": ["Rigging", "Film Lighting"],
    "lvl1": ["Rigging > Rigging Support", "Film Lighting > Stands"],
    "lvl2": ["Rigging > Rigging Support > Stands"]
}

Here is where i'm at with the transformer:

'transformer' => static function (craft\base\Element $entry) {
    return [
        'entryTitle' => $entry->title,
        'id' => $entry->id,
        'url' => $entry->url,
        'title' => $entry->equipmentFriendlyName,
        'manufacturer' => $entry->equipmentManufacturer,
        'modelNumber' => $entry->equipmentModelNumber,
        'description' => $entry->equipmentDescription,
        'categories' => $entry->equipmentCategory->all(),
    ];
}


texts:
I have AMPPS installed on my Mac OS X, and am trying to install the CMS. When I browse to http://craft.dev/admin to install, it redirects to http://craft.dev/admin/install with the following error:

Fatal error: Call to undefined function ctype_alpha() in /Users/username/domains/craft.dev/craft/app/vendor/twig/twig/lib/Twig/Lexer.php on line 380

Any suggestions on fixing the issue?


texts: Is there a way to set a new property on an entry

texts:
In a plugin I am creating I want to add a property to some entries.

Ideally this property would be hidden from the admin user, as I don't want them to edit it.

At the moment I am trying to do something like this (simplified):

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

foreach ($entries as $entry) {
    $entry->secretName = urlencode($entry->title);
    craft()->entries->saveEntry($entry);
endforeach;

But this produces the error 'Property "Craft\EntryModel.secretName" is not defined.'

Does anyone know how to do what I am trying to do? Is there a way to set a new property to just this section?


texts:
I have a multi-lingual site with a folder structure set up like this:

/craft
/assets
  -/images
/nl
  -index.php
/fr
  -index.php
index.php

I have an asset source set up like this:

File system path: assets/images/
File URL: http://krycer.be/assets/images/

This allows me to upload images without any problems and they are uploaded in the correct folder on the server.

I use image transforms in my templates by using the {{ asset.getUrl('imageTransformHandle') }} but this gives me errors. The images are not generated (there is no redirect to the generated image, the URL is linking to the cpResources/transform/ID).

When I try this code in devMode 'generateTransformsBeforePageLoad' => true it gives me an error that it cannot find the file (allthough it is definitely on the server).

I tracked this issue back to the fact that I have sub folders for my languages (nl/fr) and probably the image transform module searches a path from the local index.php file.
So when I adjust the asset source to ../assets/images/ the transforms are generated and I can see the images.
But then I have the problem that I can no longer upload any images because the path is not correct (because the asset source is probably looking in relation to the top index.php file, being the one above the nl/fr folders).

How do I fix this and is this a bug or is there an easy idea behind it I do not grasp?


texts: 400 Bad Request on account or admin login

texts:
On attempting to login into either a front-end account or admin account I'm hit by:

400 Bad Request
Request Header Or Cookie Too Large
nginx/1.8.0

It's only happened recently but running the latest Craft CMS v2.5.2757 and from looking at the cookies created during login I think it's possibly related to CSRF protection as deleting the top cookie in the list below fixes the issue until you log in again.

Running a few other Craft sites on the same staging nGinx server without the same issue, and even the same codebase is running another site without issue.

Any thoughts please?!


texts: How do you set up live preview for headless Craft CMS installs connected to Gatsby?


texts: How can I validate a Redactor rich text field in a front-end form using the VeeValidate Vue.js plugin?

texts:
Scenario

I'm using the VeeValidate Vue.js plugin to validate a Craft front-end form that contains a Redactor rich text field.

Problem

Validation of the rich text field fails because Redactor adds style="display: none;" to <textarea> elements.


texts: Load Balancing Craft CMS - Admin gets logged out instantly

texts:
We are load balancing 2 servers hosting an identical Craft environment.

When clicking around in the admin a user will get logged out after 30 seconds and sometimes even faster when browsing in the admin panel.

I am unable to set the load balancer to sticky sessions due to the load balancer sitting behind a Firewall which NAT's inbound traffic. So the load balancer see's all inbound traffic as a single IP.

Is there anything else that can be done to resolve this issue?


texts:
I have a channel of Musical Compositions:

Now all these Compositions have a Composer.
All the composers are stored in a separate channel and then linked with their respective compositions trough a entries field

Now I like to order the compositions by the last name of the composer and group them together alphabetically.

I managed them to be grouped but not by the composer name, just by the composition title which is not helpful.

{% set allEntries = craft.entries.section('komposition').limit(null) %}
{% set allEntriesByPrename = allEntries | group('title|upper|slice(0, 1)') %}

{% for letter, allEntriesSorted in allEntriesByPrename %}
 {# stuff #}
{% endfor %}

Now the catch here is the group filter I guess but when I use the handle of the entries field it doesn't work:

| group('composerRelated.lastName|upper|slice(0, 1)')

If I write it like this, the group filter simply is ignored. Since the entries field returns an array I have no idea how to write this. And I think at the time of the group filter the entries field is not available yet.

I also tried to grab all composers from the section and put it into the group filter:

{% set allEntries = craft.entries.section('komposition').limit(null) %}
{% set composerName = craft.entries.section('komponist').limit(null) %}

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

This is too much inception for me. How do I have to write this?


texts: How can I build a combined search without making all fields required?

texts:
I'm trying to build a form where users can search for events based on a date range, location and price range. I've got the form working, but having a bit of trouble when some fields/ selects are left blank.

The desired functionality should be that none of the fields should be required.

For example: If I select a location, I would like to see all events at that location even if the dates and price ranges are left blank. Or if all fields are left blank, I should see all events.

This is a stripped down version of my form:

`<form action="{{ url('results') }}">

<input type="text" name="dateFrom"> //this is a datepicker
<input type="text" name="dateUntil"> //this is a datepicker

<select name="country">
  <option></option>
  <option value="france">france</option>
  <option value="belgium">belgium</option>
</select>

<input type="text" name="priceMin">
<input type="text" name="priceMax">

<input type="submit" value="Go">
</form>`

And here's what i've got on my results page

`{% set country = craft.request.getParam('country') %}
{% set dateFrom = craft.request.getParam('dateFrom')|date("Y-m-d") %}
{% set dateUntil = craft.request.getParam('dateUntil')|date_modify("+1 day")|date("Y-m-d") %}
{% set priceMin = craft.request.getParam('priceMin')  %}
{% set priceMax = craft.request.getParam('priceMax') %}

{% set results = craft.entries({
  section: 'events',
  order: 'score',
  start: '>=' ~ dateFrom,
  end: '<=' ~ dateUntil,
  country: country,
  price: [
    'and',
    '>=' ~ priceMin,
    '<=' ~ priceMax,
    ]
}) %}

{% if results|length %}

{{ results|length }} results:

  {% for entry in results %}

{{ entry.title }} - {{ entry. price }}

  {% endfor %}

{% else %}

Your search didn’t return any results.

{% endif %}`

Anyone have any suggestions?
Thank you!


texts: Order of Redactor format options using formattingAdd

texts:
I'm using formattingAdd in a JSON config file for redactor. The items do not appear in the menu in the order I define them.

After some searching I realise the format for formattingAdd is an object and each format is a property of that object. Javascript does not guarantee the order of properties returned from an object.

The redactor source code uses jQuery $.each which cannot 'fix' the issue with javascript not ordering the properties of an object.

Does anyone have a workaround for this? I could change the code in craft/app/resources/lib/redactor/redactor.js to accept an array of objects for formattingAdd but I guess it would be overwritten everytime I upgrade craft.


texts: Output section and tag name with URL in entry loop

texts:
I'm trying to loop through entries in specific sections and output Entry's:
    - URL
    - Title
    - Type
    - Asset's image
    - asset's URL
    - Section's name
    - Section's URL
    - Tag's name
    - Tag's URL

So far I came to this with having difficulties with section's URL and tags that belongs to relative entry.

        {% set entries = craft.entries.section(['worldTechnology','worldTravel']) %}
        {% for entry in entries %}

{{ entry.title}}

                    in
                    {{ entry.section.name }}
                    {{ entry.getType.name }}

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

                            {{ tag.title }}

                        {% else %}

                            No tags found

                    {% endfor %}

        {% endfor %}

I'm working on it only in evenings and I'm starting to like Craft and Twig. Hopefully some of you guys, will advice me or give me some direction to go after.

Thanks for viewing it.


texts: Emails not being sent when transaction complete

texts:
Folks:

I'm wondering if this is a bug or something else. Essentially, test emails from the system work fine but emails that are supposed to be sent when the order moves to "Processing" do not. The log file from yesterday states: 2016/03/17 14:31:52 [info] [plugin] [Forced] Can't send email if no status or emails exist.

But there is a status (processing) and an email for that status ({{ order.email }}). I have attempted several dummy transactions today as well but the emails don't come through and the logs don't update either. And no, there's nothing in the spam folder. Or error messages sent back to the host.

I even tried to have the order emails sent to a specific email address instead of {{ order.email }}. No joy.

Finally, I am using the default commerce templates so I'm pretty sure the issue isn't there.

Does anyone have any ideas?


texts: Conditional statement for nav tag when no children

texts:
On the menu below I need to change the class on the li from dropdown-submenu to dropdown-item for those entries that don't have children.  Any ideas?

Thanks

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

                {{ page.getLink() }}

                {% ifchildren %}

                        {% children %}

                {% endifchildren %}

        {% endnav %}


texts: I'm trying to set up some shipping rules. I've created a new shipping category called "Sample" I can apply it to the product fine. When I set the rules I want and then head to the checkout the shipping category doesn't show. Are there any obvious steps I'm missing here? Or any examples I can follow?


texts: Problem with Twig group function, group by year

texts:
I am trying to apply the group filter so that my year headings appear in DESC order. They are appearing in ASC order instead, and applying |reverse doesn't work. Suggestions?

{% set entries = craft.entries.section('blat')
.orderBy('postDate DESC')
.limit(null)
.with ( ['thumbnail'] )
%}
{% set entriesByYear = entries|group('postDate.year') %}
{% for year, entriesInYear in entriesByYear %}

    <h2>{{ year }}</h2>

  {% for entry in entriesInYear %}

{% endfor %}


texts: Only allow signups from people with @___.com emails

texts:
I want users to be able to signup to my Craft site, but only if they have a specific email domain. So:

*@gmail.com
*@hotmail.com

Would be allowed, but anyone with a yahoo.com email, for example, would not be able to sign up. I can do client-side validation but is there anything I can do in Craft?

Thanks!


texts:
I have 2 separate sections living in the same place on my site. Example:

About (Single-type Section)

Team (Structure-type Section)

So in the URL I need to nest Team underneath About, i.e. /about/team. Since they're not in the same section I can't do it the built-in way, so how would I accomplish this?


texts: How do I add an H2 tag to a page? The site already runs many months now. All pages are okay but some are lacking an h2 tag. Is there a simple way to add an h2 tag to these pages?


texts: Display Backend User Entries on Front end

texts:
I have the user submitting to a function that adds entries to a field called completed. It basically adds entries to each user showing the admin who has completed what.

I'm trying to figure out how to display a message on the front end that states if the user has completed the article. I need the message to stay on the front end for each entry that's been completed.


texts: Limiting the Upload Location for assets in a Matrix Block

texts:
In the Dashboard, while editing the settings of a Matrix Block — the instructions for setting Upload Location for an Assets field says Note that the subfolder path can contain variables like {owner.slug} or {owner.author.username}.

To what does owner refer?

Ideally I want to store these assets in Site Assets/pages/{slug of the page this block is on}  — is owner the page name or the username or what?


texts: Get events where all occurrences are in the past with the Solspace Calendar plugin

texts:
With the Solspace Calendar plugin, is there currently a way to pull a list of all events that don't have occurrences in the future?  In other words, we have a calendar with a lot of repeating events and we want to pull up a list of all of the events (not the occurrences) which are not longer actively repeating.  So until < today?

It seems like using the dateRangeEnd parameter lets you pull up only occurrences in that range but don't seem to know of a way to just get events that have stopped repeating?


texts: Template for submit via ajax to Guest Entries plugin

texts:
I am a bit mystified by how to utilize templates for Guest entries plugin working fine for normal post saving custom fields.

When I use ajax to submit I get an XHR 200 response but an HTML response - no JSON. Ideally I don't want to redirect to another page but just manipulate the DOM and pass some variables into the page form JSON returned on success.

I have read and reread every ajax post but still can't get a pure JSON response

Is it necessary to utilize some kind of detection within the template for Craft ajax?

Just when I thought i had ajax understood...

Here is my JS:

$(document).ready(function () {
//validation rules
$("form#brick").validate({
    ignore: ":hidden",
    rules: {
        "fields[firstName]": {
            required: true,
        },
        "fields[lastName]": {
            required: true
        },
        "fields[email]": {
            required: true,
            email: true
        }
    },
    messages: {
        "fields[email]": "Email is required"
    },

    submitHandler: function (form) {
        // Prevent default posting of form
        event.preventDefault();

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

        $.ajax('/', data, function(response) {
            if (response.success) {

                console.log(response);
                $('#thanks').fadeIn();
                $('#brick').fadeOut();
                console.log(response);
            } else {
                // response.error will be an object containing any validation errors that occurred, indexed by field name
                // e.g. response.error.fromName => ['From Name is required']
                alert('An error occurred. Please try again.');
            }
        });
    }
});

});


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


texts:
I'm a total S3 noob but would like to get it set up so that I can store Assets there. So far, I've:

created an AWS account (zing!)
created a bucket named mybucket
created a user in IAM myuser
assigned the AdministratorAccess policy to myuser*
created a new Asset source called s3
entered the user Access Key ID and Secret Access Key, which correctly shows me the mybucket destination
URL Prefix is auto-filled with http://s3.amazonaws.com/mybucket

OK! When I go to upload a file to the S3 source, I see the upload stripe go all the way across the page and the loading spinner happening at the top right of the page. But this process hangs and the file is never uploaded.

This is a tiny image, so I don't think it's a file size issue. No errors / warnings are produced. I don't see anything obvious in the logs.

Any help is appreciated! Thanks!

--

*I know that I'll eventually want a more restrictive policy but for the time being, just trying to get a Hello World working.


texts: Edit a checkbox field within table field from the front end

texts:
This is an extension of a question I posted here earlier, but another layer of complexity.

I'm trying to have a checkbox field within a table field be checked/unchecked from a front end form.

I've tried a number of scenarios using the example found here in the docs, but no dice.

Here is my current code:

      {% for row in currentUser.providerPayment %}

        Sliding scale?

        {% for slidingScale in currentUser.providerPayment  %}
            {% set checked = false %}

            {% if slidingScale.selected %}
                {% set checked = true %}
            {% endif %}

            {% if not checked %}
                <input type="hidden" name="fields[providerPayment][0][col2]" value="">
            {% endif %}

            <input type="checkbox" value="{{ slidingScale.value }}" name="fields[providerPayment][0][col2]" {% if checked %} checked="checked"{% endif %}>
        {% endfor %}
    {% endfor %}

And here is the error it's producing:

Update Here are my table field settings:


texts:
Running Craft 3.1.19 and have started getting twig error in the control panel.  When I click on the utilities link I get this error:

Declaration of craft\web\twig\Environment::compileSource(Twig\Source $source) should be compatible with Twig_Environment::compileSource(Twig_Source $source)

And when I try to create a new field I get this error:

Key "defaultUploadLocationSubpath" in object with ArrayAccess of class "craft\fields\Assets" does not exist.

Any idea what is going on?

Thanks!


texts: Template output when grouping matrix blocks

texts:
I have a shared content builder matrix field that has the usual blocks: Redactor, Headings, Images, etc.

A typical entry might look like this:

- Heading
- Redactor
- Image
- Redactor
- Heading
- Redactor
- Heading
- Redactor
- Image

Ideally I'd use a nested matrix - I'm aware this is on the roadmap  and Super Table / Neo do support this but I'd like to reuse my shared content builder field and handle the output via the templates.

On the page I'd like to output it like so:

- Heading | - Redactor
          | - Image
          | - Redactor

- Heading | - Redactor
- Heading | - Redactor
- Heading | - Redactor
            - Image

Basically grouping by heading block and then output any content until the next heading block.

I've seen a couple of examples which are similar to this but I haven't been able to get the template and queries right for this.

I know I can use the group filter but I'm having trouble with not being able to break out of a loop. Fairly sure I need to construct a list of structured id's and output them that way.

Anyone done something similar to this or can shed some light?


texts:
I'm working on an import of a feed from a Simple Machines Forum (SMF) which contains images from lots of external sources. Some of the images are importing OK, but most of them are failing with:

fopen(): SSL operation failed with code 1. OpenSSL Error messages: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed.

I haven't been through all of the ones that have failed, but each one I've looked at, I can open directly in a browser tab. Most of them are https addresses. Some are http addresses that redirect to https versions.
Most of the ones that are failing are from i.imgur.com or the client's own domain (although I'm doing the import on my local copy of the site at the moment).
Has anyone else ever come across similar errors and how did you resolve them?
EDIT: Just discovered that the client's domain is being protected by Cloudflare.


texts: Applying an image transform returns a 404 cpresources URL

texts:
EDIT 3: Started using imager and no longer have the problem. It's not a real answer to the problem but solves the problem.

This is the situation that has me pulling my hairs... I've looked at other related Q&A's but can't seem to distill a solution for the issue I'm facing.

I'm trying to apply an image transform but I get a link like /cpresources/404?x=TBKkjeyyP returned. Also, no image is being generated.

Files can be uploaded trough the backend just fine, can be linked to an entry and can be shown without applying the transform.

Any pointers as to what is going wrong? I'll gladly provide additional information if/when needed.

My setup is as follows:

Using Craft CMS 2.6.2986 on apache
3 locales configured (nl, en, fr)
local storage (File System Path: uploads/& url:  {baseUrl}uploads/)
relevant config below (using process described here)

General config:

// All environments
'*' => array(
    'omitScriptNameInUrls' => true,
    'overridePhpSessionLocation' => true,
    'usePathInfo' => true,
    'cacheDuration' => false,
    'useEmailAsUsername' => true,
    'generateTransformsBeforePageLoad' => true,
    'siteUrl' => array(
        'nl' => getenv('CRAFTENV_SITE_URL').'nl/',
        'fr' => getenv('CRAFTENV_SITE_URL').'fr/',
        'en' => getenv('CRAFTENV_SITE_URL').'en/',
    ),
    'craftEnv' => CRAFT_ENVIRONMENT,
    'environmentVariables' => array(
        'baseUrl'  => getenv('CRAFTENV_BASE_URL'),
        'basePath' => getenv('CRAFTENV_BASE_PATH'),
    ),
    // development environment
    'development'  => array(
        'devMode' => true,
        'enableTemplateCaching' => false,
        'allowAutoUpdates' => true,
    );
);

Relevant CRAFT_ENV settings:

'SITE_URL' => $protocol . $_SERVER['HTTP_HOST'] . '/',

'BASE_URL' => $protocol . $_SERVER['HTTP_HOST'] . '/',

'BASE_PATH' => realpath(dirname(__FILE__)) . '/www/',

EDIT: Part of the code applying the transform:

{% set thumb = blog.previewImage.first() %}
{% if thumb %}
    <img src="{{ thumb.getUrl("blogPreview") }}" width="{{ thumb.getWidth("blogPreview") }}" height="{{ thumb.getHeight("blogPreview") }}">
{% endif %}

EDIT 2: relevant log entries

  Level warning
  Category    application
  Message [Forced] Image “gasmeters.png” could not be found.

  Level trace
  Category    system.db.CDbCommand
  Message Executing SQL: DELETE FROM craft_assettransformindex WHERE id = :id. Bound with :id='70'


texts: How to get user's information when registering or logging in via ajax form

texts:
I did search for this but was unable to find the documentation for getting user's data on a return when logging them in from a front-end facing login form (I need to do the same for a registration as well).

I need to get a return of the user's Id and their email.

This is my code for the form. It works fine,  I just cannot seem to find the user's info in the data return so if anyone has an example or suggestion it would be greatly appreciated.

$('#workshop-registration-user-login-form').submit(function (e) {
  e.preventDefault();
  var data = $('#workshop-registration-user-login-form').serialize();

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

    ...

    // get data populate the fields
  })
  .error(function(data) {
    console.log('error');
  });


texts:
How do I flush Craft's query cache so that I may query a relationship field again in the same web request with a new set of parameters? In this particular scenario, I need to handle it inside of a custom module so I need PHP and not Twig.

Yes, I am fully aware of cloning the original query in order to make a second query with modified parameters so do not mention that in your answer. It is not an option in this scenario and it does not answer my question.


texts: Fetch values for a single field across all entries in a section

texts:
I have a section "Hotel Room" with a field "Sleeps" (number). There is no limit on the values that can be entered. On the frontend I want a list of all existing entered values for this field. So if I have these four entries:

sleeps=2
sleeps=2
sleeps=8
sleeps=10

I want an array [2, 2, 8, 10] to iterate over. Bonus points for unique/distinct values, but I'm well aware I can add a Twig filter to array_unique() it.

Is this possible using Craft's craft.entries lookups within Twig?


texts: Is it possible to limit the locales for asset meta fields?

texts:
I am working on a multi-lingual site that contains a few sections in 5 languages (de, en, es, fr, ja). Most of the content however exists only in two languages (de, en). For regular content sections I can indicate which locales should be available. However, I could not find a way to limit the locales for asset meta fields in a similar way.

Background: Why do I want to limit the number of locales?

My site contains a large number of product descriptions. Each product description can have multiple assets. Each asset has a (non-translatable) type (e.g. image, PDF, audio sample) and a (translatable) caption. The captions exist only in the de and en locales. When I import the assets in craft (with a plugin), a content entry for every locale will be created and this leads to a very bloated content table.

Can I just delete the unwanted entries in the content table?
Should I use a different setup for storing assets (e.g. a special content section with a file field and not asset meta fields)?

Any help is highly appreciated. Thank you.


texts: How to get a param from an ajax request in twig?

texts:
Ok this has been puzzling me for too long now! I have some code that makes an ajax request:

reqAjax: {
    type: 'get',
    url: '/mytemplatefolder/myfile.html',
    data: {town: 'bournemouth'}
}

This returns a json object to populate dates in a calendar. The dates have links to the town the event is in but to do this dynamically I need to be able to make use of the town param in twig. What I have at the moment at the top of myfile.html is:

{% header "Content-Type: application/json; charset=utf-8" %}
{% header "Access-Control-Allow-Origin: *" %}

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

But town is not being set. So I guess I am missing something on how to get the data from the ajax call and set it in the template. Any help much appreciated.

Cheers


texts: From a Twig template, how to retrieve the content of a HTTP header in the current request?

texts:
I would like to detect if a header in the current request is present and obtain its value, directly within a Twig template.
I know that craft.app.request gives access to a few variables like isAjax that directly check the headers content, but I haven't found a method to directly retrieve a specific header.

Can this be achieved in some way? (preferably not by writing a plugin)


texts: I need to accept a decimal value for the quantity of a line item and for the total quantity. I understand this is not a normal request for most products but my client sells items by the foot and needs the flexibility to sell lengths in feet and inches (ex. 10 ft. 6 in. = 10.5 or 5 ft 6.5 in. = 5.541. I could probably hack this using JavaScript on the front-end but would like to do this the correct way. Any guidance is greatly appreciated. Has anyone achieved this?


texts: Adding an additional Download PDF to orders

texts: Is there a hook or something I can use to add an additional Download PDF option to the Edit Order screen? It looks like a dropdown, but I can't find any docs on how to add to it.


texts: How do I add a local file to an asset field with a dynamically generated sub-folder?

texts:
I've got a plugin that creates PDFs using Michael Rog’s Printmaker plugin. I'm able to successfully save these to a local folder and, using insertFileByLocalPath(), add them to an asset source. Then, by finding the id of the newly created asset, I can save the PDF to an entry.

My problem is that the asset field in the entry is setup to use dynamically-created subfolders, which I want to use to keep the assets for each entry separate from each other.

However, because the dynamically-created subfolder doesn’t exist until an asset is added to the entry, I am adding the PDF to the parent folder using insertFileByLocalPath().

I thought that when I added the asset to the entry and saved it, Craft would dynamically create the subfolder and move the asset into it, but it doesn’t do this. Instead, it just leaves the assets in the parent folder.

Here’s a simplified version of the code I’m using at the moment:

// Create PDF with $vars and $settings
$pdf = craft()->printmaker_pdf->pdfFromTemplate($template, $vars, $settings);

// Save PDF and get URL
$pdfUrl = $pdf->url();

// Get assets parent folder
$folder = craft()->assets->findFolder(array(
    'name' => 'parent-folder'
));

...

$response = craft()->assets->insertFileByLocalPath(
    $localFilePath,
    $filename,
    $folder->id,
    AssetConflictResolution::KeepBoth
);

// Get id of pdf (newly created Asset)
$pdfId = craft()->assets->findFile(array(
    'filename' => $settings['filename'].'.pdf'
))->id;

// Add PDF to entry
$entry->setContentFromPost(array(
    'myAssetField' => array($pdfId)
));

if (craft()->entries->saveEntry($entry)) {
    // Yay! PDF successfully saved to myAssetField
}

And here’s what the asset folder layout looks like:

parent-folder/new.pdf

Whereas what I want to achieve is this:

parent-folder/entry-slug/new.pdf

Where entry-slug is a dynamically created subfolder for each entry.

Any ideas how I can achieve this, or if it is even possible?


texts:
I am attempting to add a second locale to a site with existing content, much of that content in matrix fields.

Following the documentation for Setting Up a Localized Site, I have defined the locale, enabled all sections for this locale (and the original one), set up the configuration and the index.php files. What I have not yet done is mark any field as translatable.

What I was expecting is that entries in the new locale would be initialized with content from the original locale. And this has happened, except that the matrix fields have not been duplicated, so the entries in the new locale do not have any of that matrix content.

This is very similar to How do I get Matrix elements to copy their content across language Locales?. The answer there is "don't mark matrix fields as translatable", which I haven't done, so not sure why this isn't working for me.

Any clues?


texts:
I'm trying to update a drop down field type on an entry using a front end form. However, the input is a hidden field (not a select)

This is the form code I have so far:

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="questions/{{ selectedSession }}">
    <input type="hidden" name="enabled" value="1">
    <input type="hidden" name="sectionId" value="{{ question.sectionId }}">
    <input type="hidden" name="entryId" value="{{ question.id }}">
    <input type="hidden" name="fields[questionStatus][]" value="answered">
    <input type="submit" value="submit">
</form>

Where questionStatus is my dropdown field handle.
Any insight would be appreciated
Thanks

Update

I have ensured that the account's user type has the necessary permissions to perform this operation


texts: Guest Entries - How I can send message to user after saving form information

texts: I use Guest Entries plugin to add information, and I need to send some message to user who filled the form to email. Can you show me an example of how I can do this?


texts: Sharing a template with identical category and tag name

texts:
I'm trying to stay as DRY as possible here and sharing one template for a news list view; all, category and tag all sharing the same template (and trying to refrain from having a category or tag segment). My query isn't returning any results when the segment 2 (in this case the url encoded tag or category slug) when there is a tag and category that share the same name. Example, 'design' is a category for design related posts; 'design' is a tag for posts that featured a design service within the 'portfolio' category. My template code is below. Is there a work around here or do I need to have a second segment for tag/category (i.e. .com/news/category/design and .com/news/tag/design - or one or the other to differentialte)

{% if category is defined %}

    {% set newsPosts = craft.entries.section('news').relatedTo(category).limit(5) %}

{% elseif tag is defined %}

    {% set tag = craft.tags.groupId(3).name(tag).first() %}

    {% set newsPosts = craft.entries.section('news').relatedTo(tag).limit(5) %}

{% else %}

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

{% endif %}


texts: Issues using the elements service in console commands

texts:
I'm having trouble getting the elements service working correctly in a consolecommand. The same code works as expected in a controller, so I expect there is either a bug, or some extra config I'm missing.

<?php
namespace Craft;

class ShoppingCommand extends BaseCommand {

    public function actionListOrders() {
        $c = craft()->elements->getCriteria(ElementType::Entry);
        //$c->locale = craft()->i18n->getPrimarySiteLocale();
        $c->section = 'orders';
        $c->limit = 5;
        foreach($c as $o) {
            print $o->orderId . ": " . $o->title . ", " . $o->price . "\n";
        }
    }
}

running this results in the following

$ ./app/etc/console/yiic shopping listorders
: blah,

running the same action with a Controller in the webapp results in the expected output:

10: blah, 123

Anyone have any ideas if it's possible to get around this? For now I can just build my functionality into a controller, but it would be much more convenient if I could run it from the command line like this.

Also, there is another issue with this relating to the locale. Originally I needed to use the commented out line above because my site's default locale was en where as the consolecommands default to en_us and without forcing the locale my queries were not returning any results at all. I changed my default locale to en_us to test whether the other issue was something to do with the locales as well, but it didn't make a difference.

Cheers

-Tristan


texts:
I have an image in a matrix-field, but can't get the url from it.
dump(block.image.one().url) says NULL. My code is:

{% if entry.hero %}
  {% for block in entry.hero %}
    {% if block.type == 'hero' %}
      {% set heroImage = block.image.one() %}
      <div class="cell hero center padding-1" style="background-image: url({{ heroImage.url }});">
      </div>
    {% endif %}
  {% endfor %}
{% endif %}

image.one() or image.first(), as well as .url or .getUrl() doesn't work the same.

What works though is {{ block.image.one().folderPath }}{{ block.image.one().filename }}

Does anyone know why? I'm on Craft CMS 3.3.15


texts: Is it possible to use environment variables as the cache duration?

texts:
I'm trying to set a cache duration as an environment variable.

I set up various environment variables and know they are being referenced correctly in my templates because I can print out the values of the variables in my templates.

return array(

    '*' => array(
        'environmentVariables' => array(
            'cacheDuration'          => '1 week',
            'cacheDurationQuantity'  => 1,
            'cacheDurationUnit'      => 'week',
        ),
    ),
);

I initially started with this cache tag...

{% cache for craft.config.environmentVariables.cacheDuration unless craft.config.devMode %}...{% endcache %}

...but I got this error:

  Unexpected token "name" of value "craft" ("number" expected)

This had me thinking that perhaps Craft or Twig is expecting an integer immediately after the "for" keyword. Thus, I broke my cacheDuration variable into two parts: quantity which is an integer and unit which is a string.

{% cache for craft.config.environmentVariables.cacheDurationQuantity craft.config.environmentVariables.cacheDurationUnit unless craft.config.devMode %}...{% endcache %}

I still got same error as above. This inspired me to try:

{% set duration = 1 %}
{% cache for duration craft.config.environmentVariables.cacheDurationUnit unless craft.config.devMode %}...{% endcache %}

This time, I got a slightly different error.

  Unexpected token "name" of value "duration" ("number" expected)

This has me thinking that any variable evaluated as expected in the duration parameter of the cache tag. However, other variables (like craft.config.devMode) are interpreted fine for other parameters of the cache tag.

Can anyone else confirm this or share insight into this?


texts: Internal Server Error after upgrading from craftcms 2 to 3

texts:
I just upgraded from Craft 2 to 3.6.14 (latest). I was able to successfully to the upgrade. I am able to get into the admin and was even able to install the feed-me plugin. I ported over all the files from the CraftCMS 2 to 3 (in a different folder) including the templates. When I try to hit the '/' URL (base URL), I get Internal Server Error with the following error.
2021-05-14 16:54:35 [-][1][a509bc948c7d5994a4c25b2437cf0413][error][TypeError] TypeError: Argument 1 passed to craft\web\twig\TemplateLoader::_resolveTemplate() must be of the type string, null given, called in /var/www/vendor/craftcms/cms/src/web/twig/TemplateLoader.php on line 72 and defined in /var/www/vendor/craftcms/cms/src/web/twig/TemplateLoader.php:108
Stack trace:
#0 /var/www/vendor/craftcms/cms/src/web/twig/TemplateLoader.php(72): craft\web\twig\TemplateLoader->_resolveTemplate(NULL)
#1 /var/www/vendor/twig/twig/src/Environment.php(299): craft\web\twig\TemplateLoader->getCacheKey(NULL)
#2 /var/www/vendor/twig/twig/src/Environment.php(381): Twig\Environment->getTemplateClass(NULL)
#3 /var/www/vendor/craftcms/cms/src/web/twig/Environment.php(41): Twig\Environment->loadTemplate(NULL, NULL)
#4 /var/www/vendor/twig/twig/src/Environment.php(513): craft\web\twig\Environment->loadTemplate(NULL)
#5 /var/www/vendor/twig/twig/src/Template.php(317): Twig\Environment->resolveTemplate(Array)
#6 /var/www/storage/runtime/compiled_templates/c7/c79cfef91787ef30e09834a18460ca59f19b243431dce3423759312bdef2fce8.php(38): Twig\Template->loadTemplate(Array, '', 1)
#7 /var/www/vendor/twig/twig/src/Template.php(405): __TwigTemplate_31142054de6396a6abc4e01d6b275a8aef55865011e7064f16ec0f90eaa4b945->doDisplay(Array, Array)
#8 /var/www/vendor/twig/twig/src/Template.php(378): Twig\Template->displayWithErrorHandling(Array, Array)
#9 /var/www/vendor/twig/twig/src/Template.php(390): Twig\Template->display(Array)
#10 /var/www/vendor/twig/twig/src/TemplateWrapper.php(45): Twig\Template->render(Array, Array)
#11 /var/www/vendor/twig/twig/src/Environment.php(318): Twig\TemplateWrapper->render(Array)
#12 /var/www/vendor/craftcms/cms/src/web/View.php(389): Twig\Environment->render('', Array)
#13 /var/www/vendor/craftcms/cms/src/web/View.php(450): craft\web\View->renderTemplate('', Array)
#14 /var/www/vendor/craftcms/cms/src/web/Controller.php(257): craft\web\View->renderPageTemplate('', Array, 'site')
#15 /var/www/vendor/craftcms/cms/src/controllers/TemplatesController.php(100): craft\web\Controller->renderTemplate('', Array)
#16 [internal function]: craft\controllers\TemplatesController->actionRender('', Array)
#17 /var/www/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#18 /var/www/vendor/yiisoft/yii2/base/Controller.php(181): yii\base\InlineAction->runWithParams(Array)
#19 /var/www/vendor/craftcms/cms/src/web/Controller.php(190): yii\base\Controller->runAction('render', Array)
#20 /var/www/vendor/yiisoft/yii2/base/Module.php(534): craft\web\Controller->runAction('render', Array)
#21 /var/www/vendor/craftcms/cms/src/web/Application.php(278): yii\base\Module->runAction('templates/rende...', Array)
#22 /var/www/vendor/yiisoft/yii2/web/Application.php(104): craft\web\Application->runAction('templates/rende...', Array)
#23 /var/www/vendor/craftcms/cms/src/web/Application.php(263): yii\web\Application->handleRequest(Object(craft\web\Request))
#24 /var/www/vendor/yiisoft/yii2/base/Application.php(392): craft\web\Application->handleRequest(Object(craft\web\Request))
#25 /var/www/web/index.php(26): yii\base\Application->run()
#26 {main}

I have tried to look for a solution pretty much everywhere. I have spent over 4 hours looking for a solution. I don't want to individually create entries in the new Craft 3 folder. Any suggestions or tips?


texts: How would I list all entries regardless of section or structure?

texts:
I'm trying to build and XML site map that sorts all entries by their modification dates with the newly modified first.

{% for entry in craft.entries.find() %} ignores the structures,

{% for entry in craft.entries.section().find() %} returns the same as above,

{% for entry in craft.entries.section('mainPages').find() %} returns the structure as expected.

Looking for a way to include everything in a single, sortable query.