texts:
The Craft documentation on Section Types state that they themselves are created using a Structure. Can someone explain the method they used here?

What I'd really like to see is the Twig code for the left hand navigation. Are there multiple Structures here (to account for the headings) and if not, how are the headings set?

Thanks!


texts: Redactor fields not saving more than 252 characters?

texts:
I haven't set any kind of character limit on my Redactor fields, but when I save a longer body of text, is always cuts it off at 252 characters. See screenshots:

Before save:

After save:

Here is my Redactor config:

{"buttons":["format","bold","italic","lists","link"],"plugins":["customstyles"],"formatting":["p","h3","h4","blockquote"],"linkNewTab":true,"toolbarFixed":true,"customStyles":{"style":{"dropdown":{"sourceCitation":{"args":"cite"},"strikethrough":{"args":"del"},"superscript":{"args":"sup"},"subscript":{"args":"sub"}}},"clearStyles":{"api":"module.inline.clearformat"}}}

EDIT: I have also noticed that if I save it with one spare character remaining, the WYSIWYG is inserting a symbol on save to fill the last spot?! Compare the previous screenshot with the next one and you'll notice i've just knocked off the final 't' and the space has been filled with a random symbol. This is sometimes an ampersand.

After save minus the last character:

Note that this is only happening on a production site and not locally.


texts:
I have this form

    <form method="post" enctype="multipart/form-data">
        {{ csrfInput() }}
        <input type="hidden" name="action" value="entries/save-entry">
        <input type="hidden" name="entryId" value="{{ entry.id }}">

          Listing Title
          <input type="text" name="title" class="form-control" value="{{ entry.title }}">

   </form>

Is it possible to add a delete button to this form or will it have to be within another form targeting a different end point for entries?


texts:
I have a client who needs to list product "Bundles" as individual products. So basically, there would be products x, y, and z, all with their own SKU, and then bundle A with it's own SKU. Bundle A is all three products (x, y, z) at a discounted price. When Bundle A is purchased, the SKU is sent to their ops and packaging team (we have an integration from Commerce to their warehouse software).

The thing is, only bundle A's SKU is sent on purchase, which is fine because the warehouse team know what products belong to what bundle. However, the products in the bundle (x, y, z) have variations.

Is their some reasonable to add a product connection field to the variation of the Bundle? The issue is that the Bundle SKU would need to stay the same, but the customer needs to able to pick the variations of the related products that are in the bundle and have it stored in Commerce for the warehouse team to manually check. I'm a little lost on how to handle this. Basically, when a bundle A is ordered, their needs to be some way to store what variations of the related products were chosen for the bundle. Any suggestions, or am I missing some basic feature that would cover this?

Edit

Due to the rush of this job (customer wants this for the shopping season) I'm thinking this (thoughts or comments asked for):

Make a Variation text field (bundleChoices) for the bundle. On the bundle add-to-cart page where all products in the bundle are listed, use Javascript to stop the add-to-cart button, collect the bundle's product's variation choices and skus, and fill in a hidden (bundleChoices) field. Then add the bundle product with plaintext data describing the product variations chosen for this bundle.

Edit

We've decided to drop product variants in a bundle product. So if you buy a bundle, you get product x variant a, product y variant f, and product z variant q, no substitutions on the products normal options. To accomplish this, a bundle product will have a field for SKUs where just copy and paste the variant SKUs you want attached to the bundle.


texts: Display a Matrix field block entry when the block's entry exists

texts:
I have a videoPost block in a Matrix field. Each videoPost has a imageField. I am trying to display the block’s image if imageField is defined. This is returning images for each block that has imageField defined when I only want to return the specific block’s image.

{% for block in entry.matrixField.type('videoPost') %}
    {% if block.imageField | length %}
        {% for asset in block.imageField %}
            <img src="{{asset.getUrl}}" alt="{{ asset.title }}" />
        {% endfor %}
    {% endif %}
{% endfor %}


texts: How can I access a template variable from an include that is loaded via ajax?

texts:
I am making an ajax request to an entry. It is returning the entry's html - and all is working great.

I have a section called "portfolio" and I loop through each:

portfolio/index.twig

{% set projects = craft.entries.section('portfolio') %}
...
{% for project in projects %}
    ...

    ...
{% endfor %}

When the project is clicked, I am making an ajax request to an entry. It is returning the entry's html - and all is working great.

Now I would like to strip out the static html, and access the parent's entry variable.

For example, here is the html that I am returning.

portfolio/_entry.twig

My Project

            {# image will go here. #}

My Project Description

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas eros dolor, efficitur lobortis eros et, dictum hendrerit nulla.

Client: My Client

What I would like to do is:

...

{{ project.title }}

I'm not sure how to do is something like this from within portfolio/_entry.twig

{% set project = ?? %}

So that I can use {{ project.title }}

Thank you for any suggestions!


texts: Switch Twig condition Case with OR condition (two values in the case)

texts:
I got a Twig switch in a template like:

{% switch bodyClass %}

    {% case 'A' %}
        ...

    {% case 'B' %}
        ...

    {% default %}
        ...

{% endswitch %}

I would like to add another possible value for the first case.
So I would have case 'A' or 'C'.

Is it possible in Twig syntax?

=================================
EDIT CRAFT BUG ?
OK lets try to rephrase, sorry for my english not easy to explain for me sometimes :)
So when the or syntax is added, then the 2nd and 3rd cases B or default (after 'A1' or 'A2' case) are never reached anymore.
The switch always say TRUE to 1st case (even if it is wrong...).

{% switch bodyClass %}

    {% case 'A1' or 'A2' %}
        ...

    {% case 'B' %}
        ...

    {% default %}
        ...

{% endswitch %}


texts:
Can I disable template caching for local development?
For example: setting a environmentVariable in a config file?
Or is this possible in the future?


texts: What's the best way to move a lot of assets from local to S3 and keep relations

texts: My client has a catalogue website with a big amount of assets. What's the best way to move the assets from local to Amazon S3?


texts: Is there a way to hide the menu item that plugins add to the control panel menu?  As seen in the picture below, I do not need the "DashCols" link in my main menu, but would like to keep the plugin installed.


texts:
I hope someone can help me to understand this.

I have a Channel called eg. "My channel". In that channel i have two entries: Post 1 and Post 2. Those two entries have different titles and content.

If I go to "my-channel/post-1" in the browser, and then to "my-channel/post-2" they have the same content based on the Post 2 (last created entry).

If I make "Post 2" inactive, then Post 1 will have the correct content.

What am i forgetting here?


texts: Need .last() functionality for categories – .last() will be deprecated going forward

texts:
I have a matrix block that calls a category channel. The categories are nested three levels "deep" at times. I want to select first, second or third level links as needed.

When I use .last(), I can get the full url path to return. When I use .nth(n), I have to specify a value, which automatically limits the link path to that level of "deepness".

What can I do to get the .last() functionality, without using .last()?

Note: .last() will be deprecated going forward in Craft 3 and beyond.


texts:
Just migrating a site from 2 to 3 and stuck on this little call, cannot find anything in the docs at all.

Matrix field, Entries.

<a href="{{ entry.featuredProjectLink.getUrl() }}">

Cannot for the life of me find the equivalent/new way in the docs.

TIA


texts: Calling plugin controller externally fails with 500 error

texts:
UPDATE: Question edited to be clearer.

I had an issue where it seems calling a plugin’s controller via an URL caused the site itself to throw a 500 error (i.e. not being accessible at all).

The plugin loads external cinema events (as an XML) and creates entries for films and shows. I’ve made it accessible in the CP, where I hit a button to update, and it will return a log which gets printed out in the CP. Triggering it from the plugins page in the CP works perfectly. Now I wanted to create a cronjob that loads the external data on regular intervals – basically calling the plugin. After some trail and error, I managed to make the plugin’s controller callable from the outside.

So my question is – is there anything special to be aware of when calling plugins from the outside? Is there a difference if it’s called as a cronjob or if it’s done manually through the browser.

Here is the code of the controller:

<?php
namespace Craft;

class UpdateProgram_ProgramController extends BaseController
{
  // Allowing to be called without being logged in
  protected $allowAnonymous = true;

  public function actionUpdate()
  {
  // Disabling having to call the plugin by POST, to access directly by URL
  // this->requirePostRequest();

    $log = craft()->updateProgram_program->update();

    // If there are entries in the log, changes have happened
    if ( count($log) ) {
        craft()->userSession->setNotice(Craft::t('Program updated.'));
        craft()->urlManager->setRouteVariables(array(
           'log' => $log
        ));
    }
    // Otherwise, give an error message
    else {
        craft()->userSession->setNotice(Craft::t('Nothing to update!'));
    }
  }
}

And this is how I'm calling it from the cronjob:

MAILTO=[my.email@address]
# Run updateProgram every night at 3am
0 3 * * * wget http://[my.site]/actions/updateProgram/program/update > /dev/null

When trying it from the browser, I used the same URL


texts: Missing 'Plugin Store' tab in admin panel

texts:
I'm using Craft 2.7.9 and can't access the Plugin Store page. I've searched for fixes here but didn't find anything helpful.

I've tried to access it directly via http://localhost:8888/admin/plugin-store but I got an error:

  Page Not Found The requested URL was not found on this server.

However, I'm not sure if the link is the same for Craft 2? That one I know from Craft 3.

Any ideas why is it missing? Need to install and test one plugin, tried to upload it manually to plugins folder but unfortunately that didn't work too.

Thanks!


texts: Is there a plugin, similar to https://wordpress.org/plugins/broken-link-checker/ or other Wordpress plugins, that can test links in the database and report which ones are broken? It doesn't have to be pretty or fancy.


texts:
I have a set of checkboxes to show content on a page. I have one instance where I'd like to show something if either checkboxes are selected. I have searched around but couldn't find how to combine multiple value. Here's what I have now

{% if entry.pageOptions.contains('testimonials') %}

And I want it to be something like:

{% if entry.pageOptions.contains('anotheroption|testimonials') %}


texts:
Is it possible to include an A&M Nav menu in an entry?
I know Wordpress uses shortcodes for such things.  I see there is also a shortcodes plugin, but is it difficult to adapt A&M nav into that?


texts:
I am using Craft on Ubuntu 12.04 servers without problems, but when trying to run it on Ubuntu 14.04 (trusty) I always get the message

  Mcrypt is required.

I installed it, however, via...

apt-get install apache2 php5 mysql-server php5 php5-cli php5-common php5-curl php5-gd php5-mcrypt php5-mysql

...and restarted the web server afterwards. Any hints? Maybe this is a bug with the way craft checks for mcrypt?


texts: Looping through a Global with a Matrix field

texts:
This might be a very simple question but I am pretty new to Craft with a EE background. Basically, I have a global containing contact details that use a matrix field, I’m literally just looking for the syntax to loop through the matrix blocks.

I have tried similar code to the successful matrix fields I have in other areas, but how do I reference the particular global? This is what I’ve attempted with no success:

{% for block in contactDetails %}
    {{ block.location }}
    {{ block.address }}
{% endfor %}

contactDetails being the name of the global. I’m sure this is very simple I just can’t figure it out.


texts:
I'm sure it's obvious, but how do I get the current site name from within a plugin?

I tried a few things, including

craft()->systemSettings->getSettings('general')

Any ideas?


texts: What are the risks of using Gmail for sending email from Craft CMS?

texts:
In Craft's documentation for email it says:

  Gmail might be a good option depending on your appetite for risk.

But I don't see anything about what the risks are. Is there a risk of getting hacked, or just an increased likelihood of messages not getting through?

I have a small and internal user base, so Gmail might work for me, but I'm trying to make a quick decision and this is making me have to dig for info so I don't make a bad call.

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


texts: Why can't users upload files in this asset?

texts:
I've two user groups; admin and user. The User group does not have access to the Assets tab, which stops them from just browsing all the assets that anyone might have uploaded - which is what I want; no random looking about in the Assets resources.

I've a field type 'Featured Image' that is an asset; and it is restricted to a single upload folder, file type image, with an upload location set to {slug} - this means it will upload files into a folder named the same as the slug for the entry in which it's being used.

It works fine for admins who have privileges to see Assets. I can not upload anything in this field with a user of type User.

This behaviour makes Asset fields essentially useless unless the user group also has privileges to view (and upload/edit) all assets site-wide. Because 'upload' is a child privilege of 'view assets' I can't give the upload rights without also giving them 'browse all the assets everywhere' rights.

I'd like these restricted users to be able to upload in that field.

Oddly, I have a Matrix field called Gallery which has an asset field inside it, set to file type image, single upload directory; {owner.slug}/gallery/

That asset field works fine for these users, and they are able to upload into it.

Anyone have any ideas?

I'd hoped this would be fixed in 2.3, alas it seems not, unless there's something I need to change?

Here's my experience as a mini screencast, logged in as a restricted user type (no assets privileges): http://viewcreative.co.uk/DELETEME/uploading.gif And here's the filetype set up and permissions: http://viewcreative.co.uk/DELETEME/permissions.gif


texts: Custom Plugin Field Using Wrong Template Path

texts:
I'm trying to build a simple dropdown field with a pre-populated set of options, so I figured I'd just import most of the methods from Craft's native Dropdown field. The plugin name is siteutilities and the field name is Regionselect:

namespace kgrote\siteutilities\fields;

use kgrote\siteutilities\SiteUtilities;

use Craft;
use craft\base\ElementInterface;
use craft\fields\BaseOptionsField;

This pulls in the code from craft/vendor/craftcms/cms/src/fields/BaseOptionsField.php.

So now I want to render a custom settings template for my plugin:

public function getSettingsHtml()
{
    return Craft::$app->getView()->renderTemplate(
        '_components/fields/Regionselect_settings',
        [
            'field' => $this,
        ]
    );
}

But I get a Twig error:

  Unable to find the template
  “_components/fields/Regionselect_settings”.

My plugin file structure looks like this:

kgrote
|-siteutilities
  |-src
    |-fields
    |  |-Regionselect.php
    |-templates
    |  |-_components
    |    |-fields
    |      |-Regionselect_settings.html
    |-SiteUtilities.php


texts: Uploaded 8-bit PNGs losing alpha transparency (using ImageMagick)

texts:
I found searching through other questions here that:

  Currently the images are being cleansed on upload, which means that
  they are being re-saved to make sure that no malicious code is
  injected in them.

The problem I have is that optimized 8-bit PNGs with alpha transparency (like the ones TinyPng creates) are transformed on upload to indexed, non-alpha transparency PNGs - and as a result they look very bad.

I'm not even using any transforms, so this is just from the "cleansing" that Craft does automatically on upload.

I initially was using the GD library but then I installed ImageMagick and even forced Craft to use ImageMagick through the config setting - nothing helped

Image uploads work just fine with ImageMagick, except the PNG issue described above.

Is there something I need to configure in the ImageMagick library or it's PHP plugin? Or can I disable the "cleansing" that Craft does? (I don't want to do that since I love the added security, but I really need to use transparent, compressed PNGs in my website designs).

Thanks in advance!

Edit: Here's a PNG image, before and after upload (just posted the links, since theimage is big and I didn't want to mess up the thread):

Before the upload - shows as RGB mode in Photoshop - has alpha transparency. Was saved as PNG 24 from PS then compressed with TinyPNG

After the upload - shows as Indexed mode in Photoshop - no alpha transparency - was re-saved by Craft on upload from the CP.


texts: Custom Fieldtype with Checkboxes - Remove value and set to null when checkboxes are left blank

texts:
I created a custom field type to show user groups in a checkbox layout, e.g. (http://cl.ly/image/0A1a140m031h).

I am running into one small issue. If I add content with a checkbox(s) option selected and save the entry. Then I try to edit the entry and uncheck all the options, the entry will still have the original checkbox options selected and won't return to the null state as expected. I was trying to use prepValueFromPost but that doesn't seem to run unless the value is set. How do I fix this?


texts: How to I set the location folder of Control Panel resources?

texts:
I'm trying to use the ./craft clear-caches/all CLI command.

Everything is working fine, except that I always get this error:

  Error clearing cache Control Panel resources: Unable to clear Control
  Panel resources because the location isn't known for console commands.

How can I set this resources folder?


texts:
I am trying to insert a div that'll call an ad between two paragraphs of copy text.

However, I'd like to do it only one instance. The current replace code I'm using is this - which is inserting my test code multiple times.

    {% set str = block.bodyText %}
    {{ str | replace('

', '

') | smartypants }}

Is it possible?


texts: Using Symbolic Links for Very Large Image directories

texts:
I'm converting an EE site to Craft. During the conversion we are establishing LOCAL > DEV > LIVE environments and using GitHub.

LOCAL = My local MAMP PRO setup.
DEV & LIVE = a single account at Arcustech.
    DEV = ~/www/dev_html/public
    LIVE = ~/www/public_html/public

The site currently has 354,000 images/thumbnail files in the /images directory. We'll eventually move images/assets to S3/Cloudfront, but for now/launch we're keeping them local.

Obviously I don't want to duplicate 354K images in the DEV directory, AND keep them sync'd, but want the DEV to correctly display images/assets for the client to see.

So I was thinking a /images symbolic link in DEV, pointing to /images in LIVE would maintain all the correct image/asset paths and display for the DEV site and Craft configs?

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


texts:
I have a directory structure in place that I'd like to mimic in Craft. File uploads are first categorised by Year, then by month so the directory sturcture is like such

-- 2014
---- 01
---- 02
---- 03
---- 04
---- 05
---- 06

I've tried this but it still only uploads to the root folder I setup in sources

/uploads/{postDate.format('Y')}/{postDate.format('M')}

Am I using the wrong syntax? Do I need to use now | date ('Y') instead?


texts:
I have a matrix with only one block type. and it only has videos ID's it (videoID).

I would like to have this videoID in the url and then fetch the corresponding Matrix Row.

http://www.example.com/segment-1/segment-2/videoID

That said: I know I could get the matrix row ID like this:

{% set test = craft.myMatrixField.id(craft.request.lastSegment()) %}
Video Id: {{ test.videoID }}

But as the ID will change when reordering the matrix, I would like something more Permalink like and use the videoID in the URL.

Anybody knows how to achieve something like this?


texts:
How do I display a variable in my template?

I have the following code:

<?php
namespace Craft;

class HelloPlugin extends BasePlugin
{
    function getName()
    {
         return Craft::t('Hello');
    }

    function getVersion()
    {
        return '1.0';
    }

    function getDeveloper()
    {
        return 'Richard G.';
    }

    function getDeveloperUrl()
    {
        return 'http://example.com';
    }

        public function hasCpSection()
    {
        return true;
    }

}

plugins/hello/variables/HelloVariable

<?php
namespace Craft;

class HelloVariable
{
    // property
    $message = 'Hello, World";"
 }

plugins/hello/templates/index.html

{% extends "_layouts/cp" %}

{% set title = "Hello World"|t %}

{% set content %}

MessageVariable  {{ craft.helloPlugin.HelloVariable.message }}

{% endset %}


texts:
I've got a problem where siteURL wasn't working for a localized version of my site. I have a site in two languages — Russian and English, with Russian exposed under www.mysite.com and English under www.mysite.com/en/.

My problem was that siteUrl variable was always giving me a non localized version of the site URL (www.mysite.com instead of www.mysite.com/en/) on the pages in English, even though other localized features were working fine (strings were translated into English, correct entries output etc.). See below for the solution.


texts:
I can find examples of prev/next style pagination but none of creating proper numeric-style pagination (eg. how Google do it).

Does anyone have an example I could use?


texts: Getting the first category of the deepest level for an entry

texts:
I want to get the first category of the deepest level for an entry.

For example if the category structure looks like this

Ocean Life > Fish > Gold Fish

I want "Gold Fish"

Here is what I've come up with so far. Is there a more elegant solution that I'm missing?

            {% set primaryCategory = entry.categories.level(3).first %}
            {% if primaryCategory is empty %}
                {% set primaryCategory = entry.categories.level(2).first %}
            {% endif%}
            {% if primaryCategory is empty %}
                {% set primaryCategory = entry.categories.level(1).first %}
            {% endif%}


texts: A hash key must be followed by a colon (:) syntax error

texts:
Trying to get entries between two dates and am getting: 'A hash key must be followed by a colon (:). Unexpected token "operator" of value "~" ("punctuation" expected with value ":")'

{% set posts = craft.entries({
    section: animal,
    orderBy: "postDate" })  %}

{% set puppyAnimals = posts({
    animalDateOfBirth: 'and',  ">= " ~ now|date , '<=' ~ now|date_modify('-1 year')|date })  %}

It's Craft 3 so I may just have the syntax wrong.


texts: Assign User to Group While Importing on Sprout Imports

texts:
we are trying to import users into a specific group but cant figure out how the json should go. Currently we have:

[
    {
        "@model": "User",
        "attributes": {
            "username": "name@example.com",
            "firstName": "john",
            "lastName": "smith",
            "email": "name@example.com",
            "pending": "0",
            "lastLoginDate": "2017-08-11 04:12:06",
            "dateCreated": "2017-11-06 12:04:04",
            "dateUpdated": "2017-11-06 12:04:04"
        },
        "content": {
            "fields": {
                "customField": "00000"
            }
        },
        "settings": {
            "groups": {
                "groupId": "1"
            }
        }
    }
]

We've tried several variations on settings, permissions, and putting groups under content and attributes but nothing has worked so far.


texts:
My orignal website is a Onepager but I am creating a individual news page.

Is it possible to extend a block to another page taking over the content from that single? I have a block filled with a really big Matrix field which I cant have on my other page cause I only need a small amount of content from it. This content is placed inside a block so I need to extend just that block.

What I need is to extend the {% block navigation %} and not the entire page

See it as this:

{% block navigation %}
  {% for block in entry.blokken %}
    {% if block['opnemenInNavigatie'] is defined and block.opnemenInNavigatie %}

        {% if block.navigatieNaam | slugify == 'news' %}

          {{ block.navigatieNaam }}

       {% endif %}

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

And also this:

{% block content %}
    {% for block in entry.blokken %}
        {% include 'blocks/' ~ block.type ~ '.html' %}
    {% endfor %}
{% endblock %}


texts: Using a loop in a loop, how do I check if child loop is empty to not display parent loop?

texts:
I'm trying to display a list of names alphabetically ordered. This is working fine, but I also want to check if the name is intoCollection or not (using a Lightswitch).

If it is intoCollection, it displays the letter + the list of names related. If there is no name related to the letter, I need to display nothing (= no letter).

Here is the code which seems good for me, but is not correct:

{% set artists = craft.entries.section('artists').limit(null).order('title') %}
{% for letter, letterEntries in artists | group('title|upper|slice(0, 1)') %}

    {% for entry in letterEntries %}
        {% if entry.intoCollection | length %}

{{ letter | upper }}

            {% for entry in letterEntries %}
                {% if entry.intoCollection %}

{{ entry.title }}

                {% endif %}
            {% endfor %}

        {% endif %}
    {% endfor %}

{% endfor %}

It displays letters duplicated, but also letters that contain no names...

Any idea? Thanks!


texts: Charge Model "amount" and "userId" not always populated

texts:
I'm using the onCharge event to populate a separate purchases table that I can query elsewhere (combining both stripe and my other Paypal payments system).

The onCharge event is mostly working, but it's not populating the $chargeModel->amount.

It's also not populating the $chargeModel->userId if a new user is being registered (it only populates if there was a previously existing user).

Any idea why the charge model wouldn't have all of its information during the onCharge event?

Here's what I have in my plugin:

craft()->on('charge.onCharge', function(Event $event) {
    // Adding New Charges to Purchases Table
    craft()->purchases_newPurchase->addChargePurchase($event->params['charge']);
});


texts: Add fields/custom fields to page in the admin page (backend)

texts:
following situation: let's assume I have page with some ARTICLES (textfields): Article1, Article2, Article3, etc..

Now is there a module for CraftCMS that I can add textfields (articles) to a page directly in the backend (admin page)? So when I want to add a new article, then I don't have to do this with PHP or else.


texts: What are the consequences of choosing structures over channels?

texts:
I want to build an international directory of fishing port centres in Craft. Each port will have the same custom fields and be geocoded.

The documentation here just doesn't make clear the ramifications of choosing channels versus structures. I get the ordering of structures which makes me think structures is the right approach. But do we lose out in search/RSS/templating down the line or are all entries equal in terms of there later usage?


texts:
I'm building out a front end form that users will use to fill out with their information. Naturally, when a user first signs up, their profile fields are empty and a blank space appears for them to add in their info later.

This works well on all fields on my form except the table field type. If nothing has been entered the loop will simply display nothing. I've been reading through this answer, but so far checking is empty or |length is not working on my form.

Here's my current loop, which works great as long as the info is entered through the CP. How do I get an empty table field type to display on the front-end so a user can update their profile?

    Institution
    {% for row in currentUser.providerCredentials %}
      <input type="text" id="accreditingInstitution" class="name-field" name="fields[providerCredentials][0][col1]" value="{{row.accreditingInstitution}}">
    {% endfor %}


texts: Craft not loading custom 404 template for errors

texts: Whenever I hit a non-existent page on a dev site, I only get Craft's native 404 page, not the one I have at /craft/templates/404.html. The site has no routes. Any ideas why this might be?


texts: What is the difference between siteUrl and baseUrl?

texts: What is the difference between siteUrl and baseUrl in Craft 3? Is there any?


texts: Create a route to display entries with multiple tags

texts:
I understand how to set up a route and template that allows me to display entries by tag.

But how can I set up a template + route to grab multiple tags (if supplied but could just be one) from the url and display entires that have these tags?

I would also like to add a category element (showing all the entires from a category with the selected tags) but suspect much of that may be answered by the first part.

For example

Have a form the builds a url depending on user selections

mysite/queryurl&tags=cheese,egg,bacon&cat=sandwich

Is this possible?


texts: Craft Setup 3.6.5.1 with MYSQL with SSL version 5.7.29

texts:
I'm trying to install Craft version 3.6.5.1 with MYSQL version 5.7.29 from Azure.
While setup it fails with the following error
Testing database credentials ... failed: SQLSTATE[HY000] [9002] SSL connection is required. Please specify SSL options and retry.


texts: What's the difference between setting cache with {% header %} tag and {% cache %} tag?

texts:
I've came to a cache problem/question on one of my sites when I run a speed test and I failed caching test. I have very little knowledge in this area and I'd like to enhance it.

Documentation for {% header %} tag says that it set a new HTTP header in response and you can tell browser what to do (for example caching a page).

Documentation for {% cache %} tag say that it will cache a portion of your template.

So what's the difference in setting cache in HTTP header using {% header %} tag and {% cache %} tag?


texts:
I have a client who requires more advanced formatting options than the current Redactor editor provides, like editing table cells, merging cells, background colors, etc.

My plan is to integrate CKEditor into Craft as a custom field type and a plugin - and basically switch out the current limited editor with CKEditor.

Has no one else needed a more advanced editor than the stock?  Am I heading down the wrong path?


texts: Set active class on parrents in a structure?

texts:
I have a section (structure) called "blog" but "blog" is not in the URL.

I have entries like:

Entry 1a
--Entry 1b
----Entry 1c
Entry 2a
---Entry 2b

A navigation like:

Overview <- a template in the root directory
Entry 1a
Entry 2a

I need to set "Overview" to active on all entries.
Entry 1a should be active if itself or child's are shown.
Entry 2a should be active if itself or child's are shown.

Doing this by hand for all entries would be a pain:

{% if craft.request.firstSegment == 'Entry 1a or Entry 1b' %}active{% endif %}


texts: How do I set up same site to use two different subdomains?

texts:
I have to set a the same site on two different subdomains. I have the two subdomains included in the config.php. But that doesn't seem to work. Is there any other configurations I need to set?

// internal
'sub1.website.com' => array(
    'overridePhpSessionLocation' => true,
    'environmentVariables' => array(
        'siteUrl' => 'https://sub1.website.com/',
        'fileSystemPath' => '/var/www/html/'
    )
),
// external
'sub2.website.com' => array(
    'overridePhpSessionLocation' => true,
    'environmentVariables' => array(
        'siteUrl' => 'https://sub2.website.com/',
        'fileSystemPath' => '/var/www/html/'
    )
),


texts:
I'm super new to Craft and was wondering if someone could help.

I'm trying to set up a hero banner. So there will be a full-width image, on top of this will be the heading text and a CTA button.

I'd like the background to be editable by the user so have set up a field for this called 'hero image'. This is how it looks now but it doesn't seem to be working:

                            {{ entry.description }}

                        {{ entry.buttonText }}

I'm so confused!

Any help would be greatly appreciated!


texts:
Element API, query entries where relationship field ':empty:' AND the same relationship field with specified entry ID.
Can't seem to figure out how to do this without performing two separate queries and merging the objects together. However I don't see a way to perform this within the Element API.
The answer to this other question seems like an approach? Option 1 or Option 2? Not quite sure as this looks all foreign to me with sparse documentation, and it's not specific to my issue.
How can I query entries based on a Matrix Block Type?
Seeing as you can't use ':empty:' with relatedTo, I'm stuck here.
return [
    'criteria' => [
        'section' => 'mySection',
        /* this is the myRelatedField entries field relating to other Section Entry ID */
        'relatedTo' => (['targetElement' => $otherSectionEntryId]),
        /* unable to use :empty: with the relatedTo, incorporating myRelatedField :empty: below will return zero results */
        /* cannot use this below */
        'myRelatedField' => ':empty:'
    ],
    'transformer' => function(Entry $entry) {
        return [
            'title' => $entry->title
        ];
    }
];

UPDATE with further testing. Various tests used below in trying to use simple relations with :empty:. It looks as though ':empty:' is ignored when utilized in an array.
// results returned where relationship field is empty
'relatedDrinks' => ':empty:'

// no results returned where relationship field is empty
'relatedDrinks' => [':empty:']

// results related to drink ID returned
'relatedDrinks' => [$myDrinkId]

// results returned for drink ID, no results returned with empty
'relatedDrinks' => [':empty:', $myDrinkId]


texts: Show just the first row of a table (stored in globals)

texts:
Morning Craft folks, I've had a look and play but can't seem to find an answer for this.

I have a global variable with a company's various phone numbers in, stored in a table field.

The table shows the city, then the phone number for the company's numbers.

For the navigation, I want to show just the first phone number in the table.

.first() and .limit(1) don't seem to work in this situation.

    {% if companyDetails.telephoneNumbers | length %}
        {% for row in companyDetails.telephoneNumbers %}
            {{ row.number }}
        {% endfor %}
    {% endif %}

    Call us

Many thanks in advance.


texts: Triggering different webhook when product is updated by Feed Me

texts:
I have two different webhooks that need to run when a product is saved.

Webhook 1 should only run after manually saving the product

Webhook 2 should only run after Feed Me saves the product

Is there any way to differentiate these save events? They both have the same Sender Class, Event Name, and Event Filters. I tried using the Debounce Key Format but all that did was always run Webhook 2 and never Webhook 1.


texts: Plugin using event listener throws error using $this

texts:
I have written a plugin to hook into an event raised by a contact form plugin. I am running PHP 5.6 locally, and the plugin works just fine. Moving the code to a server running 5.3 (which I cannot change) leads to an error. My init() looks like this:

public function init() {

   /* Intercepts the Capture form submission */
   craft()->on('capture_submissions.onBeforePost', function(Event $event) {
      $data = array(
         'email_address'   => $capture_data['email'],
      );
      $result = $this->addMember($data);
}

When submitting the form, I get the following error:

Fatal error: Using $this when not in object context in /home/mysite/craft/plugins/myplugin/MyPlugin.php on line 69

By changing the plugin to use MyPlugin:: instead of $this-> leads to an error in Craft core:

Fatal error: Using $this when not in object context in /home/mysite/craft/app/etc/components/BaseSavableComponentType.php on line 41

What is the correct way to call my plugin methods when running as an event listener?


texts:
I have a field in my users of type user. This field holds a user's employer (another user).

How can I get a collection of all the employees in a plugin?

I tried craft()->users->relatedTo($currentUser); (where $currentUser is the employer) as that's pretty much how I'd do it in a template, but of course relatedTo isn't part of the usersService.

So how can I do this without just getting every user, checking their employer field and filtering out the matches?


texts: How do I render pages with dynamic content from a json feed

texts:
I am building a module to show a job/vacancy-list and the detailpage of a job, the data is fetched from a remote json feed.

Currently I have the following routes to a controller in my module

return [
  'job' => 'job-offers-module/job/process',
  'job/detail' => 'job-offers-module/job/detail',
];

And loading twig templates eg.

namespace modules\joboffersmodule\controllers;

use Craft;
use craft\web\Controller;
use craft\web\View;

class JobController extends Controller
{
  protected $allowAnonymous = true;

  public function actionProcess(){
    return \Craft::$app->view->renderTemplate('joblist');
  }
  public function actionDetail(){
    return \Craft::$app->view->renderTemplate('jobdetail');
  }
}

But I keep getting an error that the entry can not be found... Do I need to register the paths in the module as a handle?

How can I load an entry from my within the module and pass it to the templates?


texts:
I have a portfolio page for a client that has a simple two column grid of images. However, I'd like to set it up so that it creates responsive images via the excellent Imager plugin.

I have the following code below so far. However, it's only outputting the first image from the Matrix. So I need it to output all the images the client drops in.

So need a little bit of help to tweak the code to output all images please?

{% for block in entry.portfolio %}
    {% switch block.type %}

    {% case "images" %}
    {% set image = block.portfolioImage.first() %}
    {% set transformedImages = craft.imager.transformImage(image,
      [
          { width: 1200, ratio: 4/3 },
          { width: 992, ratio: 4/3 },
          { width: 768, ratio: 4/3, jpegQuality: 60 },
      ],
      {
          format: 'jpg',
          allowUpscale: false,
          mode: 'crop',
          jpegQuality: 80,

          interlace: true
      }
    ) %}
    {% if image | length %}
    <img class="img-responsive"
         src="{{ transformedImages[1].url }}"
         sizes="50vw"
         srcset="{{ craft.imager.srcset(transformedImages) }}"
         alt="{{ image.title }}">
    {% endif %}

    {% endswitch %}
{% endfor %}


texts: Entries from previous year 2016 not displaying

texts:
Ok, so this is pretty bizarre... Entries from 2016 are NOT displaying when searched for in the admin panel. Whether we search by the year, title, or part of the title, until they're edited (using the id to access them).

I see entries from 2015 and 2017 but only a few from 2016 which, as I said, are the ones we managed to edit.

This happens in the list of entries as well as on fields that link to them and we've got LOTS of entries...

UPDATE - Check this out:

Articles listed from December 2016:
https://www.dropbox.com/s/o0rmkiazm436etb/Screenshot%202017-10-22%2009.16.07.png
Searching for name of article:
https://www.dropbox.com/s/ydwilwz6pye1jb4/Screenshot%202017-10-22%2009.16.44.png
Searching for year 2016, bottom of results, all 2015 and 2017:
https://www.dropbox.com/s/w7imwnnfyrnjjri/Screenshot%202017-10-22%2009.17.15.png
If i access the article highlighted on screenshot 1, via URL:
https://www.dropbox.com/s/opdv12hpyz993z4/Screenshot%202017-10-22%2009.20.50.png

The articles are there, they're accessible from the user end, but for some reason they won't show up on the Admin side. Bizarre...


texts:
I written a plugin which doesn't work on PHP 5.3 but does work on 5.4

It doesn't seem to be even routing to the function as if I I add a die("dead") to the controller function I still just get a 500 error if using ajax or a blank page if going straight to the actions URL

The craft requirements say PHP 5.3 and above, is this not the case for plugins?


texts: Craft 2: Serve language / locale i18n according to user agent

texts:
As the official documentation does not give any hints on this:

I am wondering how to serve the correct localization of my website according to the user’s language preference and/or browser/OS language with Craft.

From other platforms/plugins I know that this is done through user agent detection, e.g. if the browser/OS is English you’ll get the EN, if it’s Spanish you’ll get the ES version of the content, etc.

The project I am working on has DE as the primary locale and the language switcher shall only appear subtly within the footer. Non-German visitors should automatically get the EN version without having to interact with any interface element.

How can I implement this?


texts: Get the current entry element in the CP (edit entry view)?

texts:
You can listen to entries.onSaveEntry or entries.onDeleteEntry events and then get or modify
the entry via $event->params['entry'];.

But how would I get the entry element and its properties in the event that a user starts editing
an entry in the CP? I don't (necessarily) need to modify them, simple access is ok.

As far as I can see, there's no event available for this. And if I understand correctly,
only P&T can add such an entries.onBeforeCpEditEntry
event (which would probably go into Entries Controller actionEditEntry function).

If you do entry edits using front-end forms this is easy, but not so from within the CP it seems.
Is there anything I overlooked, or is this simply not possible and maybe worth a feature request?

-

This question is related to this one: "How to reference the current entry element in custom Control Panel templates?"
but it's not quite the same. The solutions / workarounds I posted below have some drawbacks, so I'm still looking for a better solution!


texts: How do I add class to redactor format list?

texts:
I understand that to add a "note" class to the redactor text editor drop down, I need to use formattingAdd. But each iteration I've tried does not work. The example is: https://imperavi.com/redactor/examples/formatting-add/

I used the example, edited it for my needs, and added it to the header of my layout template on the Craft site...

<style>
.article-note {
  font-style: italic;
  font-size: 1.2em;
  font-weight: 700;
}
</style>

<script>
    $(function()
    {
        $('#redactor').redactor({
            focus: true,
            formatting: ['p', 'blockquote'],
            formattingAdd: {
                "article-note-add": {
                    title: 'Note',
                    args: ['h6', 'class', 'article-note', 'toggle']
                },
            }
        });
    });
</script>

Didn't work. Also, I didn't know how the textarea in the example is used or where it should go.

A lot of people in the discussion boards I've researched have recommended plugins. I am not interested in a plugin. Both Craft CMS and redactor state that there is a way to do it without a plugin. While it hasn't worked from me so far, I'm sure someone has succeeded and I'm hoping to learn.


texts:
I'm currently redirecting all requests to https. I've updated the siteUrl variable and all of my entry links have been correctly updated but the image links are still http.

When I go to the admin panel all of the CSS/JS files wont load because the site is trying to load them over HTTP instead of HTTPS.

server {

  listen   443;

  root /var/www/<url>/htdocs;
  index index.php index.html index.htm;

  ssl on;
  ssl_certificate /etc/ssl/cert.crt;
  ssl_certificate_key /etc/ssl/rsa.key;
  server_name <url>;
  proxy_set_header X-Forwarded-For $remote_addr;
  proxy_set_header X-Forwarded-Proto https;
  client_max_body_size 10M;

  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/opt/remi/php55/root/var/run/php-fpm/php-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
  }

  location / {
  try_files $uri $uri/ @rewrites;
  }

  location @rewrites {
    rewrite ^(.*) /index.php?p=$1 last;
  }

  # Errors

  error_page 404 /index.php;
  error_page 500 502 503 504 /50x.html;

  location = /50x.html {
    root /var/www/<url>/htdocs;
  }

  # Enable gzip compression
  gzip on;
  gzip_comp_level 2;
  gzip_http_version 1.0;
  gzip_proxied any;
  gzip_min_length 1100;
  gzip_buffers 16 8k;
  gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

  # Disable for IE < 6 because there are some known problems
  gzip_disable "MSIE [1-6].(?!.*SV1)";

  # Add a vary header for downstream proxies to avoid sending cached gzipped files to IE6
  gzip_vary on;

}


texts:
I am wondering if you can offer some help with an issues I am having. I am using Freeform Lite and I have a hidden field with the entry title as the value.

Is it possible to use that value for sending email notifications dependant on the value.

Basically I want to use that hidden field so that I can send the notifications to the location email address e.g. Bishopbriggs to bishopbriggs@hellocovault.com and Bellshill to bellshill@hellocovault.com etc.

I have tried the dynamic recipeint field but I can't get that to pre select the correct option.

You can see the form here - http://hellocovault.com/locations/bellshill


texts: Get all elements (entries) where a field exists

texts:
I'm developing a plugin and I'm searching a way to get all entries where a field exists (by id or handle).
I'm trying to get all the entries even if the value of the field is null, empty or text.

I can't find a way to that. Can somebody help ?


texts: PHP version issue when installing Craft 3 using Composer

texts:
Why do I get the error when I try to install Craft 3?

composer create-project craftcms/craft Documents/Development/Project -s beta

The error:

[InvalidArgumentException]
Could not find package craftcms/craft with stability stable
in a version installable using your PHP version 5.6.30.

I am running PHP 7.1.


texts: Commerce: How can I check that a user has bought a product?

texts: I have a digital product, with a landing page, and I want to know if the connected user has already bought the product so I can give him access to the content.


texts: How do I configure Varnish to work with Craft?

texts: Has anyone successfully used Varnish with a Craft build? I'm trying to set up Varnish on my server but I'm very new at this. Can anyone share their config file or point me in the right direction? We have this build on an EC2 instance and so far it works great but we'd like to optimize it further.


texts: How do you prevent white space from being removed after line breaks within a Rich Text Field?

texts:
I am utilizing a CSS class within headlines for responsive line breaks. This class shows the line break for large displays and hides the break for small displays.
Using the HTML/Source button within Redactor works fine until the entry is saved.
Line breaks were the first thought.
 Not an afterthought.

The code above produces this for large displays:
Line breaks were the first thought.
Not an afterthought.
And should produce this for small displays:
Line breaks were the first thought. Not an afterthought.
However the white space after the line break is removed upon save, which produces this:
Line breaks were the first thought.
Not an afterthought.

Which displays like this on small displays:
Line breaks were the first thought.Not an afterthought.
This is not the desired result.
While I am able to correct this with the Twig replace filter, I would prefer not having to manage those filters within the templates.
Any clue how to prevent the original white space from being removed after line breaks within a Rich Text Field?
(Note the white space is not removed within Plain Text Fields.)


texts:
I'm nearly there on this one but could use some help. I want to list all User Groups, with all Users listed under each group. For bonus points, this all needs to be alphabetical (Group, then Users). Something like...

User Group A

User Name A
User Name B
etc...

User Group B

User Name A
User Name B
etc...

Here's what I have so far...

{% set userGroups = craft.userGroups.getAllGroups() %}

{% if userGroups|length %}
    {% for userGroup in userGroups %}
        <h2>{{ userGroup.name }}</h2>
        {# list all users for this group #}
    {% endfor %}
{% endif %}

I just can't figure out how to loop through users for a userGroup.


texts: Ordering Entries without using entry date

texts:
Looking to explore solutions for ordering entries in a channel. My current ideas are:

For example purposes let's say this is for recipes and the client wants to be able to pick the order of recipes by some method other than changing the date of the recipe.

1. Add a matrix field, with blocks as entry fields ( for recipes channel ) on the single section (recipes index), where you can select and reorder the entries. Then loop over matrix field to print out the recipes in that order.

Pros: Very easy drag and drop sort.

Cons: Every time a new recipe is added, it as to be manually added to the matrix field.

2. Add a custom field to the recipe channel entry as an integer. Use that integer to sort the entries.

Pros: No extra field on a single section that is somewhat de-coupled from the recipe channel.

Cons: As far as I could find, there is no way to add a column to the entries overview page on the backend of Craft, so you would have to go into each entry and make sure to not have duplicates of the same number. If you wanted to add a new entry at spot 5, and you already had 10 entries, that would be very tedious.

We are brainstorming today, and thinking about what we could make plugin-wise that may add this kind of functionality as well. Will post more info if I come with anything else.


texts: Is it possible to manually clean the database caches for templates? Doing it from the CP becomes stuck.


texts:
I am using CraftCMS 2.

Beside the admins, I have 2 user groups: Employees and Editors. As admin I can activate pending Editor accounts by clicking on 'Activate account' in the corresponding user account. However, this button is not available for non-admins (Employees), even if the non-admin has all permissions of the user module. I understand that there is no way to make this button available for non-admins in control panel.

Question: Is there a way to make this action ('Activate account') available for Employees through a frontend form? Ultimately I want Employees to be able to activate pending Editors manually.

Basically I want to do the same as Jeremy A but with non-admins.


texts: TwigExtension added to Craft don’t work in emails

texts:
I added tomodomo/twig-pluralize-extension to my project composer, loaded with a custom module like that :

if (Craft::$app->request->getIsSiteRequest()) {
    // Add in our Twig extension
    $pluralize = new \Tomodomo\Twig\Pluralize;
    Craft::$app->view->registerTwigExtension($pluralize);
}

I use this to pluralize some string in my templates and email templates. When I check the url to my email template, everything work fine but the email didn’t send out because of "unknown function pluralize".

I have another custom module (to handle something else in my emails) and this part work fine.

Do I need to register/declare TwigExtensions with another method to get them work in emails ?

Note:

The only error related to my emails in the logs is about pluralize
function missing.
Everything work fine if I don’t use |pluralize


texts: Is a migration needed if defineContentAttribute is changed from false to an AttributeType

texts: My plugin's FieldType was initially setup with defineContentAttribte set to false.  I and switching it to AttributeType::Mixed. Does a migration need to be written to account for this change? If so how would this be written since it is the specific input name that is added to the content table?


texts: Pulling blog entries related to a structure entry field type

texts:
fairly new to craftCMS. I've wrestled with this now for hours and exhausted all research avenues.

I have three main "service pages" (Web Design, Digital Marketing, Hosting & Analytics) These are top level Structure pages, each with 5 entries - for example Web Design/Web Development, Web Design/User Experience, Digital Marketing/Inbound, Digital Marketing/SEO, etc. etc.

I have set up an 'entries'field type called 'blogServices' that uses the three main service pages as the parent source, and allows me to select the child pages with no issue. So for instance, if I write a post about Web Development, I can select the 'Web Design/Web Development entry with no problem and have it show up as a related service on the blog post.

Where I am running into a roadblock is I want to pull up 3 most recent blog posts on my 'Web Design' index page. However, I want to be sure that the three most recent posts fall under one of the five 'Web Design' child service entries (side note: Each blog post can also fall under multiple services as well).

Any help with showing me how to filter out only these posts on the index page is of course greatly appreciated. I've been trying the 'relatedTo()' function with no luck at all.

Thank you in advance.


texts: How to get an input value without refreshing with twig?

texts:
One way to read a dynamically inserted value is to refresh the page and get it in a twig variable through the url, something like this:
{% set amount = craft.app.request.getQueryParam('amount') %}

But I am looking for a solution to get a value inserted into an input without refreshing the page, of course, after sending the form (i thing). Do you know if thats possible? Maybe with javascript.


texts: Assume my website (developed using Craft, of course) is expected to have 1000 concurrent access. How many MySQL db connections would be required to open? Does Craft control this or does it depend on program code?


texts:
I regularly use srcset to serve large images, such as heroes, and take advantage of Craft's image transform capabilities in the implementation, e.g. <img srcset="{{ image.getUrl('img500') }} 500w,...etc.
Curious to know if anyone has a clever solution for doing this when images are stored on AWS? I know I can still use transforms, but they will be saved on the webserver, not AWS. I could create subfolders in my AWS bucket and manually scale the images, but that is obviously not an ideal solution.
Thanks for any insights!


texts:
I'm working on a multilingual website where I have one structure called Products. Currently, this structure's URI format is configured like this:
{parent.uri ?? section.handle}/{slug}

Which returns URLs like this:
/products/topLevelProduct1
/products/topLevelProduct1/nestedProduct1
/products/topLevelProduct1/nestedProduct2

/products/topLevelProduct2
/products/topLevelProduct2/nestedProduct1
/products/topLevelProduct2/nestedProduct2

etc

The main thing I'm struggling with now is: how do I translate the top-level part of the URI (i.e. /products)? I guess I could use the built-in t() function on section.handle (is that even a good idea?) but that would still be overwritten by parent.uri.


texts: includeCssFile and includeJsFile doesn't output {{ siteUrl }}

texts:
It seems that when calling a CSS or JS file include, if the path contains {{ siteUrl }} it outputs {{ siteUrl }} in the html that is generated.

Like so;
<link rel="stylesheet" type="text/css" href="{{ siteUrl }}css/styles.css"/>

Which should be (for example);
<link rel="stylesheet" type="text/css" href="http://site.url/dev/css/styles.css"/>

Anything I'm missing here?


texts:
Is it possible to prevent a coupon code from also discounting the shipping costs associated with an order? We've run into a situation where a customer cart totaled $0 after they used a coupon code we configured to only work on a specific type of product which also had a separate discount available to it.

The minimum order total was met because this calculates before other discounts (in this case, it's a volume based discount).

Example:

Item: $25 ea
QTY: 75

Subtotal: $1650
Volume Discount: 15% off over 20
New Total: 1,402
Shipping: 85
Special code for customer: -$1500
Order total: $0

What we hoped here was the order total would come to $0 + $85 shipping but I am not seeing any way to do this with discount configurations. I'm hoping I am just missing something or there is some snippet I can add somewhere to prevent this from calculating this way in the cart.


texts: need file extension in url to access template

texts:
I've got a structure setup, and one of the entries under it is called "Our people" at the top level, in the "About" structure. So the url would look like this: /about/our-people.

I have a template setup at: craft/templates/about/our-people.html

When browsing /about/our-people it does not route there, though /about/our-people.html works fine.

In my general config I have 'omitScriptNameInUrls' => true set.
Only weird thing I have is a "Single" entry is setup to deal with the top level "about" page viewable at /about.

Any ideas?

Thanks!


texts:
I'm trying to set up craft to run with the docker images provided here. When I run docker-compose build, it gets through a few lines in the Dockerfile and then stops with an invalid reference error after these three lines:

ARG PHP_VERSION
ARG PROJECT_TYPE
FROM php:${PHP_VERSION}-${PROJECT_TYPE}-alpine

I do have php installed, but somehow the arguments aren't getting through to docker correctly. Has anyone gotten the docker images from that repo set up/integrated properly?
I'm no docker wizard so apologies if this is some really simple docker thing.


texts: Include CSS file inline rather than as a link

texts:
I use a pre-processor to generate my CSS. I would like to include the resulting file inline, rather than as a link. Is there a way of doing this  via the twig tags in Craft?

I know I could move the CSS file to the templates folder, so that I could use the include function, but is that the only and/or preferred method of achieving what I want to do? Or am I just best moving the inlining into my pre-processing? Thanks!


texts: Sprout Forms: Populate checkbox field options with entry data

texts:
I have a form with a checkbox field. I want the options of the checkbox to be pulled from an entry field.

My custom field template is below but it wont pass validation. I guess this is because Sprout looks for the option values to validate but as they are populated from an entry it wont pass??

At the moment the example below is successfully displaying the entry data as options in the checkbox, it just wont allow me to submit the form.

{% if handle == "checkboxes1" %}

        <div
                {%- if id %} id="{{ id }}"{% endif %}
                {%- if class %} class="{{ class }}"{% endif %}>

            {% if name is defined and (name|length < 3 or name|slice(-2) != '[]') %}
                <input type="hidden" aria-hidden="true" name="{{ name }}" value="">
            {% endif %}

                {% for date in entry.eventOccurrences %}

                <label for="checkboxes1-{{ loop.index }}">

                        <input type="checkbox"
                        data-value="{{ date.date }}"
                                {%- if name %} name="checkboxes1"{% endif %}
                                {%- if id %} id="checkboxes1-{{ loop.index }}"{% endif %}
                                {%- if value %} value="value-{{ loop.index }}"{% endif %}
                        >

                        &nbsp;{{ date.date }}||

                </label>

            {% endfor %}
        </div>

{% endif %}


texts: Performance when loading lots of Elements but only need limited data

texts:
The performance of the ElementCriteriaModel for lookups is killing me.

I have 300 or so "People" entries in a craft site and trying to load them just for a basic listing page takes forever. There's just so much overhead.

In this case of i.e. a listing page, I need the entry title, slug and an image field (which I'm eager loading). I don't need all of the other fields and overhead it loads.

Is there a way to get more acceptable performance for cases like this specific one (listing page with large number of entries and limited data needed)? Or am I going to have to bypass the element criterea stuff and do the lookups myself in SQL?

Thanks


texts:
What is the best way to create a simple (one level) navigation that also have active class?

My section types are singles only for now.

Thank you


texts: Is it possible to add white background to transformed images?

texts:
For a client eCommerce project I am working on all the product images are on white backgrounds, so they blend nicely with the background of the site. Currently I am putting all the images through a fit transform (480px by 480px), so that parts of the image aren't cut off.

The images are of different shapes and sizes and are transformed something like this (the grey area is the actual visible product part of the image)

However, I am trying to achieve something like this, so all the images are 480px by 480px, and the visible content is slap bang in the middle. Anything extra is added as whitespace to make all the images the same dimensions.

Is this something Craft can do and I am just being a dolt?

Update

At the risk of this question being closed as off topic, please note that I am not looking for a CSS/JS related answer for this.

I'm trying to find out if there is a way Craft can process the images for me, perhaps with ImageMagick or something similar to achieve what I am hoping for.


texts:
Does anybody successfully implemented a language switch run Craft 3? Trying the Craft 2 variant slightly adjusted but still running into issues: Invalid site handle: nl

{% set otherLocales = craft.app.i18n.siteLocaleIds|without(craft.locale) %}
{% for locale in otherLocales %}
   {% set localeEntry = craft.entries.id(entry.id).locale(locale).one() %}
    {#  set localeCategory = craft.categories.group('worksCat').locale(locale).first #}
    {% if localeEntry.locale is defined and localeEntry.locale == locale %}

            <img src="/{{ craft.app.i18n.getLocaleById(locale) }}.svg"  {{ craft.app.i18n.getLocaleById(locale).nativeName }}

    {% else %}

             {{ craft.app.i18n.getLocaleById(locale).nativeName }}

    {% endif %}
{% endfor %}


texts: How can I set new user accounts to pending status in a Craft 3 module?

texts:
I have the following code in my site module:

Event::on(
    User::class,
    User::EVENT_BEFORE_SAVE,
    function (ModelEvent $event) {
        /** @var User $user */
        $user = $event->sender;
        if ($event->isNew === true) {
            $user->pending = true;
        }
    }
);

It was working as expected until I updated from Craft 3.0.25 to 3.0.27.1

I think this issue is related to a change in the src/controllers/UsersController.php file as per GitHub https://github.com/craftcms/cms/commit/db089251994329d0fbe082c0d3ff234a01d82c98

Also, I replaced my 3.0.27.1 UsersController.php with one from a 3.0.25 install, and my code works again.

What is the best/correct/official way to set new user accounts to pending status in a module that won't break with future Craft updates?

I tried this:

Event::on(
    Users::class,
    Users::EVENT_BEFORE_ACTIVATE_USER,
    function (UserEvent $event) {
        $event->isValid = false;
    }
);

but got There was a problem activating the user. when trying to activate the user account.

P.S: Verify email addresses? is disabled in User Settings.


texts: Recognizing Twig tags in VS code live server

texts:
I'm not sure if this is the correct place to ask this, but seeing as I'm developing with Craft I thought I'd give it a try.
Does anyone know if it's possible for the Live Server plugin for VS Code to recognize Twig tags? When I launch the Live Server plugin it seems to be showing the tags on page such as:
{% block ... %}
{% endblock %}
{% extends .... %}

Are these kinds of tags supported by Live Server?


texts: How is a typical frontend request output generated?

texts:
Long story short: I've been trying to find out how Craft processes the request and eventually create the output. The search is going deeper and deeper into the core, but it feels like I'm missing out on something.

Is it possible for a plugin to 'fetch' the (full) output of a page generated by Craft?


texts: LJ Dynamic Fields unable to output title

texts:
I’m using the LJ Dynamic Fields plugin and have a dynamic multi select setup for the client to select predefined tags, which is working all fine in the cms using the following code.

{% for tags in craft.tags.group('default').limit(null).order('title') %}
{ "value":"{{ tags.id }}" , "label":"{{ tags | raw | capitalize }}"
}{% if not loop.last %},{% endif %}
{% endfor %}

However, in my template I can only seem to output the id, but I want the tag title. I’m using the following code in my template:

{% for tags in entry.tagsMultiSelect %}
{{ tags }}
{% if not loop.last %}, {% endif %}
{% endfor %}

Can anyone tell me where I’m going wrong?


texts: Tried to update to new version. Website and admin went down, error message states "Undefined class constant 'Client'". How to solve this message?


texts: Instructions for Using Craft "Embedded Assets" Plug-in?

texts:
I'm trying to use the "Embedded Assets" Craft plug-in to embed Youtube videos in my content, but I can't figure it out. I've read through the instructions on the Github page, and I've looked at other resources online, but it's not working and I can't make sense of it.

I have successfully installed the plug-in, and it seems to be "grabbing" the videos correctly because a thumbnail for the video appears when I enter the URL for it in the "Embed link" Asset selection. These are also saving in their respective fields when I enter them into an Entry.

Where I'm having trouble is understanding how to integrate them into my templates; the only configuration I changed was the 'extraAllowedFileExtensions' => 'json' setting in the general.php file. It said something else about configurations in the documentation, but it was very vague and said their should already be defaults in place. I tried dropping the code in that they suggested, as well, and played with the values a bit, but it's just empty space when I preview the page (or it breaks the page altogether).

Here is the code I tried to put into my template in different forms (tried the given loop, not looping, and etc.):

{% for asset in assets %}
    {% set embed = craft.embeddedAssets.fromAsset(asset) %}
    {% if embed %}
        {{ embed.safeHtml|raw }}
    {% endif %}
{% endfor %}

If you care to write an example, the handle for the field I'm using is embeddedMediaUrl and the embed links are stored in assets/mediaEmbeds (not sure if this info is needed or not.)

Any and all help with this will be greatly appreciated. I apologize if this is vague, but I've been messing around with it long enough that it seemed time to reach out to the community to see if someone could give me some help. Thank you.


texts: Why is Craft hanging every time I try to save an entry?

texts:
I just upgraded to the latest version of Craft.  I can login and create a new entry, but then it hangs when I try to save it.  I can't even stop and go back to the entries panel.  I have to exit out of Safari or Chrome and go back in.  Sometimes it has saved the entry and other times it has not.  There are no error or pop of notification of any sort.

And by hang - I mean seizes up and freezes for about 5-10 minutes ...and sometimes creates a duplicate entry.


texts:
I just check the CMS. It looks great.

One question about the Globals: Where could they be used?

I found them in a Navigation-Example. Do you have other examples for me?


texts:
Scenario 1: A language other than English is selected.
New website.com visits will be in that language.
Even after switching back to English, websites will continue to load in the previous language.

Scenario 2: Website sticks to English on new visits regardless of which language is picked.

Scenario 3: A different language is selected.
New website visits will remain on that language until another one is chosen.

Is there any way to disable saving of language cookies so as to always reproduce scenario 2?

Thanks in advance


texts: Copy uploaded image in event assets.onSaveAsset

texts:
Is there a way to copy an uploaded image in the assets.onSaveAsset event?

I want to make a copy of the original uploaded image (for internal purposes) and after that I want to add a copyright text on the uploaded image (for displaying on webpage).

UPDATE
Some more info, to prevent missunderstandings: I use the BusinessLogicPlugin. Users can upload a picture which should be stored in S3. First I want to make a copy of this picture and after that to the picture should be added a small text. The copy works fine.

But now I want to modify the uploaded image.

My Code:

craft()->on('assets.onSaveAsset', function(Event $event) {

  static $recursionLevel = 0; // is set only once

  if ($recursionLevel == 0 ) {

    if ($event->params["isNewAsset"]) {
      $recursionLevel++;

      $asset = $event->params['asset'];
      $remoteFile = $asset->getUrl();

      // get remote image and store in temp path
      $imageInfo = pathinfo($remoteFile);
      $tempPath  = CRAFT_STORAGE_PATH . 'runtime/temp/' . $imageInfo['basename'];
      file_put_contents($tempPath, fopen($remoteFile, 'r'));

      // only JPEG allowed
      $im = @ImageCreateFromJPEG ($tempPath);
      $textcolor = imagecolorallocate($im, 0, 0, 255);
      // add text and save to original path
      imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);
      imagejpeg($im, $tempPath);

      // update the image, but how?!

    }
  }
});

How can I update the asset with the new generated file in $tempPath?


texts: Is it possible to load different "_layouts" with ajax for certain pages?

texts:
I've followed this tutorial by Zack Spear. It leaves your website with a header and footer that stay constant while the body of the page is loaded in through AJAX when you change pages.

Is it possible to have different _layout templates used for different pages with this approach or can it only be one? Could I hide the header on certain URLs? Could I show a secondary menu on specific urls?


texts: Receiving PHP Warning on move to Production

texts:
I am moving a client site from my staging VPS to my clients preferred hosting. All of Crafts requirements check out just fine:

PHP Version 7.0.29
MySQL Version   10.2.12-MariaDB-log

However, when going to either admin or main homepage I get the following warning:

Wrong parameter count for class_alias()

The file it is pointing to is /craft/app/vendor/twig/twig/lib/Twig/LoaderInterface.php(57)

What am I possibly missing?

My VPS has the following settings:
PHP Version 5.6.36
MySQL Version   5.6.39


texts: Restrict viewing front end to specific group permissions

texts:
How can I restrict content frontend to specific user groups?
There seems no sensible way to do this out of the box.
For example group permissions in CP are all about CP - there is no view option.

Never had a use case for this before today but have one now and finding Craft3 coming up short :(

Scenario is a support portal where different companies can provide user specific content. Idea is login with company id (done that ok via a plugin) but then once logged in they get redirected to content for that specific company.

So I have two probs now: redirect to company 'home page', and restrict access to content. I've considered splitting content into sites and pairing users with sites. I've considered section root parent and checking permissions for top of tree in twig. I'm thinking restricting per section is best and adding company homepage as entry field in user field or user group field and managing access via plugin + twig but its all feeling very heavy handed....


texts: Is there a way to import recipients into a list in Sprout Email?

texts: I have a couple of excel sheets with a list each of recipients for my e-mail campaigns. Is there a way to import that into Sprout Email? If not, I would really appreciate a pointer to where I could look to start hacking/building my own importer.


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

texts:
I'm getting white blank page when trying to access my website and Craft login page. I haven't updated the website for few months. So I assume no files has been changed.

I checked with the hosting provider, and they say everything is okay on their part.

So I turned on the Dev Mode. And it came back with this error :
Fatal error: Class 'Craft\HttpRequestService' not found in /home/alpw7814/craft/app/framework/YiiBase.php on line 213

What could possibly cause this? Is there anything I need to check?
Thank you in advance.


texts:
This works for me, but i would like to solve this with ajax without reloading the page. Choosing the values from the Dropdowns and submit the data per POST Method, so i can return the value with "getParam( name )". This question is related to my own question Reuse chosen dropdown field value on frontend

{% set field = craft.fields.getFieldByHandle('jahrgang') %}

<form action="tourdefrance.html" method="post">
   <select class="dropdown" name="modelljahr" size="1" onchange="this.form.submit();">
     {% for opt in field.settings.options %}
        <option name="fields[myFieldHandle][]" value="{{ opt.value }}">{{ opt.value }}</option>
     {% endfor %}
   </select>

{% set modelljahr = craft.request.getParam('modelljahr') %}
{% set entries = craft.entries.section('mountainbikes') %}

<form action="tourdefrance.html" method="post">
  <select class="dropdown" name="modell" size="1" onchange="this.form.submit();">
    {% for entry in entries %}
      {% if entry.jahrgang == modelljahr %}
        <option value="{{ entry.title }}">{{ entry.title }}</option>
      {% endif %}
    {% endfor %}
  </select>

{{ craft.request.getParam('modell') }}

Thanks a lot!


texts: Three duplicated guest entries posted on form submision

texts:
I was doing some design tweaks to the form today, barely touched coding parts and than I went for a test run to see if it submits an entry.
Everything run as it was on the front end except on the back end I got 3 same entries created with ascending IDs every time an entry is posted.

I was going through and through the form for hours, but ... aaargh!

If anyone has a theory of the issue without seeing the code, post it here please. Otherwise I will submit the code. It's extensive thought.


texts:
I have a matrix field with one block type. In that block type, I have one field that is a related entries field.

How do I access the title from the related entries field from the matrix field?

Here is the setup I have:

Entry name is programs
In that entry I have a matrix block with handle name menuLinks
In that block, the related entries field name is called menuLink.

Thanks


texts: How to limit number of entries returned from a group filter?

texts:
I'm wondering how I would go about limiting the number of results returned from a set using the group filter? I only want four to show, but using the limit() method seems to throw errors wherever I put it. Here's my template code:

{% set entries = craft.entries.section('recipes').find() %}

{% for category, catEntries in entries | group('cuisineType.first().title') %}

    {% for entry in catEntries %}

       // I only want four entries shown here

    {% endfor %}

{% endfor %}


texts: URL rewrites not working return Apache 404's

texts:
Content is accessible via example.com/index.php?p=page-name but not via example.com/index.php/page-name or example.com/page-name.

The .htaccess and 'omitScriptNameInUrls' => true are both in place but still no luck.

Any ideas?


texts: Craft request returns null in test, but works locally

texts:
I have a search that is working locally, but not when I push it to my test environment.

I imported the database from my local environment into test, so the data should exist.

The URL for each is:

test: https://mytesturl/site/?q=test

local: http://local/site/?q=test

I set the query, which returns null/empty in test, but populates correctly locally:

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

I'm drawing a blank what could be wrong. Seems to be a config issue, but I'm not sure where to look.

Any ideas? Thanks!


texts:
Is there a way in Craft to filter assets by an associated category?

In asset settings, one of our asset sources has been given a category field, and those assets have been given a category.

ie; asset source "documentLibrary" has category field "documentType"
and asset "documentOne" has documentType "sitePlan".

I have tried the following variations below:

craft.assets({documentType: "sitePlan"})
craft.assets({documentType: "contains, sitePlan"})
craft.assets({documentType: "LIKE '%sitePlan%'"})
craft.assets({documentType: array('sitePlan')})
craft.assets({count(documentType): '> 0'})
craft.assets({relatesTo: "sitePlan"})


texts: Can't seem to get variables set in controllers

texts:
I think I might be confused by https://craftcms.com/docs/plugins/controllers#posting-to-controller-actions

I have a controller that I want to return a model when validation fails:

$post = craft()->request->getPost();
$requestModel = Micros_AuthModel::populateModel($post);

if ( ! $requestModel->validate())
{
    craft()->urlManager->setRouteVariables(array(
        'requestModel' => $requestModel
    ));

    $this->redirectToPostedUrl();
}

I assumed I would have access to requestModel in the template that posted:

{% if requestModel is defined %}
    {{ inspect(requestModel) }}
{% endif %}

But I that inspect() call never fires.

What am I missing?


texts: How would I change "disabledElementIds" when using createElementSelectorModal()?

texts:
I'm using the createElementsSelectorModal to access certain element types as described by Brandon here

With this implementation, how would I clear out "disabledElementIds"? So that if an Entry is added and then removed I can tell the Modal it should be selectable again.

Thanks!


texts:
Trying to use an image transform (tried in the template itself and in CP) but I'm getting "Image transform cannot be created." when I try to visit the transform url - the image doesn't load on the page. I get a 500 error.
I'm running MAMP Pro on Windows 10, and I've had the same issue before on another PC running MAMP Pro and Windows 10. In the end I had to change to GD instead of Imagick as there seemed like no working solution.
Imagick is loaded and listed in phpinfo within CP. Maybe related, but no thumbnails load when browsing assets in CP either.
I've cleared caches, and updated asset indexes. Neither made a difference. I can upload assets to the site without issue.


texts:
I am trying to use a lookup table technique I saw in a recent Craft Link List post, but getting errors.
The general objective is to auto-generate button text from an array of possibilities using a Matrix block type as a key. Here is my code:
    {% set buttonText = {
    "video" : "Watch the Video",
    "podcast" : "Listen Now",
    "externalLink" : "Visit Site",
    }
%}

{# resource is a Matrix fieldtye #}
{% set resources = entry.resource.all() %}
{% for block in resources %}
    {% set text = buttonText[(block.type)] %}

{{ block.heading }}

{{ block.description }}

        {{ text }}

{% endfor %}

The problem is trying to figure out how to use variable as a key in this statement: set text = buttonText[(block.type)], where buttonText is the array and block.type is the key. The value of block.type is correct and matches the key in the array, so I am guessing the syntax is wrong, but can't get it figured out.
Thanks for any suggestions!


texts: Remove duplicated entries from SuperTable related entries

texts:
Anyone able to assist me with removing duplicates in this example?
So I have a related entries (cables) setup in a SuperTable. Some of these entries are duplicated across different rows. So a cable might be related to the first row in the SuperTable and also row3 and row4.

I want to be able to run through all these cables in any SuperTable row and output the entries just once not duplicated.
So as an example a basic SuperTable setup like this;

{% for row in entry.tests %}
    {% for cable in row.cables %}
        {{ cable.title }}<br />
    {% endfor %}
{% endfor %}

would output this;
BS 7211
BS EN 50525
BS 6724
BS 8573
BS 7835
BS 7629-1
BS 8436
BS 5467
BS 6724
BS 7846
BS 6622
BS 7835

I want to essentially loop through and only display the related entry once. As you can see from the example some entries are duplicated (e.g BS 6724)


texts:
I have a plugin that captures data and stores it as an Element, similar to a log. There can be a lot of Elements created so there is also a way to purge those Elements from the DB. In most cases, the amount of Elements being purged at a given time is reasonable. However, there are some scenarios where a user may be triggering the deleting of tens of thousands of elements.

What is the best way to handle this so that I'm least likely to crash a users site

I'm not sure what the right question to ask is so here are a few areas that a better understanding would be helpful:

Does creating a single job with 10,000 steps use more resources than creating 100 jobs with 100 steps?
If breaking things out into batches makes sense, what is a reasonable batch size for modifying Elements using a job?
Would the need to do different actions lead to a different answer? For example, would the same recommendations hold for modifying Elements and deleting Elements?


texts: "Failed to instantiate component or class" when calling Craft module

texts:
I created a module with the pluginfactory generator. The module is used for generating a zip file with all the files belonging to a project.

In the composer.json file, I added the following:

"autoload": {
    "psr-4": {
      "zipassetscraft3module\\": "modules/zipassetscraft3module"
    }
  },

in the config/app.php I added:

'modules' => [
      'zip-assets-craft-3-module' => \modules\zipassetscraft3module\ZipAssetsCraft3Module::class,
    ],

In the file controllers/DefaultController.php I added a function called actionDownload() as well as a download() function in the file services/ZipAssetsCraft3ModuleService.php

On the website I have a form with the following url as action: https://default.com/actions/zip-assets-craft-3-module/default/download

When I submit the form, I get an error:

  Invalid Configuration – yii\base\InvalidConfigException Failed to
  instantiate component or class
  "modules\zipassetscraft3module\ZipAssetsCraft3Module".

  Caused by: ReflectionException Class
  modules\zipassetscraft3module\ZipAssetsCraft3Module does not exist

I have dumped the composer autoload, but I don't know why it's not working. Any ideas what I need to change to get this working?

This is the file structure of the module:

So the error message says, there is a class missing, in which file is this class looked for?


texts:
The Freeform docs say there is a predefined option for Countries, but I do not see it anywhere in the Field types or existing fields. How does one access this? Using the latest version of both Craft and Freeform.
Thanks!


texts: I'm needing to allow users who aren't logged in to post new entries, but of course it always redirects to login. Any way I can allow saveEntry to be anonymous, preferably for a single entry type?


texts: Assets and S3 - Reduced Redundacy Storage

texts: is it possible for S3 bucket assets to use reduced redundancy storage?


texts:
I can't seem to figure out a good way to see if an Entry has an actual field defined. All the examples I see just to a falsy check for the property name, but this might fail if you have previously defined a field (either by switching Entry Type, or if you modified the Entry Type).
Example:
Entry Type 1 previously had a field called MyFirstField (let's say it's a static table).
I later on concludes that the table was wrong, and hard to work with on some types. So I modify the Entry Type and replace it with MyFirstFieldV2. I still keep MyFirstField on some other type, and I use a shared partial to render this, so I want to check if the current type has MyFirstField, or MyFirstFieldV2 and render it appropriately.
The falsy check works, as long as it is a new entry. If it is an old entry, it will think that it has data for MyFirstField, even though I have removed that field from the type.
Entry type has a fields() method, that returns an array of all fields, but that becomes quite clunky to work with. I guess it would be possible to make some helper that validates the field name against that array, but it feels like there should be an easier way.
Preferably I think the entry should loose all properties that no longer exists on the entry type, but it seems like every entry has a property (albeit null) for each and every field that exists in the system?
EDIT: Regardless whether this is a feature or a bug, what is the appropriate way to check if an Entry Type has a certain field configured? The fields() function doesn't at all return what I expected.


texts:
I'm using a matrix field to allow the author to add products they can link to category pages, but my code:

{% for block in entry.transformerProductNavigation %}
 {{ block.transformer.one.title }}
{% endfor %}

outputs the parent category, can I somehow display the nested category – as you would if it was an entry field and nested entries?


texts:
I have a super strange problem.

I've created three locales: de fr en

I've set up all the necessary steps for a multi language config and everything works fine.

Except in the en locale I get a Variable "xyz" does not exist.

de and fr work just fine but english does not.

The variable is a global field. If I strip my templates from all globals it's working fine.

Otherwise each and every global field throws the Variable does not exist error in the en locale. How is that even possible when the other locales work just fine?

I' cant access the en globals in the control panel. Error: url not found. I guess this is a routing problem.


texts: How to integrate an image haystack replacement technique

texts: I'd like to use a tokenised image replacement technique which is commonly adopted in ExpressionEngine. This is where the author can add image tokens such as {image_1}, {image_2} etc into their content, and these get replaced by images defined in a matrix in the same publish form (with additional information such as image size etc). What technique can I use to achieve this?


texts: Template error on local development when checking entry variable

texts:
I'm working on a english/spanish site that includes a language switcher link in the site footer.

The code for the switcher grabs the currently displayed entry, checks whether a corresponding entry exists in the other locale. If it does exist, the clicking the switcher will link to the corresponding entry. If not, you'll land on the other locale's homepage. If we're already on the homepage, just redirect to the homepage.

The code, simplified, looks like this:

{% if entry.sectionId == 1 %} // The homepage

  // Redirect to homepage

{% else %}

  // Do some checking into whether there's a corresponding entry, etc.

{% endif %}

The problem:

I have some pages on my site that aren't entries, and on these pages, I get a template error telling me that Variable "entry" does not exist

I tried rewriting this code so I'd check if that variable exists first:

{% if entry|length %}

 // Do the previous code

{% endif %}

But this gives me the same error. How can I write this logic so I don't have to rely on the entry variable existing or not, which should presumably avoid the error.

Thanks!


texts: I was wondering if anyone had any experience in installing Moodle to a server that already had a CraftCMS website installed onto it? I've followed the instructions on the Moodle Installation Guide (I put the Moodle files in the CraftCMS template folder) but when I get to the part where I go to http://domain/moodle to install it I get a 404 error. If I go to http://domain/moodle/install.php I get the install file but it doesn't work, I just get a string of text like the PHP isn't executing. I can't find any similar issue's on Moodle's forums so I think that this will have something to do with craft not allowing the PHP?


texts: I was just wondering when it's recommended to set the attributes on a custom model? Would it be ok to set them within the model's constructor or not? I guess it depends on when defineAttributes() is called, right?


texts:
I get an error when trying to load a page occasionally. It appears to have a problem getting the "type" property from a matrix block.

CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]:
General error: 2006 MySQL server has gone away. The SQL statement
executed was: SELECT `id`, `groupId`, `name`, `handle`, `context`,
`instructions`, `translatable`, `type`, `settings`
FROM `craft_fields`
WHERE (handle = :handle) AND (context = :context)
ORDER BY `name`. Bound with :handle='type',
:context='matrixBlockType:6'


texts: Getting started with Craft Commerce 2 subscriptions using Stripe

texts:
I’m new to Craft Commerce and am really having trouble getting started with subscriptions.

I used the example from the docs and nothing happened. When reloading the cp though, it kept telling me "Unable to start the subscription. Please check your payment details." I learned from the docs that "Subscribing a user to a plan requires that the user have a stored payment source." So I added the getPaymentFormHtml bit. Without any success. Not to mention error messages of any kind.

This is my template so far:

{% for item in craft.session.getFlashes() %}

{{item}}

{% endfor %}

{% set plans = craft.commerce.getPlans().getAllPlans() %}

<form method="POST">
    <input type="hidden" name="action" value="commerce/subscriptions/subscribe">

    {{ csrfInput() }}

        {% for plan in plans %}
            <input type="hidden" name="planUid" value="{{ plan.uid|hash }}"/>

            {# Display only if the user does not have a payment soure saved #}
            {{ plan.getGateway().getPaymentFormHtml({})|raw }}

        {% endfor %}

    <button type="submit">{{ "Subscribe"|t('commerce') }}</button>
</form>

I’ve set up a subscription in the cp, added store information and tried a valid testing card from the stripe docs. But even then it keeps giving me the above flash notice.

Could anybody shed some light here? Am I missing anything obvious?


texts: multi environment nginx, how to check $_SERVER['SERVER_NAME']

texts:
I'm trying to have Craft switch baseUrl in general.php based on the environment. The Craft docs tells me to specify the environment in index.php by using logic based on the $_SERVER['SERVER_NAME'] variable.
But this variable doesn't seem to exist in my server environment.

In Craft, neither craft/config/general.php and craft/public/index.php seem to have access to this variable. Where does the $_SERVER['SERVER_NAME'] for each project live and how do I see what it is? Is it supposed to be the same as the server_name block in my nginx config?


texts: What's the best way to degrade gracefully when using a Plugin Variable?

texts:
When providing plugin users with variable containing arguments like {{ craft.pluginname.variable(arg1, arg2) }} what's the best practice for returning something that doesn't throw an Internal Server Error exception for Missing argument 1 or argument 2?

Should this be done as part of the /services/PluginService.php or somewhere else? Is it better to return a nicer Javascript console error (or Craft error log) vs. crashing the page?


texts: What's the correct directory setup for Craft with Vanilla Forums?

texts:
I'm looking in to setting up a new site which has a Craft site in front of the open source version of Vanilla Forums. I'm a bit stuck on exactly where I should put vanilla though, and how to access it on the front end.

At the moment I've got this setup:

/
    /craft
    /public
        /vanilla

But then vanilla's URLs look like http://domain.dev/vanilla/index.php?p= and it seems to conflic with Craft's .htaccess.

I've also seen on another question that someone installed vanilla in the templates directory. Is that better or a bad idea?

Lastly, should I be trying to run the forums under something like domain.dev/forums/, or would it be easier to run it on a subdomain like forums.domain.dev? I'm going to be using the Single Sign On plugin to integrate it with Craft.


texts:
I have a frontend user account registration form and I d like to auto login the user automatically after the account creation.

So the user can choose a subscription plan and pay immediately after, without having to enter his login and password a second time.

I added the parameter 'autoLoginAfterAccountActivation' but it does not work.

Any idea ?


texts: Craft 3 Image quality is terrible after asset upload from admin panel

texts: After I upload an asset (png), the image loses quality. I changed the defaultImageQuality from its default value of 82 to 100 but didn't make a difference. I can't add these assets via FTP as I need users to be able to add them from the admin panel. Any advises?


texts: What's the most user friendly way to create a video block in a matrix field?

texts:
I want to make it super easy for my user to embed a video from YouTube (maybe eventually from other sources) without having to get the iframe code. They should only have to enter the URL for the video, and maybe check a couple of optional settings, and the code will do the rest.

I'm planning to share the snippet and field architecture I develop here to save myself/others time in the future, but if someone else has already done this and wants to share first, even better!


texts: Set Parent Template Defined Content to Output in Child Template

texts:
I have a layout template, we'll call that Template A that is extended by another template, we'll call that Template B that includes another template, we'll call that Template C that includes another template lets call that Template D

So the visually it goes like so:

-Template A

--Template B

---Template C

----Template D

In Template C I define some content such as "Hello World" as well as a bunch of other content.

I do not want Template C to output the "Hello World" content but instead want Template D to decide where it is output as defined in Template C

I'm thinking that somewhere i might should use embed rather than include but i'm a bit hazy on exactly how to achieve this. Any help would be greatly appreciated.

NOTE: The content defined in Template C is defined after Template C includes Template D and also the content that is defined is not just a simple string as indicated above "hello world" but actually much more complex data.

UPDATE: Here is an example of the templates to help better understand the question.

Template C:

{% for block in entry.body.level(1) %}
  {% include 'Template D' %}
  {% if block.children is not empty %}
    {% block child %}
        {% for block in block.children %}
            {% include 'Template E' %}
        {% endfor %}
    {% endblock %}
  {% endif %}
{% endfor %}

Where Template E is the "Hello World" content mentioned above.

Template D:

 {% if block.slide|length %}

             {% for background in block.slide %}

             {% endfor %}

             {% block child %}{% endblock %}

 {% endif %}

And more code also after that endif. Where Block Child (in Template C) is the content to be defined and Block Child (in Template D) is where i want it output.


texts: Loading related entries by category using a select menu

texts:
I have a list of people (entries) who are related to Categories.

I would like to create select menu which will change (filter) the people (entries) shown on the page depending on which category (option) is selected from the select menu.  I would like the default option to show everyone.

I don't mind if this is done on page reload or via ajax but I really don't know where to start with this one :/

Thanks again

Martin


texts: How can I pre-raw a Model attribute for the Twig template? (ie. "myModel.myAttr" without requiring the raw filter)

texts:
I have a model that returns markup as part of a variable. To escape twig's encoding we have to include the raw filter, like so :

{{ entry.customField | raw }}

The encoded output of that field is never useful, so ideally we'd have a way to get the same result without that twig filter. ie :

{{ entry.customField }}

Looking at the various twig and template components I doubt this is possible, but is there any hidden ways to get this working?

This is all designed to remove that extra requirement from the usage, so wrapping unescape tags around it isn't want I'm looking for.