texts: Why might I be unable to delete entries and uninstall plug-ins in Craft CMS Solo 3.6.12?

texts:
I know the two things may seem unrelated but the actions are both red items in their respective dropdown menus and perform destructive tasks.
In Entries, I was unable to delete a couple of test entries and some that had been deleted in a previous version of Craft (whatever version was out on 1/8/2021; on Craft Solo 3.6.12 now) were able to be restored and now they are sitting in my Entries list, unable to be deleted. The Entries are in a Structure section,m not a single as Craft won't let you delete those from the Entries page.
I went to check to see what plug-ins I have installed that might cause an issue but nothing jumped out at me. Since I had both CK Editor and Redactor (wanted to try each out) installed, I thought I might remove one and commit to the other for the remainder of this project. I was able to disable the plug-in but not uninstall it.
In either case, no errors appear, and clicking the action causes no visible hint that anything is occurring at all.


texts: RelatedTo Query Using Both "and" and "or"

texts:
I'm attempting to build a filter that queries entries of a section based on two criteria: A selection of one or more categories (inclusive), and a single related entry (exclusive).

Specifically, the entries are from the "technologies" section. Each technology is related to one or more categories and a single "institution" entry.

The first step is to allow a user to, for example, select two categories (like "Information Technology" and "Medical Devices") and have the results be inclusive. Easily done with a relatedTo "or" parameter.

But next, I'd like the user to be able to select a single institution, and return only the previous results that are also associated with that institution (like "UW-Oshkosh"). This filter requires an additional relatedTo "and" parameter.

My attempt to add two different relatedTo parameters to the same query (detailed below) doesn't fly -- it will only honor the last relatedTo request:

{% set params = {
    section: 'technologies',
    limit: null
} %}

{% if technologyIds|length %}
    {% set paramTechnologyRelation = ['or'] %}
    {% for technologyId in technologyIds %}
        {% set paramTechnologyRelation = paramTechnologyRelation|merge([{ targetElement:technologyId }]) %}
    {% endfor %}
    {% set params = params|merge({relatedTo: paramTechnologyRelation}) %}
{% endif %}

{% if institutionId != "" %}
    {% set paramInstitutionRelation = ['and'] %}
    {% set paramInstitutionRelation = paramInstitutionRelation|merge([{ targetElement:institutionId }]) %}
    {% set params = params|merge({relatedTo: paramInstitutionRelation}) %}
{% endif %}

{% set technologyResults = craft.entries(params) %}

{% paginate technologyResults.limit(10) as technologies %}
    ...
{% endpaginate %}

I'm trying to think of other approaches -- Is is possible to run a second query on an array of entries? Any ideas on how to best approach this? Thanks for any insights.


texts: I'm creating a new Craft 3 site and migrating a lot of content from a wordpress setup. I'm wondering if it is better to separate assets into more sources - thus reducing the number of files per directory. An example would be a different asset source per section. Or is it fine to lump them all into one large directory? Is there any performance advantage to the former?


texts: Retrieve matrix content from Entries form field in an Entry

texts:
I'm trying to retrieve matrix content from a an Entry field chooseTemplateExample which has a matrix block component with a Entry field component.

{% for template in entry.chooseTemplateExample %}
  View {{ template.title }} example

  {% for block in template.component %}

     //Trying to get the matrix content within this "template"
     {% for block in entry.chooseComponentForTemplate %}
      {% for component in block.component %}
        {{ title }}
      {% endfor %}
    {% endfor %}

  {% endfor %}

{% endfor %}

Thank you in advance.


texts: Multiple issues with User Registration from frontend

texts:
I am not able to get User Registration to work properly using a frontend form from the Craft Docs (https://craftcms.com/docs/templating/user-registration-form).

Here are the particulars:

Craft Pro Version = 2.6.2791

Users > Settings has the ‘verify email addresses’ and ‘allow public registration’ boxes checked, and a default User group selected

I specified a redirect in craft > config > general to 'activateAccountSuccessPath' => 'registration-success',

The form submits and the user is created, but no verification email is sent and the user is not assigned to the group I selected in User Settings. If I manually send a verification email, following the link causes the user to be verified, but still not added to any Group. Further, the user is redirected to http://sitename/dashboard, despite having a redirect set in the Config > General file.

I tried this on two different Craft sites, each on different hosts (one of which is Arcustech) and both of which are running the latest Craft release (2.6.2791).


texts: https problem with multi environment config

texts:
I'm using Craft-Multi-Environment on a clients site and have it all working happily with standard http. However, we want the site to run on https to be more secure, but the server company can't seem to get it to work.

I have the same Craft-Multi-Environment working fine with https on a personal site on a cloud server that I setup myself via Plesk. However, the clients site is being administed purely via the command line by the server company. So I wanted to know if there's any know issues that might be able to help to get it to work?


texts: How to allow data attr in tags in Redactor HTML Purifer

texts:
I am looking to allow data attr in tags with Redactor content.

What should I add to the Default config settings to allow this attr?


texts: Is it possible to include category slugs in the entry URL format?

texts:
Is it possible to include category or tag slug in the entry URL format?
Would you please let me know the tags that make it, if possible?


texts:
I was wondering if anyone else has experienced a serious performance hit when implementing pagination?

By just using Safari's timeline, I can see my page takes 500ms to generate.  After introducing JUST the paginate tag (not including any loops etc), it now takes 1.5s!

Is this normal behaviour?  If not, what should I be doing to improve the performance?

Thanks

EDIT:  Thanks for the suggestions regarding caching.  I am aware of the cache tag however, the paginated entries are the results of a search query with various filters so I'm concerned that the caching will have little effect.  Or am I wrong?


texts:
I'm trying to show the nutrition information for restaurants using the following snippet

                    {% set nutrition = craft.entries.section('nutrition').Ids() %}

                    {% set entries = craft.entries ({
                        section: 'restaurants',
                        orderBy: 'title',
                        limit: 50,
                        relatedTo: nutrition
                    }) %}

The nutriton channel has around 300k entries and around 200k entries in restaurants channel. Dedicated server with 16gb ram and 8 vcpus can't really handle it. Load average is above 4 and CPU utilization by mysql is 100%-300%. Page loads forever with 550 ram used according to dev toolbar.

Is there a way to speed the things up?


texts:
I'm currently trying to filter my search results by category, I've been following this tutorial but cannot get it to work. It keeps not adding on the category parameter, but instead just replaces the search parameter like so:

On search:
"/search/?q=dress"

On Clicking a Filter:
"/search/?category=wedges"

Below is the code running my search box:

  <form action="search/" class="form">
    <input type="text" class="text-field w-input" maxlength="256" type="search" autofocus="true" name="q" data-name="Name" placeholder="e.g. Black Dress" id="name">
    <input type="submit" data-wait="Please wait..." class="search-field-go w-button" value="">
  </form>

and the code running the results page:

{% set query = craft.request.getParam('q') %}
{% if craft.request.getParam('category') is not null %}
    {% set category = craft.categories.slug(craft.request.getParam('category')) %}
    {% set entries = craft.entries.search(query).order('score').relatedTo(category).find() %}
{% else %}
    {% set entries = craft.entries.search(query).order('score') %}
{% endif %}

{% include 'search/_filters' %}

{% if entries|length %}

{{ entries|length }} results:

        {% for entry in entries %}

{{ entry.title }}

        {% endfor %}

{% else %}

Your search for “{{ query }}” didn’t return any results.

{% endif %}

   {% for category in craft.categories.group('womens').find() %}

            {{ category.title}}

  {% endfor %}


texts:
I've got a clean install of Craft with just some initial configuration of entry types, categories, assets, etc.

Any image I upload (either directly into assets or via an image field) has almost all of its EXIF metadata stripped out. Most of the removed info I don't care about, but it's essential that the embedded copyright, geolocation and keyword information is retained.

I assume this has something to do with the configuration of ImageMagick/GD (whichever Craft uses by default). Is there a way I can create a configuration that specifies which EXIF fields to preserve in the uploaded image?


texts: Get parent entry from a section using the Element API

texts:
How can you access the parent of a section using the Element API? I have the following where I use the getParent() function which does return an empty object when an entry has a parent.

Do I need to pass in the element criteria model or something?

Also could someone expand on this to show how you just get the level 1 parent or the level 2 parent please.

return [
  'endpoints' => [
    'brands.json' => [
      'elementType' => 'Entry',
      'criteria' => ['section' => 'brand'],
      'transformer' => function(EntryModel $entry) {
        return [
            'title' => $entry->title,
            'url' => $entry->url,
            'level' => $entry->level,
            'parent' => $entry->getParent()->first(),
        ];
      },
    ],
  ]
];


texts:
I have trouble installing the demo site 'happylager'.

Windows 8.1
WAMP 3.0.4 - MySQL 5.7.11 - PHP 5.6.19 - Apache 2.4.18

I follow the instructions from https://github.com/pixelandtonic/HappyLager and when I import the .sql file I get this error message.

When I head back to happylager.dev/admin I get the installation screen, not the login screen as it is described in the repo. What do you think is the problem?

Thank you in advance


texts: How would I create a select element with the 14 days from today as options

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

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

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

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

Thanks


texts:
I'm trying to get our Craft CMS install to use a memcached cluster we created in AWS. I am able to telnet to the memcached server on port 11211 from the server that will be connecting to it. I did a tcpdump (packet trace) on the web server's interface and it did not try to connect to the caching server at all over a period of 12 hours.

I have the caching method in config/general.php set to use "memcache" and have the useMemcached set to true in config/memcache.php as well as the memcached server info all filled out correctly.

Is there something I am missing? It should have at least attempted to connect at least once in that amount of time. I was wondering if my web server was missing some sort of php plugin. I found libphp5-memcached wasn't installed so I installed it, but still no connection out.

The documentation on getting Craft CMS to work with a caching server don't appear to have much more than the config stuff, so not sure what we're missing.

Thanks for the help in advance!


texts:
I'm using a category group and routes to serve up entries on landing pages with a URL structure like this.

www.domain.com/properties/retail/freestanding

My code works, but I am wondering if there's a better way to write it (dry it up).

{% set allProperties = craft.entries.section('propertiesSection') %}
{% set cat = craft.request.getSegment(2) %}
{% set subcat = craft.request.lastSegment %}

{% set retail = craft.categories.group('properties').craft.categories.slug('retail-properties') %}

{% if subcat == "freestanding" %}
    {% set entries = allProperties.relatedTo([ {targetElement: freestanding } ]) %}
{% endif %}

{% if subcat == "storefront" %}
    {% set entries = allProperties.relatedTo([ {targetElement: storefront } ]) %}
{% endif %}

.... and so on

{% if entries|length %}
    {{ entry.title }}
{% endif %}


texts:
I have a bunch of images that aren't related to any entries but are in an asset source. Let's call this 'My Images'.

How do I just grab those assets? I can't find anything in the docs that suggests this is possible—it seems such an obvious use-case though I'm sure I am missing something.


texts: What’s the pattern for Entry Form inputs for Assets meta data fields?

texts:
The templating pattern for Entry Form inputs for Assets files is clear enough.
But how can I provide inputs in an Entry Form for meta data pertaining to an Assets file?
For example, I have fields like:

attrAlt for an ‘alt’ text image description
attrHref for a URL the image will link to

Any help much appreciated.


texts: Relational query get error "Getting unknown property"

texts:
I built up a plugin and inside the plugin I created the relation between Entry and Section using ActiveRecord, like below:

In SectionRecord :

class SectionRecord extends ActiveRecord
{
    public static function tableName()
    {
        return '{{sections}}';
    }

    public function getEntries()
    {
        return $this->hasMany(EntryRecord::className(),['id' => 'sectionId']);
    }
}

In EntryRecord file:

class EntryRecord extends ActiveRecord
{
    public static function tableName()
    {
        return '{{entries}}';
    }

    public function getSection()
    {
        return $this->hasOne(SectionRecord::className(),['sectionId' => 'id']);
    }
}

At last in controller:

$hub = SectionRecord::findOne(['handle'=>'hub']);
dd($hub->entries);

I tried to get section which is working, but when I wanna fetch entries under that section, showed me an error:

Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: raintestplugin\test\records\SectionRecord::sectionId


texts: Using a Dropdown field in a Matrix to parse a global

texts:
I have two globals setup for affiliate and compensated type language - using Matrix and a dropdown I'm trying to find a way to let the user add this language in a new block.

I cannot for the life of me get the globals to parse. In my dropdown handle I've made sure to mirror the handle of the globals themselves. Then I'm using something like this:

{% case 'globals' %}
{% set legalContent = block.legalVariables %}

{{ legal.legalContent }}

'globals' is the block handle, 'legalVariables' is the dropdown handle and 'legal' is the global group. I've tried quite a few different variations on this, but it just spits out 'legal.affiliateLegal' which is right, but it won't parse it.

Am I missing something simple or is this not possible with globals?


texts:
This just happened, but just one time. Any idea why?

CDbException
CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query. The SQL statement executed was: SELECT id, groupId, name, handle, context, instructions, translatable, type, settings FROM craft_fields WHERE context = :context ORDER BY name. Bound with :context='global' (/Users/johndoe/Desktop/Projects/websitetest/craft/app/framework/db/CDbCommand.php:543)
0 /Users/johndoe/Desktop/Projects/websitetest/craft/app/framework/db/CDbCommand.php(396): CDbCommand->queryInternal('fetchAll', Array, Array)
... (large, not relevant stack trace)
30 {main}


texts: How to connect to a Remote DB using CraftCMS 3.1+

texts:
I tried using Andrew Welch's craft-connect plugin, but the plugin was throwing an error on the REMOTE_DB_SERVER variable. I commented the variable out in the .env file, but I still could not connect. I also tried just using the IP address of the remote server in the DB_SERVER variable.

What I hope to accomplish is a shared development DB which exists on a remote server. I can then connect both of my local environments to that development DB. When I know that the development DB is good to go, I will synch it with my production DB. But, I cannot sort out how to accomplish a remote DB connection with CraftCMS.

I can connect to my development DB using the SSH method in SequelPro (requires SSH host IP, SSH user and SSH password). I've tried replacing the DB server variable with the IP address of my server in my .env file, but that doesn't work. If I'm tunneling into the server using SSH first in SequelPro, wouldn't I also need to do the same with my connection in Craft?


texts:
In the Sections settings ("Entry URL Format") I would like to add an entry property tag for Entry Type.

discography/{slug}


texts: Can't install Craft on a GoDaddy shared hosting server

texts:
I've followed Shanti's advice when something similar happened to her. However, it hasn't resolved my problem and I think something else is going on.

GoDaddy's support are quite usless (bascially just sales people). Having installed Craft as I normally would, I'm getting this Internal Server Error.

I can't even get to the point of installing craft; even if I try going to

  www.domain.com/index.php?p=admin/install

I have a feeling it's something to do with how the directories are structured for people with multiple domains on a host/reseller account. It looks something like this:

The website is setup to point to the "/website3/public" directory. I know I could put the Craft directory into the Public folder and fiddle with the index.php $craftPath variable. But I want to keep true to Crafts Installation guide, and keep those files secure.

So, if you have a similar setup; how might I go about trouble shooting the problem of getting things pointing in the right directions?


texts: I'm have group called "Editors" that can create entries with the text fields but I would like to "Admin" group have lightswitch called "promoted" in same entries or maybe even text field for notes that would be not visible for "Editors" group (and entry owner if he is in "Editors" group) it is possible?


texts: Filtering products by categories and showing number of products related to selected category

texts:
I currently have about 420 products and over 100 of categories to choose from for each products, showing the list of categories and filtering it, works fine, and performance is not too bad when it's also cached.

What I'm trying to do now is show the total number of products for each filter, but it has to update when I select a filter,(on a side note: my filter is currently being done through ajax).

My issue is that, with all the number of products and filters, when I get all the total number products for that filter, it gets very query heavy and slow which is not a good user experience.

What's the best way to do this, performance wise?


texts: Pass Craft Field String to Javascript Function

texts:
I tried different solutions given here, here and here.
But I get nothing to work, probably missing something small and simple.

I have this variable in a .js File:

var dziFilesUrl = 'http://localhost:3000/openseadragon/highres/{{ entry.kelimImageData }}/';
var dziData = '<?xml version="1.0" encoding="UTF-8"?><Image xmlns="http://schemas.microsoft.com/deepzoom/2008" Format="jpeg" Overlap="1" TileSize="254"><Size Height="5097" Width="3600"/></Image>';

where I want the entry.kelimImageData coming from the Backend.

In my .twig File i have this:

{% includeJsFile "/assets/js/openseadragon-custom-dzi.js" %}

{% set myJs %}
  tileSourceFromData('{{entry.kelimImageData}}');
{% endset %}

{% includeJs myJs %}`

My openseadragon-custom-dzi.js File looks like this (modified to make it not so long)

var dziFilesUrl = 'http://localhost:3000/openseadragon/highres/{{ entry.kelimImageData }}/';
var dziData = '<?xml version="1.0" encoding="UTF-8"?><Image xmlns="http://schemas.microsoft.com/deepzoom/2008" Format="jpeg" Overlap="1" TileSize="254"><Size Height="5097" Width="3600"/></Image>';

var tileSourceFromData = function(data, filesUrl) {
  var $xml = $($.parseXML(data));
  var $image = $xml.find('Image');
  var $size = $xml.find('Size');
  var dzi = {
    Image: {
      xmlns: $image.attr('xmlns'),
      Url: filesUrl,
      Format: $image.attr('Format'),
      Overlap: $image.attr('Overlap'),
      TileSize: $image.attr('TileSize'),
      Size: {
        Height: $size.attr('Height'),
        Width: $size.attr('Width')
      }
    }
   return dzi;
  };
}

var viewer = OpenSeadragon({
  ...
  tileSources: tileSourceFromData(dziData, dziFilesUrl)
});


texts: I want to display entries that have a field that is the same as a field in a global variable

texts:
There is a publishMonth (multiselect) and publishYear (radio buttons) field in each article. They do not correspond to an actual date. Each article is is associated with one year, or one or more months. I'd like my editor to be able to change two global variables. currentMonth (radio button), and currentYear (radio button) to change all the articles display on the webpage at once at any time she pleases. Some articles may be associated with one or more months. Articles do not get changed over at the same date and time each month, which is why it's not associated with a real month or year. The code below returns nothing.

The idea is to make it as easy as possible for my editor to "flick the switch" to the next month.

{% set dogs = craft.entries.section('news').order('articleOrder desc').limit(5) %}
{% for entry in dogs %}

    {% if entry.publishYear in currentEdition.currentYear %}

{{ entry.title }}

    {% for image in entry.images.limit(1) %}

    {% endfor %}

{{ entry.body|striptags|slice(0,300) }}... Read more

{{ entry.publishYear }}

        {% for option in entry.publishMonth %}

{{ option }}

        {% endfor %}

    {% endif %}

{% endfor %}


texts: How can I make the Redactor toolbar to not affix to the top of my viewport? I tried to modify the config files, but I had no luck!


texts:
Trying to get my head around this and make my code a little DRYer.

I have a _helpers macro file. Like so:

{% macro date_formatted(givenDate) %}
    {{ givenDate|date("l, jS F Y") }}
{% endmacro %}

{% macro product_title(product) %}
    {{ product|replace(' HA', 'HA')|raw }}
{% endmacro %}

This file is used in various places throughout the website and is included in various base templates using {% import '_macros/_helpers' as helpers %}

I then have another macro for creating products (teasers and various code that would be repeated). This contains:

  {% macro teaser(product, imgSize, className) %}
    {% set cart = craft.commerce.getCart() %}
    {% set category = product.category.first() %}
    {% import '_macros/_helpers' as helpers %}

        {% set thumbAsset = product.productImage.first() %}
        {% if thumbAsset %}

        {% endif %}

{{ helpers.product_title(product.title) }}

{{ product.defaultPrice|currency(cart.currency) }}

            View Product

            {% if className == "product-teaser--featured" %}
                {{ category.title }} Range
            {% endif %}

{% endmacro %}

{% macro alsoPurchased(product, imgSize) %}
    {% set cart = craft.commerce.getCart() %}
    {% import '_macros/_helpers' as helpers %}

        {% set thumbAsset = product.productImage.first() %}
        {% if thumbAsset %}

        {% endif %}

            {{ helpers.product_title(product.title) }}

            {{ product.defaultPrice|currency(cart.currency) }}

{% endmacro %}

The problem/question I have come up against is that it seems I have to include {% import '_macros/_helpers' as helpers %} in each Macro and also the same goes for setting the variable for cart. {% set cart = craft.commerce.getCart() %}

Is there a better way of doing this? Or a DRYer way of doing this? So I don't have to repeat my includes and setting of variables for each Macro block?


texts: I want to add an "Edit entry" button on each page for admin users. Am I overlooking a simple way to output the Edit link to the CP edit page for the current entry? Curious if there is something like {{ entry.editLink }}


texts: Moved Craft 3 site to new server and getting "No primary site exists" error

texts:
I moved a Craft 3 site to a new server. The previous server was a plain vanilla Ubuntu 16 LTS LAMP stack. The new web server is a Bitnami Ubuntu 16 LTS with a LAP stack (no local MySQL). In the new environment I have setup the Craft 3 site to connect to the remote server via SSL. The SSL connection seems to be working fine, but I am getting the following error when I navigate to the site on the new server:

  An Error occurred while handling another error:
  craft\errors\SiteNotFoundException: No primary site exists in /opt/bitnami/apache2/vhosts/ijm.org/htdocs/vendor/craftcms/cms/src/services/Sites.php:422
  Stack trace:
      #0 /opt/bitnami/apache2/vhosts/ijm.org/htdocs/vendor/craftcms/cms/src/web/Request.php(1120): craft\services\Sites->getPrimarySite()

I have tried adding a siteUrl setting in the general.php file, but that didn't help.

Does anyone have any ideas on how to fix this issue?

Thanks!


texts: Conditionally attach behaviors to craft\elements\Entry by section

texts:
I'm trying to conditionally attach behaviors based on an entries section.

The following code works fine, but I'm trying to clarify one bit:

To avoid a yii\base\InvalidConfigException on the CP entries screen, I need to bail early with the $event->sender->sectionId check.

Should I be using this event for this type of thing?

…or should I attach them later, e.g. PopulateElementEvent?

<?php

namespace modules\appmodule;

use Craft;
use craft\elements\Entry;
use craft\events\DefineBehaviorsEvent;
use Tightenco\Collect\Support\Collection;
use yii\base\Event;

class Module extends \yii\base\Module
{
    const SECTION_BEHAVIORS = [
        'products' => [
            \modules\appmodule\behaviors\Reviewable::class,
            \modules\appmodule\behaviors\Product::class,
        ],
        'trips' => [
            \modules\appmodule\behaviors\Reviewable::class,
            \modules\appmodule\behaviors\Trip::class
        ],
    ];

    public function init()
    {
        parent::init();
        Event::on(
            Entry::class,
            Entry::EVENT_DEFINE_BEHAVIORS,
            function (DefineBehaviorsEvent $event) {
                $event->behaviors = Collection::make(self::SECTION_BEHAVIORS)
                    ->filter(function ($behaviors, $sectionHandle) use ($event) {
                        return
                            $event->sender->sectionId &&
                            Craft::$app->sections->getSectionById($event->sender->sectionId)->handle === $sectionHandle;
                    })
                    ->prepend($event->behaviors)
                    ->flatten()
                    ->all();
                }
          );
    }
}


texts: Structure - Add class if element has children

texts:
I have a structure section which I am using to create a navigation menu.
It works ok and produces the list etc.
I want to add a class to the li element if it has children.

Current Code is:

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

    {% nav entry in entries %}

            {# Check for entry type / get related entry #}
            {% if entry.type == 'customLink' %}

                {# Link to a custom url #}
                {{ entry.title }}

            {% else %}

                {# Link to a structure entry #}
                {{ entry.title }}

            {% endif %}

            {# Repeat this for child entries #}
            {% ifchildren %}

{% children %}

            {% endifchildren %}

    {% endnav %}

I want to add class="has-dropdown" to the first list element if it has children.

I have tried this:

But that does not work. How can this be achieved?


texts: Craft search only shows results matching 'title' of entries

texts:
I´m doing a search on Blog entries, i want to get all relevant entries searching on several fields, and seems that only matches the title. I try already using search(query), now i added the fields, same result. Maybe the search item should be re-generated? i don´t know how to do it in console, but i have only 4 blog entries at the time, i already change and saved all of them, same result...
Any help is welcome. Thanks.
{% paginate craft.entries({
             search: 'title:' ~ query ~ ' OR categoriaBlog:' ~ query ~ ' OR etiquetasBlog:' ~ query ~ ' OR resumenBlog:' ~ query ~ ' OR subtituloBlog:' ~ query ~ ' OR contenidoBlog:' ~ query,
             orderBy: 'score',
             section: 'blogSec'
        })
        .limit(6) as pageInfo, blogs %}


texts: Get entry by slug with EntriesService in ElementAPI

texts:
I'm looking to get all entries from one section (say 'videos'), that are related to a specific category. The only reference to the category is the slug that is a parameter in the url:

....dev/videos/category-slug

I need to get the category id from the slug to be able to relate the videos to the category in the criteria:

'criteria' => [
  'section' => 'videos',
  'relatedTo' => ['targetElement' => $categoryId],
],

I can't seem to find a way to get the properties of the category before applying the criteria. Is there something on the EntriesService object that I can use to get the category entry, similar to template usage? E.g:

$categoryEntry = craft()->entries->section('categories')->slug('category-slug');

And then pass the $categoryEntry id through to the criteria to return all the related videos. E.g:

'criteria' => [
  'section' => 'videos',
  'relatedTo' => ['targetElement' => $categoryEntry->id],
],

Any help with a way I could do this all in one endpoint would be great. The alternative is passing the slug into another category endpoint to get the entry, then use the response to pass the id to the above endpoint.

Cheers!


texts:
I’ve set up a few email notifications to be sent to customers, and in the corresponding email templates I’d like to use content from Global fields I’ve created.

But when I use the regular variable {{ globalSetHandle.fieldHandle }} nothing is outputted in the emails.

Does that means that we can’t use Globals inside email templates?

Thanks!


texts:
I am wondering the way to go about modifying the redactor formatting settings either for all the configs or on a per config basis. I want to add custom formatting styles and classes for various text elements. Per the documentation
it seems I need to add it with JS (not something I add in a config json file) but i'm not sure where I need to add the file.


texts:
I am working on my SEO and I am getting a duplicate title in Craft.
I want to make a custom title using the URI segment in using PHP.


texts: How do I remove the index.php from all URLS in Craft 2 CMS?

texts:
I am very new to Craft and have only been working with it for a few hours. However, I am stuck with something I can't seem to figure out.

I understand the basics of templates, of which I have an index.php using % extends "_layout" % Then I created a new Section with the Section Type set as Single for About. Craft sets the Entry template to about and I have the URL set to be about. Then I create a new template file called about.html.

However, the problem comes when I go to view it on localhost/about as I get the following message;

The requested URL /about was not found on this server.

But when I navigate to index.php/about it is there. I'm confused as to why the architecture of the URL is set up this way as on a normal website you would'nt have index.php/ before every other page on your site.

Is this fixable?


texts: Unable to get relatedTo working on an ElementCriteriaModel

texts:
In a plugin I am trying to get Users related to other Users:

$criteria = craft()->elements->getCriteria(ElementType::User);
$criteria->group = 'partners';
$criteria->relatedTo = [
  'sourceElement' => $someUserId
];

$result = $criteria->find();

I can see data in the relations table where sourceId is set to the value of $someUserId but I get nil results from $criteria->find().

I've tried passing in a UserModel, the user ID (as shown above) and changing sourceElement to targetElement and element all with no success.

What have I missed here?

======EDIT======

It seems I can get what I need by doing this:

$user = craft()->users->getUserById(someUserId);
$relatedUsers = $user->partners;

This works but I'd like to understand what's wrong with the original code above. partners is the name of the relationship field on the source element as well as the name of the user group that that field targets.


texts: Customizing front-end login/logout redirects

texts:
I have "manage" link that redirects to domain.com/login.
"login" is custom front-end page that after logging in redirects to homepage.
After logging in when I click "manage" again the domain.com/login redirects me to CP dashboard.
Signing out from CP redirects me to default Craft login page.

How to redirect directly to dashboard after logging in?
How to redirect directly to domain.com/login or homepage after signing out?

I'm also using manager as cpTrigger, and this is my config:

'postLoginRedirect' => 'manager',
'logoutPath' => 'login',
'cpTrigger' => 'manager',

For some reason according to #1 postLoginRedirect doesn't take effect
same for #2 and logoutPath, maybe I'm using them in the wrong way?

login/index.html code:

{% extends "login/_layout" %}
{% set title = "Welcome back, friend :)" %}
{% block content %}

          <form method="post" accept-charset="UTF-8">
          {{ getCsrfInput() }}
          <input type="hidden" name="action" value="users/login">

            {% if errorMessage is defined %}

               {{ errorMessage }}

            {% endif %}

                <input class="input" id="loginName" type="text" name="loginName" placeholder="Email">

                <input class="input" id="password" type="password" name="password" placeholder="Password">

                <input type="checkbox" name="rememberMe" value="1">
                Keep me logged in

                <button class="button is-primary" type="submit">Login</button>
                Cancel

          </form>

              Register an Account
              |
              Forgot password
              |
              Need help?

{% endblock %}


texts: Unable to store Model in Commerce Order Fields

texts:
I'm trying to use custom order fields in Craft Commerce to store a reference to an object, but all I am getting back is an ElementCriteria model.

I have two custom order fields defined: twoDayOption and fourDayOption. Both are events from Solspace Calendar (Calendar_EventElementType).

In the Commerce -> Orders page, I can set these fields with no problem.

On my product page I have a dropdown for selecting the values of each of these fields. They look pretty much the same. Here is the twoDayOption one:

<select name="fields[twoDayOption]">
    {%- for days in craft.calendar.events({calendar: 'workshops'}) -%}
        <option value="{{ days.id }}">{{ days.title }}</option>
    {%- endfor -%}
</select>

After submitting the form the values for twoDayOption and fourDayOption seem to be lost. When I call {{ dump( cart.twoDayOption) }} I get an object of type Craft\ElementCriteriaModel. It references the Calendar_EventElementType, but the ID that was submitted is not there.

Here's the first part of the output of that dump:

object(Craft\ElementCriteriaModel)#757 (17) {
  ["strictAttributes":protected]=>
  bool(false)
  ["_elementType":"Craft\ElementCriteriaModel":private]=>
  object(Craft\Calendar_EventElementType)#990 (7) {
    ["componentType":protected]=>
    string(11) "ElementType"
    ["_sourcesByContext":"Craft\BaseElementType":private]=>
    NULL
    ["_classHandle":"Craft\BaseComponentType":private]=>
    NULL
[snip]

Looking through Commerce_CraftController, I found that it calls BaseElementModel->setContentFromPost("fields") to set the custom order fields. I added in some logging statements to make sure it was getting the information I expected.

When it enters the method it finds these values from $_POST['fields']:
    Array
    (
        [twoDayOption] => 16
        [fourDayOption] => 12
    )

This is exactly whe I expect. It then finds the two custom field handles that match this. I have other logging statements that show what handle it's processing, and the value it gets from the POST:

2016/09/29 13:54:39 [info] [application] setContentFromPost twoDayOption
2016/09/29 13:54:39 [info] [application] setContentFromPost twoDayOption: 16

setContentFromPost also gets the fieldType, and calls $fieldType->prepValueFromPost. The value 16 is passed in, and 16 is returned.

Finally, that value is put into $this->_content->$handle, and I have a logging statement immediately after that verifies I can retrieve 16 from it. But when I log $this->twoDayOption, I'm getting the ElementCriteriaModel again.

I'm at a loss. It seems to know it's supposed to have a Calendar Event for that field. Should I not be passing in the ID? Is there another step I am missing?


texts:
Anyone have any tips on speeding up entry searches? Ours are currently taking about 90 seconds per search.

Some stats about our Craft database:

Entries: 336,000
Relations: 4,390,000 (!!!)
Search Index Records: 320,000

It used to be fast. But the more data we get into it, the slower it goes. It's basically unusable now. We removed indexing on every field except for title, slug and item number. But that didn't help much.


texts: Set Search to query multiple attributes (e.g. title, body)

texts:
Craft Pro 2.5.2761 (no plugins)

I've got a basic search form, and on my results template, the following:

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

{% set articles = craft.entries({
section: 'article',
order: 'score',
search: {
  attribute: 'keywords',
  query: query,
  subLeft: true,
  subRight: true
}
}) %}

Which works as expected (I get results when the query term matches the keyword of an entry).

However, I want my search to encompass not just keywords, but also the  title and the body field.

[edit - deleted part of my post because it was misleading as to the real problem]


texts: Limit Users Signup to Users from Specific Domain

texts: I have an eLearning page people from a .gov domain need to access.  I want them to be able to sign up for a user account and get immediate access, but I only want people from within that domain and perhaps one other to have this privilege.  I would want to approve any other users before they gain access.  Is this possible?


texts: Editing Images in Craft Cause Server to Hang

texts:
In the assets area when wanting to edit an image (focus point etc), the server hangs after double clicking an asset.

If you checkmark an asset and then select Edit Image, set the focal point and click save, the website hangs as well.

We are using Forge and hosting images on Digital Ocean Spaces. We are also using the imageOptimize plugin.

This is happening locally as well as on our staging server. Restarting the server is the only way to access craft again.

Where would we start looking to resolve this problem?

The below image illustrates how our image volumes are set up. The settings are defined in the .env.php file and given aliases in the general.php config file.


texts: How to display in the CP only the current user's entries?

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


texts:
How do I set the webhook URL for Charge in the config file?

I've got my /config/charge.php created.


texts: How to calculate the number of days left?

texts:
I want to calculate the remaining days between the current day (now) and a future date set as a date field in {{ inschrijven.datumEvenement }} globals

{{ inschrijven.datumEvenement.diff(now).format('%d') }}

This is what I came up with but it doesn't generate the right number of days left.

Using now = 05-15-2015, inschrijven.datumEvenement = 08-30-2015 the above tag generates "14".


texts: Composer conflict when installing craftcms/plugin-installer

texts:
I have installed composer successfully but when I try to add:

composer require craftcms/plugin-installer

I get the following:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- craftcms/cms 3.0.0-RC4 requires craftcms/plugin-installer ~1.5.0 -> satisfiable by craftcms/plugin-installer[1.5.0, 1.5.1, 1.5.2] but these conflict with your requirements or minimum-stability.
- craftcms/cms 3.0.0-RC4 requires craftcms/plugin-installer ~1.5.0 -> satisfiable by craftcms/plugin-installer[1.5.0, 1.5.1, 1.5.2] but these conflict with your requirements or minimum-stability.
- craftcms/cms 3.0.0-RC4 requires craftcms/plugin-installer ~1.5.0 -> satisfiable by craftcms/plugin-installer[1.5.0, 1.5.1, 1.5.2] but these conflict with your requirements or minimum-stability.
- Installation request for craftcms/cms 3.0.0-RC4 -> satisfiable by craftcms/cms[3.0.0-RC4].

Installation failed, reverting ./composer.json to its original content.

I have also tried the following with no luck:

composer require craftcms/plugin-installer --ignore-platform-regs

Note my composer.json file shows the following:

{

"minimum-stability": "dev",
"repositories": [
    {
        "type": "composer",
        "url": "https://asset-packagist.org"
    }
],
"config": {
    "optimize-autoloader": true,
    "platform":{
        "php":"7.1.1"
    }
},
"require": {
    "craftcms/cms": "3.0.0-RC4"
}
}

Any help would be appreciated! On a side note this is a local install using Mamp Pro.


texts: How can I get tasks to complete when not logged in to the CP?

texts:
I've noticed that tasks only run when logged into the admin panel, is there anyway to avoid this?

For some context: I have jobs scheduled on a cron to run every 30 minutes, when I log in it seems that all of the items get queued up from the last time I logged in and proceed to run, this isn't terrible - but this app won't be seeing much login activity down the road.

`public function execute($queue)
{
    $section = Craft::$app->sections->getSectionByHandle('orders');
    $entryTypes = $section->getEntryTypes();
    $entryType = reset($entryTypes);

// Create an entry
    $entry = new Entry([
        'sectionId' => $section->id,
        'typeId' => $entryType->id,
        'fieldLayoutId' => $entryType->fieldLayoutId,
        'authorId' => 1,
        'title' => 'Order Number: ' . $this->orderId,
        'slug' => $this->orderId,
        'postDate' => new DateTime(),
    ]);

    $entry->setFieldValues([
        'orderId' => $this->orderId,
        'lineItemMatrix' => $this->lineItemMatrix,
        'couponMatrix' => $this->couponMatrix,
        'amountPayable' => $this->amountPayable,
        'orderTotal' => $this->orderTotal,
        'tax' => $this->tax,
        'sellerDiscount' => $this->sellerDiscount,
        'shipping' => $this->shipping
    ]);
    //check to see if entry exists.
    $existing = Entry::find()->section('orders')->slug($entry->slug)->one();

    if (is_null($existing)){
        return Craft::$app->elements->saveElement($entry);
    } else {
       // don't do anything;
        return false;
    }
}`


texts: Is it possible to compose a DateTime object from a string?

texts:
I experienced that there is a difference between real DateTime objects (as now is one) and strings composed to "fake DateTime objects" (ie. {% set myDate = '2014/06/24' %}).

Sometimes it makes no difference and you can use one or the other. The date() filter for example works fine with both. But this isn't always the case, the localeTime() method is an example that exclusively takes real DateTime objects.

Applying a date or date_modify filter to the myDate (string) variable is apparently not sufficient to convert it. The only solution I found is to modify now or fetch a DateTime object from an entry field, but I am looking for a way to generate one solely with twig in the template.

.

Edit:

Thanks for your answers so far, but I still don't get this to work. For me it always results in the following template error when I use a DateTime method on a manually composed DateTime object:

  Method "localeTime" for object "DateTime" does not exist

Here my example code for easy reproducibility. I more and more believe this is rather a problem with those DateTime methods and not with the way I compose the object.

{# Set var to string in supported format #}
{% set myDatetimeString = '2014-06-24 23:40' %}

{# Use date() function to convert string to DateTime object #}
{% set myDatetimeObject = date(myDatetimeString) %}

{# Alternatively use date_modify filter to convert string to DateTime object #}
{% set myDatetimeObject = myDatetimeString|date_modify('+0 day') %}

{# DateTime method doesnt work with these "objects" !! #}
{{ myDatetimeObject.localeTime() }}

{# But DateTime methods work with the `now` DateTime object #}
{{ now.localeTime() }}
{{ now.day() }}
{{ now.iso8601() }}


texts: How to trigger updateElements when hide modal?

texts:
Is it possible to refresh an element's list when closing a modal? I have a modal ready with:

onHide : function(){
    //but all what I tried doesn't work here

    //1: This will do the trick, but there is some bug with "Double-instantiating a select on an element" then the check box for the actions appear multiple times.
    Craft.elementIndex = Craft.createElementIndex('Plugin_ElementType', $('#main'), {
        context:        'index',
        storageKey:     'elementindex.Plugin_ElemenetType'
    });

    //2 I was searching for some global function as updateElements
    something like this: Craft.cp.updateElements()
    or: Craft.Plugin_ElementType.updateElements(); but no success

}

I need this because in that modal I change, delete data from my elements so I have to update the list, if is possible without to reload the page of course. Thank you in advance!


texts: Is it possible for photo's to be uploaded to a form?

texts:
I would like to create a form for competition entries. However, there needs to be the option for entrants to upload pictures with their entry form, is this possible?

Many thanks


texts: Migrations: What's the right way to rename a Foreign Key?

texts:
I'm writing a migration for one of my plugins, and struggling to resolve something which should theoretically be simple:

$this->renameColumn('myplugin_mytable', 'oldId', 'newId');

Except that doesn't work, because the column is a foreign key. The migration fails, and it kicks out this error in the log file:

  2016/02/07 20:09:29 [error] [application] CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 1025 Error on rename of './mysite/#sql-95d9_1e' to './mysite/craft_myplugin_mytable' (errno: 150). The SQL statement executed was: ALTER TABLE craft_myplugin_mytable CHANGE oldId newId int(11) NOT NULL (/craft/app/framework/db/CDbCommand.php:358)

Googling around, it seems that this error happens when you attempt to alter a foreign key.

I tried this method as well:

dropForeignKey for "oldId"
renameColumn from "oldId" to "newId"
addForeignKey for "newId"

But unfortunately, that's not working smoothly either.

What is the right way to rename a foreign key?

Sidenote: I'm tempted to post a feature request for P&T to add a renameForeignKey method to the MigrationHelper class. If that seems like the right approach, I'm happy to submit that feature request and we can close this question.


texts: How to build contact form from scratch (no plugin)

texts: I want to build a simple contact form without plugin, i am new to craft cms coming from wordpress, how can i build a simple form that will be save on entries and will send an email.


texts: Obtain suspended users in Craft3 Dev Preview

texts:
So I'm running into an issue where I'm given the users email. From there, I use the following code: Craft::$app->getUsers()->getUserByEmail($email);. This returns a null value, not because the user does not exists, but rather the status is set to suspended.

Is there a way to retrieve the User model from the email address, regardless of status?


texts: Is there comparable syntax to display dimension and weight filter settings from Commerce similar to those for currency eg: {{ variant.price|currency('CAD') }}? Couldn't see any info on this in the docs.


texts: Querying for an exact match on a Matrix block field with multiple types

texts:
I'm trying to query against a specific field value in a Matrix field with multiple block types, and I've tried multiple approaches with no success. It either returns 0 results, or all blocks regardless of type.

The use case is that Snipcart is doing a callback with the ordered items and their skus. I got the different product variants in a Matrix fields, and every variant has its own sku. The field have two block types. I want to find the correct product variant and reduce the available stock.

The simplest approach is this:

$criteria      = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->sku = 'JW';

I figured out that it won't join the content table if you don't specify a fieldId, and you also need a typeId.

$criteria      = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->fieldId = $fieldId;
$criteria->typeId = $typeId;
$criteria->sku = 'JW';

What happens then is that it's seem to do the correct query, but with a AND query for the field on both block types (even though I have defined a typeId):

system.db.CDbCommand.query(SELECT `elements`.`id`, `matrixblocks`.`fieldId`, `matrixblocks`.`ownerId`, `matrixblocks`.`ownerLocale`, `matrixblocks`.`typeId`, `matrixblocks`.`sortOrder`
FROM `craft_elements` `elements`
JOIN `craft_elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id
JOIN `craft_matrixcontent_colorsandtextures` `content` ON content.elementId = elements.id
JOIN `craft_matrixblocks` `matrixblocks` ON matrixblocks.id = elements.id
WHERE (((((((elements_i18n.locale = :locale) AND (content.locale = :locale)) AND (elements.archived = 0)) AND (elements.enabled = 1)) AND (elements_i18n.enabled = 1)) AND (content.field_texture_sku=:contentfield_texture_sku1)) AND (content.field_color_sku=:contentfield_color_sku1)) AND (matrixblocks.fieldId=:matrixblocksfieldId1)
GROUP BY `elements`.`id`
ORDER BY `matrixblocks`.`sortOrder` LIMIT 100. Bound with :locale='en_us', :contentfield_texture_sku1='JW', :contentfield_color_sku1='JW', :matrixblocksfieldId1='15')

The key here is the fact that my typeId isn't being applied, and this part:

(content.field_texture_sku=:contentfield_texture_sku1)) AND (content.field_color_sku=:contentfield_color_sku1))

I would like to query for a match independent of what type it is, as the blocks can be either or. Is there a way I can turn that into a OR query?


texts: Limiting form entries per day in FreeForm

texts:
I am using freeform to manage forms on my site.

I'd like to limit the number of entries on a form to 200 per day.

The method I thought would be best is to get the submissions for the form, and use the dateCreated parameter to only return those that matched today's date.

Here's my code

{% set form = entry.form %}
{% set submissions = craft.freeform.submissions({
    form: form.handle,
    dateCreated: 'now' | date('d M Y')
}) %}

{{ submissions | length }}

But it isn't working. Am I getting the date parameter wrong?


texts: How to use the default HTML email template when sending an email from a plugin?

texts:
On /admin/settings/email, when the HTML Email Template field is set to a valid template, all system messages are sent using it. They inject the content of the messages inside the {% block main %}{{body}}{% endblock %} variable.

From a custom plugin, setHtmlBody doesn't inject the content inside it. It takes its value as the whole template value instead of only replacing the {{body}} variable.

Example:

<?php

use craft\mail\Message;

$message = new Message();
$message->setTo('john@doe.com');
$message->setSubject("Hello world.");
$message->setHtmlBody("Hello world.");
$message->send();

How can I send this email using the custom HTML email template specified in my CP Email Settings?

I could copy-paste the whole file content of my custom template inside the setHtmlBody, but it doesn't seems to be a clean way...


texts:
My home page and some inner pages work fine but some page is not working and when i click on it then its showing me " Internal Server Error Server Error"
Please help me to sort out this issue.


texts: How do I create a dynamic field on a front-end form with the Sprout Forms plugin?

texts:
I have a job listing channel. I want to create a form on the front-end that has all the jobs that are created in the channel inside of it. I'm using the Sprout Forms plugin, but when I create a custom plugin that creates a new field type. I get the error that this field isn't meant to be used on the front-end.

Has anyone encountered this situation? Have any recommendations? Or am I going about it all wrong?


texts: Getting error when using bootstrap: Craft\WebApp::$request

texts:
I am using a testing library and while trying to load Craft through bootstrap with:

$craft = require '<full path here to>/app/bootstrap.php';

(but with the real path)

I dumped the error to a html file from the console and get this:

I see that Ben Parizek got a similar error (but i don't believe it was while using bootstrap only from the command line) in this question.

I tried setting cache to file in general.php and also cleared all caches in craft.


texts: Blog Comments / EntryModel.owner is undefined

texts:
I have build a Blog. Now I've tried to add the commenting function with "Comments":
https://github.com/engram-design/Comments

I use the absolute basic template:
https://github.com/engram-design/Comments/blob/master/examples/standard/standard.html

The call in my Tpl:

{% set params = {
   order: 'dateCreated asc'
} %}

{{ craft.comments.form(entry.id) }}

Until here everything is fine. When I want so send the comment, i always get this Error:

Property "Craft \ EntryModel.owner is undefined.

The "Comments" Plugin use EntryModel.owner when I want so submit a comment on any entry. Now the problem is that {{ entry.owner }} is undefined. But how can I define the {{ entry.owner }}?

I know this is a noobie Question, but how can I fix this?


texts: Populate Field Group With Fields From Another Field Group

texts:
I hadn't seen this asked, so I thought I'd broach the subject.
I would like to copy fields into a new field group, and then add/delete a few of those fields from the new group, to save time of building one again from scratch.
Does Craft have a way to do this?


texts: Migrating a Craft site to a different host.

texts: I'm moving my site from one host to another, and I'm having some trouble moving my craft site over. I have all of the files moved, and in the config file I'm pointing to the new database which I've imported over already. But when I go to the site or the admin url I'm getting a 500 error. Any thoughts?


texts:
Good Evening and Merry Christmas.
We are having an issue with some contact form submissions are not submitting emails and the database entry, however they continue through to the redirect page.
The affected submissions seem to be ipad related so far.
I have updated cms and all plugins to latest versions.
submissions are sent via SMTP using Sendgrid.
Can you suggest a way to diagnose the issue?


texts:
I'm a UX designer with some front end skills (though a complete novice with server config and Craft). I'm hoping someone can help me with something that seems rather basic.

Setup:
Mac Book Pro running High Sierra (10.13.5).
Using MAMP 4.4.1 (free version)
PHP 7.2.1, MySQL, and Craft 3.
The site loads in a browser when I visit: http://localhost:8888/.

My craft files are here: Macintosh HD/Applications/MAMP/htdocs/.

The template file in question is here: Macintosh HD/Applications/MAMP/htdocs/templates/_layouts/base.html

In the base.html file, in the head section, I am attempting to link to several CSS files. Here's the entire head section:

<head>
    {% block head %}
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta charset="utf-8">
      <title>{% if title is defined %}{{ title }} - {% endif %}{{ siteName }}</title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      {% css %}
        <link rel="stylesheet" type="text/css" href="{{ siteUrl }}src/css/typeplate.css">
        <link rel="stylesheet" type="text/css" href="{{ siteUrl }}src/css/grid.css">
        <link rel="stylesheet" type="text/css" href="{{ siteUrl }}src/css/screen.css">
      {% endcss %}
    {% endblock %}
</head>

The CSS files in question are here: Macintosh HD/Applications/MAMP/htdocs/src/css.

The Problem:
When I load the home page, the CSS does not load.

Things I've Tried:

I've tried removing the siteURL bit, and just hardcoding things
instead (like this: http://localhost/src/css/typeplate.css), and I
get 404 errors for the 3 css files under the network tab in Chrome developer tools.
I've tried removing the {% css } brackets around the stylesheet links, and the network tab in Chrome dev tools just tells me "failed" when the links are hard coded. When the links have {{ siteUrl}} in them, I can see the browser looking for the files at www.mywebsite.com/src/css/typeplate.css. But the files aren't currently there - this is a local dev site only.
I've tried changing the dev siteUrl in general.php from "null" to
"http://localhost/", and the web page stops loading altogether.
I've tried different hard coded URL's, like
(../src/css/typeplate.css).
I've searched StackExchange for similar problems, but I can't seem to make sense of any of the answers.

Can anyone help? Thank you so much in advance.


texts: Store categories in array by level in controller

texts:
I'm making a plugin and I need to get an array from a certain category group where the levels of the array are the same as the level of the categories in the group.

So I used the following code to get all categories in a group.

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->group = 'groupHandle';
$array = $criteria->find();`

This works fine but I want to create something like this:

$array[
    level1:[
        level2[
            level3,
            level3,
        ],
        level2[],
        level2[]
    ],
    level1:[
        level2[],
        level2[],
        level2[]
    ]
]

I hope you get the idea...
I could make a foreach in a foreach in a foreach but that's not very classy.
Thanks in advance!


texts: Uploading Asset Doesn't Clear GraphQl Cache with VueJS/Axios

texts:
Context:
I have a VueJS method that uses a form and Axios to upload an asset to an entry's asset field.
The method successfully uploads the asset to the entry, and I can prove that fact via the CraftCMS admin interface. So this works.

Problem:
I then have another VueJS method that calls on CraftCMS' GraphQL service to list the assets in the entry's asset field. This works, and returns the assets. But if I add more assets using my VueJS/Axios method above, the assets are added just fine (as confirmed on the CraftCMS admin side), but the GraphQL cache is not updated. So when I refresh the page and make another call to GraphQL, it never shows the new asset(s) unless I manually clear the GraphQL cache in the Craft CMS admin interface.

Questions:

Can I force the GraphQL cache to be cleared from some kind of javascript / Axios call, or some kind of Twig call on the same page as it loads?
Can I prevent GraphQL from caching?
Is this a GraphQL/CraftCMS bug?
Amy I crazy to think any of this?

Thanks for any ideas/help!

VueJS Method to Load the Asset list

  created () {
    //Define a global self variable
    var self = this;
    //Load our query
    var queryData = {query: '{entries(section:"caseStudy",id:{{entry.id}}) {...on caseStudy_caseStudy_Entry{id,csImages{id,url,}}}}'};
    //Get authorization
    var queryHeaders = {headers: {'Authorization': 'Bearer ABCDEFG'}};
    //Fetch data from the system using our query
    axios.post('/api', queryData, queryHeaders).then(function(queryResponse) {
        //Set the uploadAssets data.
        self.uploadedAssets = queryResponse.data.data.entries[0].csImages;
      }).catch(function (queryError) {
        console.log(queryError);
    });
  },

self.uploadedAssets Will contain the assets on the asset field as desired. But if I upload new assets using the following VueJS method, GraphQL won't see the new asset(s), but I can prove that they uploaded just fine bucasue in the CrafCMS admin side I can see the news asset(s) in the entry form.

VueJS method to upload the asset to CraftCMS, which works fine.

 uploadImage(event) {
  //Get the current form data
  var formData = new FormData(document.getElementById('formCaseworkEdit'));
  //Upload the form data to CraftCMS
  axios.post('/', formData).then(function(response) {
      //Call a function to retrieve the new list of assets
      self.getNewImage(response, self);
    }).catch(function (error) {
      console.log(error);
    });
 },

self.getNewImage(response, self); Will run the same GraphQL Query from the create() function , but will return the "old" listing of assets. When I manually clear CraftCMS caches, this list returns the new items.


texts: Saving to db with devMode true works, but not when false

texts:
// Upload and save as temp file
$request = Craft::$app->request;
$file = UploadedFile::getInstanceByName('file');
$tempPath = $file->saveAsTempFile();

// Create as permanent asset
$folder = Craft::$app->getAssets()->findFolder(['id' => 5]);
$asset = new Asset();
$asset->tempFilePath = $tempPath;
$asset->filename = Assets::prepareAssetName($file->name);
$asset->newFolderId = $folder->id;
$asset->volumeId = $folder->volumeId;
$asset->avoidFilenameConflicts = true;
$asset->setScenario(Asset::SCENARIO_CREATE);
Craft::$app->getElements()->saveElement($asset);

// Save ticket to db
$ticket = new ErrorReportingRecord();
$ticket->description = $description;
...
$ticket->assetId = $asset->id;
...
$ticket->save();

The problem is $ticket->assetId = $asset->id;. When devMode is true the asset id is stored in the db table as expected (assetId int(11) DEFAULT NULL). But when devMode is false the value of assetId in the table always becomes 0.
I should note that everything works on both my local machine with devMode set to both true/false as well as on the staging server which is identical to the production server, yet somehow the production server does not work. return $asset->id on production returns the id, so I don't understand why 0 is saved to the db.
If I do
return $asset->id;
$ticket->assetId = $asset->id;

on production (with devMode false) as a test, it returns the correct id, however removing return and running again still saves $ticket->assetId as 0.
I'm genuinely baffled by this.
When devMode is false no logs are produced when running the code.


texts:
Say i have a url: /lists/more-lists/even-more-lists and i have a route  lists/more-lists/*.

If i hit example.com/lists/more-lists/even-more-lists then it tries to load the index template (not the template defined by my route)

If i hit  example.com/lists/more-lists/foo then it loads the template defined by my template route.

I should add, that the url segments are category url's.


texts: Using a variable that was set in a previous include

texts:
By base.html:

{% block searchLogic %}
{% endblock %}

{% block meetingDisplay %}
{% endblock %}

My index.html:

{% extends "base.html" %}

{% block searchLogic %}
{% include 'logic/anonVisitor.logic' %}
{% endblock %}

{% block meetingDisplay %}
Some html code
{% for meeting in meetings %}
{% endfor %}
{% endblock %}

My anonVisitor.logic file:

{# More code that works, I just removed it for clarity #}
{% set meetings = craft.entries.section('meetings').address(params).limit(25).order('distance').find() %}

I try to use the variable meetings in the block "meetingDisplay" in the index.html file. For some reason the variable "meetings" is no longer available.

I am trying to seperate my logic blocks and my html blocks into separate files for manageability and reuse.

All this logic worked before I broke the code and html using the extends and includes.

Is there a way to make variables set in an include be available in a block?


texts:
I've set up an archive page as described in the docs... so my archive page url looks something like this http://mysite.dev/news/2014/09.

How do I then make the title display Archive for September 2014?

The {{ month }} variable is set as 09 and doing this -> {{ month|date("F") }} outputs January not September.

Any help would be appreciated.


texts: How can I expand on a normal Craft query to sort by a column in a custom table?

texts:
I have a plugin which contains a Record. My record contains a foreign key of the related element ID. The only other column in my custom table is the value I'd like to sort by.

In Twig syntax, how can I expand on a normal Craft query to sort by a column in my custom table?

Ordinary query:

craft.entries.section('colors').find

Ordinary query which sorts by my custom data:

craft.entries.section('colors').myPlugin('asc').find

Disclaimer:

I've done something similar to this once before... But in that case, I used the modifyElementsQuery method in my Field Type. Since this new plugin doesn't require a field type, I'm not exactly sure of the best way to modify a standard query.


texts: Craft Commerce cart product as unique product with different notes

texts:
Our client wants a specific option built in Craft Commerce. I guess is possible, but don't know how? Maybe you can help me out?

A customer selects a box: for example "giftbox custom 4" (priced $ 15). After selecting the box. The customer can pick 4 different tastes of chocolate cookies (e.g. 2 brownies, 2 white choco. etc). After picking the cookies, the client can add this to the cart.

My initial thought is to use a note fields for this, storing all the cookie data. But how can I make sure that each "giftbox custom 4" is a unique line item? Now Craft is adding all the "giftbox custom 4" together.

This is what I want to create:

2x Giftbox custom 4
Containing: 2 caramel, 2 brownies

1x Giftbox custom 4
Containing: 1 white choco, 3 caramel

2x Giftbox custom 4
Containing: 2 dark choco, 1 caramel, 1 fruit

In total there a more than 14 different giftbox sizes.
Giftbox custom 2, Giftbox custom 4, Giftbox custom 6, etc.
And you can choose from > 30 different cookies

@Luke Holder:
When I am using line-item options: For example: Giftbox 4 -> with options ABCD.

After submitting: they appear in my basket. Perfect, and i can change the quantity of Giftbox 4 -> with options ABCD .

But when I go back to the shop and add an extra giftbox to the cart: Giftbox 4 -> with options EFGH. Giftbox 4 -> with options ABCD are removed from my cart.

So i want the "Giftbox 4" products separated:
1x Giftbox 4 -> with options ABCD .
1x Giftbox 4 -> with options EFGH


texts: How can I have more than one product on the same page?

texts:
Using Craft Commerce, I would like to offer more than one product on my _entry template.

For example, let's say I am selling a wagon. I have a drop down of variants for color:

Choose Color

<select name="purchasableId" class="form-control">
    {% for purchasable in product.variants %}
        <option {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %} value="{{ purchasable.purchasableId }}">
        {{ purchasable.wagon.label }} &ndash; {{ purchasable.price|currency(cart.currency) }}
        </option>
    {% endfor %}
</select>

Now I would also like to offer a warranty. There could be different prices for different plans (variants) as well:

Choose Warranty

<select name="purchasableId" class="form-control">
    {% for purchasable in product.variants %}
        <option {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %} value="{{ purchasable.purchasableId }}">
        {{ purchasable.warranty.label }} &ndash; {{ purchasable.price|currency(cart.currency) }}
        </option>
    {% endfor %}
</select>

EDIT

Each "Warranty" is it's own section and has it's own product type within Commerce.
You could purchase a warranty by visiting mysite.com/warranties/my-warranty or mysite.com/wagons.

An example might look like mysite.com/warranties/basic. That page would have information about the "basic" warranty along with the option to add to cart.

In theory, you could purchase a warranty without purchasing a wagon.

I also want to (somehow) allow the user to purchase a warranty when they purchase a wagon. That's not to say I must do it this way, I am open to ideas. Currently both products are available together.

EDIT 2

Here is what my current form looks like on my product page. Is there a naming convention I should follow to pass multiple  options to the updateCart method? If I make both fields have the name of purchasableId, as expected, the system just grabs the last element. In my case it's the warranty product.

Since I would like to make the warranty a required field, maybe I need to restructure how I am selling wagons? I don't want to add to the variant list of my wagon product, that would get out of hand quickly.

Or, perhaps it's just a "Related Products" title and a link to the warranties page?

<form method="post" action="" accept-charset="utf-8">
<fieldset>
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="redirect" value="commerce/cart">
    <input type="hidden" name="qty" value="1">
    {{ getCsrfInput() }}
</fieldset>

<fieldset>
    Choose Color
    <select name="purchasableId" class="form-control">
        {% for purchasable in product.variants %}
            <option {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %} value="{{ purchasable.purchasableId }}">
            {{ purchasable.title }} &ndash; {{ purchasable.price|currency(cart.currency) }}
        </option>
    {% endfor %}
    </select>
</fieldset>

<fieldset>
    {% set warranties = product.warrantyOptions %}  {# This is the products field #}
    Choose Warranty
    <select name="warrantyId" class="form-control">
        {% for warranty in warranties %}
            {% for purchasable in warranty.variants %}
                <option {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %}
                value="{{ purchasable.purchasableId }}">
               {{ purchasable.title }} &ndash; {{ purchasable.price|currency(cart.currency) }}
               </option>
           {% endfor %}
       {% endfor %}
    </select>
</fieldset>


texts: Is it possible for an assigned entry (via field type Entries field) to know what it has been assigned to?

texts:
I have two entry types 'pipeline' (structure) and 'series' (channel). I know I can add children in a structure, but I want to keep 'pipeline' and 'series' separate to avoid duplication, as a series can belong to multiple pipelines.

I assign a series to a pipeline with a field type Entries field.

As an example I assign 'series1' to 'pipeline1' and 'pipeline2'.

What I'd like to know:

a) Is it possible for 'series1' to know it is assigned to 'pipeline1' and 'pipeline2'?

b) If it's not possible, is there a way to update the series entry when assigning to a pipeline?

Thanks for any help!


texts: How to validate a unique field in Craft 3 element?

texts:
I'm trying to validate a custom Element in my Craft 3 plugin.

Where should I be putting my validation rules?

I have two classes: one for the Element, one for the ActiveRecord (e.g. Invoice and InvoiceRecord).

One of the requirements is that one of its field (e.g. number) has to be unique.

If I override rules() on the Element, the validation occurs normally but the unique rule throws an error:

  Call to undefined method Invoice::getDb()

Now if I try to add the unique rule to my Record's rule() override, it does seem to fail validation and prevent saving the record, but no validation error is thrown (Craft flashes the "saved successfully" message and returns to the element index, but without the new/updated element).

I understand that the record's validation is called only in afterSave, so technically validation has already been done:

public function afterSave(bool $isNew)
{
    if ($isNew)
    {
        $record = new InvoiceRecord();
        $record->id = $this->id;
    }
    else
    {
        $record = InvoiceRecord::findOne($this->id);
    }

    $record->number = $this->number; // Has to be unique

    $record->save();

    parent::afterSave($isNew);
}

But I don't understand how to get my validation working for something rather simple.

I can't find anything about validation in the Craft 3 plugin docs or migration docs from Craft 2, does anybody know?


texts: How to improve unexpectedly poor Craft performance?

texts:
We have a seasonal website which gets very popular around this time of year. This year we ported it from ExpressionEngine to Craft, for all the obvious reasons. We were very surprised to discover that the Craft version of the site is using considerably more resources than the old EE one. I'm looking for any advice on how to get this load down.

For info; both sites used the same dedicated Virtual Server, a quad core Xeon (minimum 800Mhz, burst to 2Ghz) with 8Gb RAM.

This weekend the Craft site was dealing with around 500 simultaneous visitors but pushing the CPU load to 7. By judicious use of the {% cache %} tags I dropped the queries per page from 200 to 20, and the load dropped to around 4-5.

Once the site is seeing 700 simultaneous visitors the CPU load is going into double digits and rapidly starts to spiral.

We had to switch out to a static scrape of the site. At the peak last year we were dealing with 1000 simultanious visitors and did not need to switch out to a static site.

I should point out that both sites are loading all their assets off Amazon S3, so none of those files are having an impact. This is purely about Craft being able to deal with the number of requests it's getting.

Why might Craft be performing so poorly in comparison, and how can I fix this?


texts: Front End Entry Form - File/asset field not saving when ajax submitted

texts:
I have a front end entry form which submits and saves fine when not using ajax.
But when i do submit via ajax the text fields etc save fine but the file/assets field will not.
I have stripped it right back for testing but still not saving the file on ajax submit.
I have even made the logged in user a full admin for testing purposes.
My Form:
<form method="post" id="applicationForm" class="sform2" accept-charset="UTF-8" enctype="multipart/form-data">
    {{ csrfInput() }}
    {{ actionInput('entries/save-entry') }}
    {{ hiddenInput('sectionId', '3') }}
    {{ hiddenInput('enabled', '1') }}
    {{ hiddenInput('entryId', '159') }}

    <label for="nameAccountIsHeldIn" class="col-12 col-form-label">Name account is held in</label>

    <input type="text" name="fields[nameAccountIsHeldIn]" class="form-control" id="nameAccountIsHeldIn" value="">

    <input type="file" name="fields[accounts][]" class="form-control" id="accounts" multiple>
    <button type="submit" class="btn btn-primary">Submit</button>

</form>

js:
$('.sform2').submit(function(ev) {
    ev.preventDefault();

    startAlerts();
    var data = $(this).serialize();
    var url = $(this).attr("action");

    console.log($(this));
    console.log(data);

    $.ajax({
        type: 'POST',
        url: url,
        data: $(this).serialize() ,
        dataType : 'json', // changing data type to json
        success: function (response) { // here I'm adding data as a parameter which stores the response
            console.log(response); // instead of alert I'm changing this to console.log which logs all the response in console.
        }
    });

});


texts: Sprout Form Date/Time field not displaying

texts:
I'm working on an inherited site where I have a sprout form and am adding additional fields. I have added a date/time field to the form with the settings in this screenshot.

In my template where all other fields are working I have added the following.

{{ craft.sproutForms.displayField('contact.targetProjectDate') }}

This field does not display and there is nothing in the source either.

Please advise


texts: Display entries based on 'entries fields'

texts:
I want to display blog entries within the related entry template linked together with 'entries fields':

-- Entrysection Bla

Blog
-- Blog entry 1 (Linked to Entrysection Bla via 'entries fields')
-- Blog entry 2 (no relations)

Now I want to display Blog entry 1 in Entrysection Bla

{% for entry in craft.entries.section('bla') %}
  {% for entries_fields in craft.entries.section('blog'){# related to ??? #} %}
     {{ entries_fields.title }}
  {% endfor %}
{% endfor %}

I figured it has to be done with relatedTo but I cant get it done. How do I have to write this?

-- Edit:

Now my code on Entrysection Bla looks like this:

{% set entries_fields = craft.entries.section('blog').relatedTo({
   sourceElement: entry,
   field: 'blogSaisonKategorie'
}) %}

{% for xy in entries_fields %}
   {{ xy.title }}
{% endfor %}

That prints out nothing. No error is displayed as well.


texts: Craft 3 Multi-site with no "default" site

texts:
I have setup a Craft 3 multi-site with the following configuration:

But what I really want is:

Additionally, I want to have a 'default' http://localhost:8888 so I can always redirect to /en or /es based on the browser language, but I don't want to add it as a site in the CMS through the admin panel, because I end up with a third unwanted version for each entry.

Which is the way to go?


texts:
Bear with me.

Shortly changing a site to run over https vs http - the issue is though that we need to maintain the Facebook open graph share data.

Facebook makes distinction between https and http. The way to maintain this is just to add <meta property="og:url" content="//www.myurl.com/segment/segment" />

Is there a variable I can access that would output the current URL without the protocol?


texts: What does the CategorySources plugin do?

texts:
A little off-topic, but wondering if someone can shed some light on the CategorySources plugin.

A client site has hundreds of articles (in an 'articles' structure) that are currently assigned to categories via a categories field. It would be great if they could view the articles by category (which I assume is what the plugin is for?). I installed, activated, and selected the category groups in the plugin settings, but I'm not seeing any obvious changes to the CP. Where are these mysterious category sources? Or am I missing the point? The plugin docs are a bit light on specifics.


texts: One database .... spinning off multiple domains?

texts:
Let's say I am selling products, with each vertical having their own domain, and one central portal that sells all the products. Is this possible with one installation of Craft?

Only one admin panel would be needed.


texts: A Structure section with an entry to a channel index

texts:
I don't have commenting privileges yet, so couldn't comment on either of these posts (here and here) regarding an entry in a Structure section that links to a Channel index. Between the two posts above I think I mostly understand what's going on, but have a question about an entry type for an entry in a Structure that essentially refers to a page that is a listing of Channel entries (basically an index page for the channel).

My situation: I have an About section with a few subpages that are dropdowns links under "About" in the main navigation bar: Vision, Leadership, and Qualifications. Vision and Qualifications are basically static pages, but the Leadership page lists a number of people (with corresponding images/titles/bios). So, I created a Channel section called "Leadership", each entry containing an individual. In the About section (Structure type) I created two entry types: "about" and "leadership". The "about" entry type has fields such as "body", "hero image", and "subheader" and is used for the static entries Vision and Qualifications. However, for the "leadership" entry type I'm uncertain what fields I should put in it. Since that one entry in the "About" section exists for the purposes of building the navigation, there isn't really any content in that entry. It's just there for the navigation link, and to get the user to a template (in my case templates/about/_types/leadership.html) that will output the individuals from the "Leadership" channel.

Does it make sense that I would just create a "leadership" entry type with no assigned fields (other than the default title), or is there a better way to approach this?


texts: Can I use official logo and images on my foreign site about Craft CMS? Are there any promo materials in good quality?


texts:
I'm trying to setup alternate locales for content across several sites. I have the following scenario:

- Group siteA
  - siteA.com/product-1

- Group siteB
  - siteB.com/product-2
  - siteB.com/fr/product-2

Content remains the same within a site group, where an entry in one locale is a translation of an entry another locale (as in Craft 2). Other site groups will have the same sections, but different content and perhaps locales. Propagating entries will not work in this case.

It's a scenario I've seen mentioned elsewhere, but I fail to understand the setup.

Is there a way to assign locales to multiple sites in general.php config the same way one would for siteUrl?

'production' => [
  'siteUrl' => 'siteA.com',
  'siteB' => [
    'en_gb' => 'siteB.com',
    'fr' => 'siteB.com/fr/'
  ]
],

Perhaps with alias?

Edit:

Ideally it would be something like propagating entries amongst site groups but not all sites, so product-2 would be propagated in siteB only.


texts:
Is there a way to assign category permissions to users so that they can only view/edit those categories?

I am currently looking at the following getEditableSections(), however, it's displaying all categories despite only assigning the user to a specific section. I have provided an example below:

Here's what I got:

Section Alpha
- Category A
- Category B
- Category C

Section November
- Category 1
- Category 2
- Category 3

Example: User John needs to access (view and edit) only Category B in Section Alpha.


texts:
Does anyone know of a way to send simple php mail from a twig template?

Something we can use like... {% mail 'Message', entry.userEmail %} or similar.

Would be good to not have to pre-define the content in a plugin.


texts: Correctly using eager loading in Plugin development

texts:
I'm trying to get some data with eager loading, which results in more queries than before.

Is there another way to tune down the number of queries as low as possible? As you can see i only need the posBrandKey (text) and id values.

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->status = null;
$criteria->limit = null;
$criteria->group = 'productBrand';
$criteria->with = array('posBrandKey');

$brands = array();
foreach ($criteria as $entry) {
    $key = $entry->posBrandKey;
    $brands[$key] = $entry->id;
}

My goal is to have the best performance possible, this is one of the many queries I call in the same script.


texts: How do I change the value of a select box field of a certain entry through the front-end?

texts:
So I'm having this entry (a product) that contains a selectbox field with two values:

Reserved
Available

By default this field is set to 'Available', but when the user lands on a certain page (a thank you page after "ordering" this product with the entry id as a querystring in the URL), I'd like to change the value of that selectbox to 'Reserved'.

Anyone can put me in the right direction on this one?

Thanks in advance!


texts: Getting fatal error when installing new plugin by hitting memory_limit

texts:
I am trying to locally install Craft Typed Link Field from the plugin store and I'm getting this PHP error.

I have already upped my memory_limit to 256M within my php.ini file, yet this is claiming to need 400M to run these updates.

I'd rather try to deal with the root cause instead of upping my memory_limit to 410M.

Trace is following:

A fatal error has occurred:

Status: Internal Server Error

Response:
PHP Fatal Error &#039;yii\base\ErrorException&#039; with message &#039;Allowed memory size of 268435456 bytes exhausted (tried to allocate 4096 bytes)&#039;

in /Users/name/project/build/vendor/composer/composer/src/Composer/DependencyResolver/Solver.php:220

Stack trace:
#0 [internal function]: yii\base\ErrorHandler-&gt;handleFatalError()
#1 {main}


texts:
I'm using the requirePermission tag in the templates for my Craft multisite. I only want users who have access to 'edit' that site be able to view it.

My code is:

{% requirePermission('editSite: (currentSite.id)') %}

It works fine when logged in as admin, however it returns a 403 for every other user, regardless of their permissions. Please help!

I'm aware I can use requireLogin but I want users to have access to some sites and not others


texts: Does Craft CMS support 'encryption at rest' / 'data at rest' encryption? I've looked here, here, and here - but can't find any info on this. Explain like I'm 5. Thanks.


texts: User registration form Solspace integration

texts:
Is there any way to integrate Salesforce with Craft's front-end user registration form? Is see Freeform has a nice Salesforce integration but for this project the data needs to be sent across when people create a new member account, and when they update their profile.

Anyone tackled this before? Thanks!


texts: Retrieving all users with specified permission

texts:
With a $user object, we can verify the user against a permission setting with the can() method. However, how can I retrieve all users who have a specific permission, including those under a group with the permission.

This needs to be generic PHP code as it's located in a service.


texts: Is there a tag to get the parents url like {{entry.url}}?

texts:
Is there a tag that can shorten the following:

{% set parentPage = entry.getParent() %}
{% if parentPage %} {{ parentPage.title }}
{% endif %}

Something like {entry.getParentUrl}?


texts: Filter entries with segments and params based on categories and fields

texts:
I'm working on a webshop with an advanced filter / search with multiple categories, entry types and fields and sorting options.

Schematic URL
site.com/template/entry.type/category/?size=category OR category&color=category AND category&checkbox=yes

Real world example
site.com/shop/woman/jeans/?size=s,m&color=blue,red&delivery=yes

What is the best way to show the entries? With search or relatedTo?

This is what I have so far:

{% if craft.request.getSegment('3') is not null %}
    {% set kind_slug = craft.request.getSegment('3') %}

    {% set categoryParams = {
        group: 'kind',
        slug: kind_slug
    } %}

{% else %}
    {% set categoryParams = {
       all kinds
    } %}
{% endif %}

{% set kind = craft.categories(categoryParams).first() %}
{% set size = craft.request.getParam('size') %} #}
{% set color = craft.request.getParam('color') %} #}

{% set params = {
    section: 'product',
    type: craft.request.getSegment(2),
    relatedTo: kind AND size AND color
} %}

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

I want the same functionality as this EE plugin: http://www.ralphmedia.co.uk/reefine/demo_basic


texts:
I have an entry with a dateOfBirth Date/Time Field.

Is it possible to calculate the current age from that field?

I can't find a craft/twig function/filter to calculate the difference between 2 dates.


texts: getVersionsByEntryId is deprecated. Can't find the new method?

texts:
We are using getVersionsByEntryId in our XML sitemap to return the number of times an entry has been saved, then comparing that with todays date and the date the entry was created to determine the changefreq over that time:

{% set revisions = craft.app.entryRevisions.getVersionsByEntryId(element.id)|default(1)|length %}

Looking at the docs however, this is now deprecated:

  DEPRECATED

  Deprecated in 3.2. Use an entry query instead.

I can't seem to find anything in the docs for an entry query? Could someone point me in the right direction?


texts: Fetching entries from an advanced search form on the front end

texts:
I'm trying to fetch entries from a channel via a front-end form featuring multiple filters - several dropdown selects and one checkbox field - kind of like an advanced search feature.

The form works OK when using the select dropdown fields but for some reason I can't get the checkbox input in the form to work. I have followed the example in the docs here.

This is what the checkbox part of the form looks like:

{# Checkboxes Based on a Checkbox Field #}
<label class="heading" for="features">Features</label>

{% for option in craft.fields.getFieldById(15).settings.options %}
    {% set checked = false %}

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

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

    <label>
        <input type="checkbox" name="fields[features][]" value="{{ option.value }}" {% if checked %} checked="checked"{% endif %}>{{ option.label }}
    </label>
{% endfor %}

This throws an error in the template:

  Key "selected" for array with keys "label, value, default" does not exist

On the line above:

{% if option.selected %}

Further, on my search results template, I'm using getParam to pull the values from the query string like so:

{% set location = craft.request.getParam('location') %}
{% set realEstateType = craft.request.getParam('type') %}
{% set bedrooms = craft.request.getParam('bedrooms') %}
{% set priceRange = craft.request.getParam('price-range') %}

and then

{% set results = craft.entries.search().location(location).realEstateType(realEstateType).bedrooms(bedrooms).priceRange(priceRange) %}

This works OK without the offending Checkbox field. I suspect because there are possibly multiple values submitted for a checkbox field that it may not work - should I use search instead of getParam?

Sorry for the long-winded question, any help would be appreciated.


texts: Change existing EntryModel custom attribute values

texts:
I am trying to change custom field values of a existing entry, but it won't save them in the database. It saves it on the model but the entry isn't persisted to the database.

craft()->on('guestEntries.success', function(GuestEntriesEvent $event) {
    if (!$event->fakeIt)
    {
        $entryModel = $event->params['entry'];
        if ($entryModel->section->handle == "aanvragen")
        {
            $form = $entryModel->formulier->first();
            if ($form)
            {
                // get all entries with that form
                $criteria = craft()->elements->getCriteria(ElementType::Entry);
                $criteria->section = "aanvragen";
                $criteria->relatedTo = array(
                    'targetElement' => $form
                );

                $total = strval($criteria->total());

                $form->getContent()->setAttributes(array(
                    'aantalAanvragen' => $total
                ));

                craft()->entries->saveEntry($form);
            }
        }
    }
}

This for example $form->setAttribute('slug', "testtestetst"); won't work.
Is there something i am missing here?

EDIT:

It seems that it was sticking on entry validation upon saving. There are some fields required. However these fields are already filled in, in the CP, i just want to update one field on a EntryModel is there a way to just do this.


texts: Running a console command produces an error mentioning sessions. How do I resolve?

texts:
None of the craft core console commands to work.
For example: ./yiic querygen all My_MyRecord produces an error which includes mention of session?

How do I get craft console commands working again?


texts:
In the CP, is it possible to assign a user group to selected entries within a section.

For example, say I have a section called Events. Within that section I have a fieldType called company.

Can I create a user group called Company 1 where users within it can only see/edit entries within Events section that has its company field selected as Company 1?

Trying to ascertain if its possible to allow users from multiple companies access to the CP, but heavily restrict what they can access.

Thanks!


texts: Can I call methods on an object represented by a string variable?

texts:
I tried the attribute twig function for this but that did not work.

Essentially, what I'd like to achieve is the following:

{# This string variable is a name of the object #}
{% set myForm = 'form' %}
{# I'd like to call the 'errors' method on the 'form' object #}
{% set formErrors = myForm.errors %}

The problem with the above code is that the errors method will be called on the myForm object instead of the form object.

Is there any way to achieve what I'm trying to do here?


texts:
Is it possible to further restrict asset filetypes than just "image"?

For example only allow .jpg, .jpeg and .png ?


texts: Clearing temporary assets from craft/storage/runtime

texts:
After some unsuccessful uploads I ended up with a lot of loose files in craft/storage/runtime/assets/tempuploads

They show up in the asset list when selecting assets for new entry. How do I remove them completely from the record?

Tried manually deleting them via FTP and running "Update Asset Indexes" but that didn't work. Also tried "Clear Caches" options.


texts:
I have 4 level product categories. For the menu I am building I need to pick a second category in all top level categories
So I get top level categories like so
{% set lv1Categories  = craft.categories.group('products').level(1) %}

How do I then get a second in the returned list?
{% set cat = lv1Categories[1] %}

This doesn't seem to work


texts:
Is it possible to add a border-radius to an Image Transform?

I'm using circular profile photos for a client. I could do the radius in CSS, but it'd be nice for the image to output with the radius.


texts:
I'm using the following URI format of a channel

{slug}-{restaurant.one().slug}-{locations.last().slug}-{locations.one().slug}

It throws a deprecation error caused by locations.last()

however when I use

inReverse().one()

instead, it doesn't work as expected.

final syntax

{slug}-{restaurant.one().slug}-{locations.inReverse().one().slug}-{locations.one().slug}


texts: Parent are not set anymore after saveElement()

texts:
In this code I try to create a new Entry and set a Parent to it.
The sectionId and the typeId are actually the same.
$navigationItem = new Entry();
$navigationItem->typeId = 4;
$navigationItem->sectionId = $navigationSection->id;
$navigationItem->title = $entry->title;
$navigationItem->setParent($herbsNavigationEntry);

$navigationItem->setFieldValue('navLink', '/tags/' . $entry->slug);

if (!Craft::$app->elements->saveElement($navigationItem)) {
    Craft::error('Couldn’t save the entry "' . $entry->title . '"', __METHOD__);
}

Before saving I get this:

But after the Craft::$app->elements->saveElement($navigationItem),
the parent disappears.
What did I wrong?


texts:
This one seems deceptively simple, but I am struggling.  My home page is a single, and in that template I want to retrieve the children of a specific entry in a structure, then loop through them.  Here is a code example that does not work:

{% set entries = craft.entries.id(4).children %}
{% for entry in entries %}
    do something
{% endfor %}

This returns the page with id 4 instead of its children.

I also tried something like:

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

Maybe I need to retrieve the entire section and do a conditional loop for entries where the parent entry ID is 4, but the proper syntax for that eludes me.

Could someone please point me in the right direction?  Thanks!


texts: Is there a way to make Disqus notify an entry author when a new comment is posted?

texts:
I'm setting up a multiple authors blog and one of the requirements provided is that authors be notified when someone posts a new comment. We're planning to use Disqus for comments, and that will notify the moderators in Disqus by default, but it's not really an option for us to add all authors in craft as moderators in Disques. Maybe this is just a limitation with Disqus.

In googling for an answer it seems that someone found a way to do this in Wordpress with a plugin. (http://wpdailybits.com/blog/notify-post-author-for-new-comment-disqus/45) Would it be possible to do something similar in Craft perhaps?


texts: Avoid saving $_POST in Craft logs for certain URLs

texts:
We know that Craft logs the $_POST variable in web.log. I wonder if we have some sensitive data going through the server side (collected from a front end form), even if we don't save it in the database, it can still potentially end up in Craft's logs, isn't it? E.g. when there's an error during the form submission.

Is there any ways which we could avoid saving the $_POST variable in the log, just for certain URLs?


texts: Plugin's action URL not working and showing 404 error

texts: I created a plugin to schedule some custom email notifications. The action URL is working perfectly on localhost but isn't working on stagings server. Is it related to any server stuff.