texts:
I'm attempting to install the Contact Form plugin. I believe that I've uploaded the correct folder to the correct location, but it's not showing up in the control panel. I'm relatively new to Craft, so this is the first plugin that I've installed.

This is my folder structure:

I've seen a couple questions that indicate that the most common problem is improper capitalization on the plugin folder. However, as you can see, mine is all lower case.

I'm building this site on a Linux localhost and I've even gone so far as to chmod 777 plugins -R just to be sure it's not a permissions issue.

I've made sure to clear caches after every change, but no matter what I do I can not get the plugin to show up in the CP.

What else should I look at to diagnose and fix this?


texts: Filter users: in group AND not in other group

texts:
Please could you advise on how to filter a user query, so that users from Group A are included, but not if they are also in Group B?
{% set vnp_users = craft.users
    .group(['groupA', 'not groupB'])
    .orderBy('field desc')
    .all() %}


texts:
The StringHelper::normalizeKeywords() doesn't work as I expected.

When I normalize überblick it leads to the expected result:

StringHelper::normalizeKeywords('überblick') -> ueberblick

But when I normalize ÜBERBLICK I expect it also to be ueberblick but it actually returns überblick.

It could be fixed by adding the missing ASCII mappings (e.g. 196 => 'Ae') to the StringHelper::getAsciiCharMap() method or converting the string to lowercase before replacing the characters in StringHelper::normalizeKeywords() on lines 358 - 362:

-> switch these two lines:

// Remove punctuation and diacritics
$str = strtr($str, static::_getCharMap());

// Normalize to lowercase
$str = StringHelper::toLowerCase($str);


texts:
I realise this is very much a Redactor question, but was wondering if anyone has figured out how to apply custom classes to UL's and OL's in Craft using the formattingAdd options?

I've tried the following but it just won't apply to any unordered lists I create:

{
  tag: 'ul',
  title: 'Large list',
  class: 'large'
}


texts:
I want to provide an easy way to make exponent style text in the Redactor field type.

Is there a Redactor plugin to do that?

If no what is the best way to handle that?

1/ HTML superscript tag

This text contains superscript text.

or
2/ CSS custom Redactor class

.sup {
    vertical-align: super;
    font-size: smaller;
}


texts:
I have a relatively simple task which is exposing an issue with efficiency. In that it isn't very efficient and the server cries and quits. Here's the high level overview:

There's a category called "Locations". There are 791 locations.
Users have three Category Fields; First Choice, Second Choice, Third Choice. The pick one location in each field. There are 1809 Users.

I need to generate a report that shows how popular each location is (how many Users chose [LOCATION] as their 1st, 2nd, and 3rd choice). A nice simple table that's 4 cells wide and 791 rows deep.

I keep running out of memory and execution time regardless of how high I take each limit. I've tried it in Twig and I've tried it in PHP as a plugin.

My strategy, via creating a Service and a Variable... :

{% set locations = craft.categories.group('locations').limit(null) %}
{% set users     = craft.users.group('members').limit(null) %}

{{ craft.reporting.locationPopularity(locations,users) }}

The ReportsService.php file:

public function locationPopularity($locations = null, $users = null) {
    $response = "";

    foreach($locations as $location) {
        $firstChoiceCount = 0;
        $secondChoiceCount = 0;
        $thirdChoiceCount = 0;

        foreach($users as $user) {
            if($user->firstChoiceLocation->last() == $location){ $firstChoiceCount += 1; }
            if($user->secondChoiceLocation->last() == $location){ $secondChoiceCount += 1; }
            if($user->thirdChoiceLocation->last() == $location){ $thirdChoiceCount += 1; }
        }

        $response = $response . "

$location->title

First Choice: $firstChoiceCount, Second Choice: $secondChoiceCount, Third Choice: $thirdChoiceCount.
";
    }

    return $response;
}

How do I get this to work? 1,430,919 loop iterations seems to be a no go.

The following works, but 2400+ queries...

{% for location in craft.categories.group('locations').limit(null).find() %}
    {% set firstChoiceCount = craft.users.relatedTo({
        element: location,
        field: 'firstChoiceLocation'
    }).limit(null).count() %}

    {% set secondChoiceCount = craft.users.relatedTo({
        element: location,
        field: 'secondChoiceLocation'
    }).limit(null).count() %}

    {% set thirdChoiceCount = craft.users.relatedTo({
        element: location,
        field: 'thirdChoiceLocation'
    }).limit(null).count() %}

    ... output ...
{% endfor %}


texts: Including block templates under different subdirectories

texts:
How do I include block types that don't all sit under the one directory? My folder structure:

 - images
  - _blockName.html
 - mockups
  - ...
 - text
 - special

How I'm currently including the blocks (which isn't working):

{% extends "_layout" %}

{% block content %}
    {% for block in entry.widgets %}
        {% include "widgets/_" ~ block.type ignore missing %}
    {% endfor %}
{% endblock %}

How do I let craft know to look under each subdirectory?


texts: Why would I get a "CHttpRequest is unable to determine the request URI" when creating a migration?

texts:
I have logged into the server and attempted to create a migration for my plugin.  However I get this output:

exception 'CException' with message 'CHttpRequest is unable to determine the request URI.'

The request is targeting "/craft/app/framework/web/CHttpRequest.php:519".

Stack trace:
#0 /craft/app/framework/web/CHttpRequest.php(431): CHttpRequest->getRequestUri()
#1 /httpdocs/craft/app/services/HttpRequestService.php(816): CHttpRequest->getPathInfo()
#2 /httpdocs/craft/app/services/HttpRequestService.php(43): Craft\HttpRequestService->getNormalizedPath()
#3 /httpdocs/craft/app/framework/base/CModule.php(387): Craft\HttpRequestService->init()
#4 /httpdocs/craft/app/framework/base/CModule.php(103): CModule->getComponent('request')
#5 /httpdocs/craft/plugins/redactorclips/RedactorClipsPlugin.php(31): CModule->__get('request')
#6 /httpdocs/craft/app/services/PluginsService.php(136): Craft\RedactorClipsPlugin->init()
#7 /httpdocs/craft/app/etc/console/ConsoleApp.php(53): Craft\PluginsService->loadPlugins()
#8 /httpdocs/craft/app/framework/base/CApplication.php(165): Craft\ConsoleApp->init()
#9 /httpdocs/craft/app/framework/YiiBase.php(121): CApplication->__construct('/var/www/vhosts...')
#10 /httpdocs/craft/app/etc/console/yiic.php(76): YiiBase::createApplication('Craft\ConsoleAp...', '/var/www/vhosts...')
#11 /httpdocs/craft/app/etc/console/yiic(4): require_once('/var/www/vhosts...')


texts: Dashboard Widget: Access widget settings from controller / service

texts:
i wrote a plugin with an additional dashboard widget.

i have to refresh the widget data every hour with ajax. so i added a plugin controller in my plugin directory with the idea of re-rendering the widget template (called through ajax).

1) how can i (correctly) access the widget instance from the controller (or service)?

my try is $widget = craft()->dashboard->getWidgetType('name'). this gives me the correct instance. is this the right way?

2) no settings data from widget (needed in widget template)

in the widget template i need access to the widget settings (defined in the widget class with defineSettings()).

in the controller, i get the widget instance (as described in point 1) and do $widget->getBodyHtml(), but the settings attributes are empty. all other parts of the template are rendered correctly.

when the widget is rendered the first time (no ajax request), anything seems to be fine (settings loaded correctly).

can anyone explain my fault?


texts: Is there an accessible callback when Craft.EntryTypeSwitcher is run?

texts:
When a user switches Entry Types in the control panel, Craft.EntryTypeSwitcher is trigged which in turn triggers onTypeChange.

Is there callback that a plugin can access to run some additional JavaScript after this event has occurred?

===== Edit to show Current work-around as per Justin's answer below ======

(function($) {
    Craft.LoadOverride = Garnish.Base.extend({
        init: function()
        {
            this.addListener(Garnish.$win, 'resize', 'runOverride');
        },
        runOverride: function()
        {
            console.log('Triggered!');
        }
    });
})(jQuery);


texts: How to link to prev/next entry depending on related data?

texts:
I am quite new to Craft and I am not sure how to get a prev/next link only for entries with related data in a specific field.

My situation:
I have a Structure (let's call it sourceEntry) with an optional field (can be empty or can have related data, let's call this one relatedData). That field is of type entries. So sourceEntry is related to other entries (I'll call them targetEntry).

Assuming I am on the entry's detail page (so, my sourceEntry object is just accessible via entry in my twig template) I would do this to link to previous/next entry:

{% set criteria = {section: 'sourceEntry' } %}
{% set prev = entry.getPrev(criteria) %}
{% set next = entry.getNext(criteria) %}
{# …and then just insert the links… #}

But in my case I need to get the prev/next entry that has set relatedData respectively I'd link to the prev/next entry that is related to targetEntry.

Example:
I have five entries of type sourceEntry: A, B, C, D, E.
The relatedData field for two of them is empty: B, C.
The others are related to posts of type targetEntry: A, D, E.
When loading the detail page for A there should be a next link to D, on detail page for D there should be a next link to E and a prev link to A and so on.

How am I able to achieve this? Thanks in advance!

EDIT:

This is the solution for those who are too lazy to click the link in Bob Olde Hampsink's answer:

{% set criteria = {section: 'sourceEntry', relatedTo: craft.users } %}
{% set prev = entry.getPrev(criteria) %}
{% set next = entry.getNext(criteria) %}
{# …and then just insert the links… #}

I feel kind of dumb now not even been trying this on my own before (although I knew about relations, but I wasn't sure how to set the criteria object properly). Thanks, Bob Olde Hampsink!


texts: Create a new row every 3 items in a matrix

texts:
I need to output a row every three items in a matrix. Here is what I have so far. The problem is that this outputs a row every three items but it duplicates each matrix item three times and puts them in a row rather than taking the items as they come. Any help here would be very much appreciated Thanks.

{% set aboutInfo = entry.imageLinkBoxes %}
{% set infoGrouped = aboutInfo|batch(3) %}

{% for group in infoGrouped %}
    {% for block in entry.imageLinkBoxes %}

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

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

                {% for entry in group %}

                                    {{ block.entry.first().title }}

{{ block.text }}

                {% endfor %}

        {% endif %}

    {% endfor %}
{% endfor %}


texts: How to fill the custom fields of users from the front-end form?

texts:
how can i fill custom fields from the front-end form ?

https://craftcms.com/docs/templating/user-registration-form


texts:
I have a hero textbox that I would like to control from the base template using a simple if/elseif.

I have a field called "hero" for the homepage. For pages in the "Small Groups" section, I want the hero to say "Groups." For everything else, I want it to be the entry title.

It seems straightforward, but this isn't working? It is ignoring the elseif.

{% if entry == craft.entries.section('homepage') %}
    {{ entry.hero }}
{% elseif entry == craft.entries.section('smallgroups') %}
    Groups
{% else %}
    {{ entry.title }}
{% endif %}


texts: Craft 3: Struggling with CRAFT_BASE_PATH and CRAFT_VENDOR_PATH

texts:
I am struggling with the definition of CRAFT_BASE_PATH and CRAFT_VENDOR_PATH in web/index.php:

My absolute URLs are as follows:

/home/xxx/public_html/craft/ (not publicly accessible)

and

home/xxx/public_html/web/ (publicly accessible)

Thank you very much for your help!


texts: Is it possible to access backend fields from my own field type?

texts:
I'm trying to access the value of an asset field in a backend entry form from my plugins own field type.

At the moment it's looking like the following:

public function prepValue($value)
{
    $filename = "path/to/csv";

    if( ($handle = fopen( $filename, "r")) !== FALSE) {
        $rowCounter = 0;
        while (($rowData = fgetcsv($handle, 0, ";")) !== FALSE) {
            if( 0 === $rowCounter) {
                $headerRecord = $rowData;
            } else {
                foreach( $rowData as $key => $val) {
                    $value[ $rowCounter - 1][ $headerRecord[ $key] ] = $val;
                }
            }
            $rowCounter++;
        }
        fclose($handle);
    }
    return $value;
}

All of the csv values are mapped to a table column of the same field type:

public function getInputHtml($name, $value)
{
    $id = 'test';
    $cols = array(
        'col_1' => array(
            'heading' => 'Col 1',
            'type'    => 'singleline',
        ),
        'col_2'   => array(
            'heading' => 'Col 2',
            'type'    => 'singleline'
        ),
        'col_3'   => array(
            'heading' => 'Col 3',
            'type'    => 'number'
        ),
        'col_4'   => array(
            'heading' => 'Col 4',
            'type'    => 'number'
        ),
        'col_5'   => array(
            'heading' => 'Col 5',
            'type'    => 'singleline'
        ),
        'col_6'   => array(
            'heading' => 'Col 6',
            'type'    => 'singleline',
        ),
    );

    return craft()->templates->render('csvImport/csvimport', array(
        'name'  => $name,
        'value' => $value,
        'id'    => $id,
        'cols'  => $cols,

    ));
}

I would like to fill $filename dynamically with the value of an asset field in the same entry backend form. Is this possible?

//EDIT:

Ok I solved the above problem by just changing the prepValue() to the prepValueFromPost()-Function. I now am able to access every piece of data I want to through the post array.


texts: Trying to determine if there is a method for getting an entry's last modified date, preferably date-time. Gave a good look over the docs and some searching and couldn't find anything other than the original creation date. Thanks.


texts: Working on a Wordpress migration at the moment, and all the post URLs are http://sitename.com/post-url, and I need to redirect them to their new home at http://sitename.com/article/entry-url. It's difficult because there obviously isn't a catch-all URL segment I can use because all posts use first segment. I could go the .htaccess route but there are >2k posts so that would be monstrous. There's a good Redirect Manager plugin where you can set a catch all template and then handle redirect in there, but I'd have to separately write a bunch of Route exceptions for other pages on the site. Anyone think of a good approach?


texts: How do you save a new Entry to be enabled on 2+ Sites?

texts:
I've made a plugin that let's you import Entries from a CSV file and I'm working through adding localization (Sites) support to it, but I can't figure out the right way to enable an Entry for a second Site.

$entry = New Entry();
$entry->authorId = $authorId;
$entry->sectionId = $sectionId;
$entry->typeId = $typeId;
$entry->enabled = true;
$entry->title = $title;
$entry->Slug = $slug;
$entry->siteId = $firstSiteId;

$entry->setFieldValues($attrs);

Craft::$app->elements->saveElement($entry);

Everything above works, but it's this next part which I can't get to work properly. It just throws errors about violating the constraint for a duplicate element ID/site ID pair:

$entry->siteId = $secondSiteId;
Craft::$app->elements->saveElement($entry);

I also tried this, but the query never returns any results:

$findTheNewEntry = Entry::find()
    ->sectionId($sectionId)
    ->id($entry->id)
    ->status(null)
    ->siteId($secondSiteId)
    ->one();

$findTheNewEntry->enabled = true;
Craft::$app->elements->saveElement($findTheNewEntry);

I wish it was as simple as being able to provide an array or such for ->siteId but I know that's wrong.


texts: How Do I show advanced Date filters for Events?

texts:
I am trying to setup an events section similar to that of Yelp's Events.  They have a listing of all the upcoming events and have filters on the side for "Today, Tomorrow" etc...

I received help from Brandon Kelly and will be posting my answer below.


texts: Reset shipping method on cart empty and order complete

texts:
Is it possible without a plugin?

Our client desperately wants the shipping method to be reset (not selected) after an order has been placed or the empty cart button is clicked.

Edit: The shipping method does indeed reset after a completed purchase. Apologies. Regardless, reset on empty cart is still an issue.

Thanks


texts: Live Preview not showing correct content when using single page app with JavaScript

texts:
So I am creating a website using Craft with JavaScript for making it a single page app. I load my layout which then calls the pages which works well.

The only problem is that when viewing pages through Live Preview I can't load the content. The layout gets loaded but not the content that the JavaScript adds calling for the pages. At first I thought it might be a problem with JavaScript in the iframe, but I don't think this is the issue.

I think the calls to my JavaScript is getting the saved data from the DB and not the data from the Live Preview.

How can I make Live Preview work with my single page app? Would somebody be able to explain how Live Preview works? Can I watch for the update event so that I can update the page with the Live Preview data?


texts: Output entries sorted by category title and paginate

texts:
I'm stuck on an issue where I have to paginate a list of entries that would be sorted by category title.
So basically, I need to:

fetch entries in the 'project' section
sort those entries by the 'projectYear' category title (2016->2002)
paginate it (limit 5 for example)
sort entries by title (a->z)

The output expected would look like this

Page 1
    2016
        Project A
        Project B
        Project C
    2015
        Project D
        Project E
Page 2
    2015
        Project F
        Project G
    2012
        Project H
    2010
        Project I
        Project J

At the moment, I have this "working"

{% set categories = craft.categories({
    group: 'projectYear',
    title: 'not Unknown',
    order: 'title desc'
}) %}

{% set allProjects = craft.entries({
    section: 'projects',
    relatedTo: categories,
    order: 'title asc'
}) %}

{% for year, projectsInYear in allProjects | group('projectYear.first().title') %}
    {{ year }}
    {% for project in projectsInYear %}
        {{ project.title }}
    {% endfor %}
{% endfor %}

By "working" I mean that it outputs all project entries sorted by title & grouped by projectYear... but those projectYear groups are not sorted by title and it also lacks a pagination system.

FYI: If I limit to 5 in craft.entries, it outputs the 5 first entries sorted by title and groups them by year after that. Instead, I want it entries to be first grouped by year and then get the 5 of those first entries.

Could anybody help me figure out how I can get the output I want or lead me in the right direction?

Thanks!

PS: we used postDate originally and it worked great, but we had to move from using postDate so it's not a possibility anymore.


texts: Does Craft CMS have skeletons/starter/boilerplate templates?

texts: I'd like to set-up quickly blog on Craft CMS and I wonder if there are any starter templates available? It would be really useful.


texts: Redirecting after login based on user group

texts:
I'd like to control where a user gets re-directed after login based on the user group. That is, userGroupA logs in and is sent to /templateA/_entry, while userGroupB logs in and is sent to /templateB/_entry.

I understand that postLoginRedirect can be used dynamically. Are there any examples of this?

Thanks!


texts:
I'm trying to update my plugin to Craft 3 and I'm getting this error message:

Unable to locate message source for category ''.

What does it mean?!


texts: ArrayHelper::stringToArray creates sometimes index array

texts:
It looks like the craftcms 2 ArrayHelper created indexed array on large strings. But I'll need a none indexed array. Any ideas what I'll do wrong? Running on php 7.1.
$playerIds = ArrayHelper::stringToArray(craft()->myFlowPlugin->parseString($triggeredFlow->settings['playerIds'], $attributes));
$playerIds = array_unique($playerIds);
$notification->playerIds = $playerIds;

Incorrect with large strings
"include_player_ids":{
    "0":"17cdd77a-0864-4886-94d9-d47faf487848",
    "1":"645daf21-6829-4eg5-ba1b-d07dbe642dab",
.....
}

Correct
"include_player_ids":[
    "4a0d5945-f996-5561-b5f3-a1c95012a9db",
    "d3dba787-2cde-489b-bef3-96df5db46261",
    "993d15ea-2f18-4d88-9de0-35b0e4be1b14",
.....
]


texts:
I am trying to eager load an asset field that contains 4 images.

When I originally set my entries the order was not affected as written below:

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

I then went and changed my set to leverage eager loading and upon doing so the order of the images was pretty much randomized throughout the template:

{% set products = craft.entries({
    section: 'products',
    with: [
        ['productImages', {
        withTransforms: ['small']
        }],
        'colorSelection']
}) %}

I then tried to add an order param next to withTransforms which did not have any effect either.

Is this a known issue?

UPDATE:

{{gender}} - {{product.displayTitle}}

            {{product.price}}

Is how we are templating out each entry. Both provide a different order of assets.


texts: Is there anyway to send a custom field by email? For example if a customer were to enter a shipping note and submits an order is there a way to send that note to an email address?


texts:
So I have a Entry type that has two custom fields on it. Both fields are integer fields. I'd like to make a query in PHP that gets the entries by two custom fields, both of which are integer values. Here is my code so far:

    $query = [
        'year' => $year,
        'quarter' => $quarter,
    ];
    $seasonBoxes = \craft\elements\Entry::find()
                 ->section('boxes')
                 ->search($query)
                 ->orderBy('dateCreated asc')
                 ->all();

Please note: $year is independent of the entry creation date so I can't use the date filters.


texts: Existing website written in PHP Zend Framework

texts:
I manage our corporate marketing website, which is written in PHP and the Zend Framework and is hosted on LAMP servers.  I've been tasked with moving the website to a CMS so other folks on the marketing team can update content without having my dev team be the bottleneck for content publishing and changes.

However, our existing site is more of a web application, in that we use the Zend Framework and PHP code for back-end integrations with HubSpot, WebEx, etc. and various CRON jobs that hit endpoints on our site to do various jobs.

My concern is - how do I maintain the site as a web application without having to rewrite all that functionality in the language of the CMS.  I'm trying to see if I can split the site into two pieces 1) the majority of the static pages powered by the CMS, and 2) the web application stuff that can remain powered by Zend Framework.  Does anyone have experience doing this?

My concern is if I send some traffic to www.site.com/A and other traffic to www.site.com/B (A being the CMS and B being the web app) how do I handle common layout code like navigation and footer?  Meaning if you update the nav in the CMS, this won't magically appear on the web app side.


texts: Finding corresponding category in different subtrees of a category group

texts:
I'm building a language switcher for a clients website. The website consists of multiple regions which can have multiple locales. As regions aren't supported yet in Craft 2, I've worked my way around that in a variety of ways.

For my products section, I have a category group of product categories. The top level of each tree within that group is the region a product belongs to. So you can have something like this:

US

Category US A

Category US A 1

Europe

Category Europe A

Category Europe A 1

So when selecting category 'US A 1' I know the region this product needs to be shown in is US and I have the correct category too.

Now when switching languages, I check if the region also changes. If so, I have the ID of the new region (which is the first level category of a tree within that group). So, I check if this entry exists related to that category ID.
If so I need to find the exact same subcategory in the Europe tree as was selected in the US tree (so find 'Europe A 1') and check if the entry is also related to that category. If so, send the user to that URL. Problem is I don't know how to do that last step as all I'm getting is an array of categories without any hierachy.

Important: I need this in a plugin in PhP so no Twig.

UPDATE

The only link between for example: 'US A 1' and 'Europe A 1' will be the slug. I'll have to enforce the client to make sure similar categories share the same slug. (Thanks to carlcs to ask this important info I forgot to mention :)


texts: How to find the block type of Super Table field that is inside a Matrix field

texts:
I'm making a front-end entry form with a Super Table field that is inside a Matrix field. Super Table docs at https://verbb.io/craft-plugins/super-table/docs/template-guides/front-end-form have an example with the following code to figure out a block type of Super Table field:

{% set fieldHandle = 'mySuperTableField' %}
{% set field = craft.fields.getFieldByHandle(fieldHandle) %}
{% set blocktype = craft.superTable.getSuperTableBlocks(field.id)[0] %}

If in my case I have a Matrix field with handle myMatrixFeild that contains mySuperTableField, how do I find out the block type of mySuperTableField?


texts: Organizing Entry, Section, and Category hierarchies

texts:
I have a site with three broad sections of content:  Humanities, Business, and Music.

Within each of these are sub-sections. Under "Humanities", for example, is Politics, History, Economics, etc. Within these are more sections as well.

What's the correct way to organize such a hierarchy?

For each index page, I want all of the posts for the entire hierarchy below it. So going to /humanities would have a feed of all of the latest entries for every section below it. Navigating to /humanities/politics/ would show just politics and its subsections.

I've looked at using categories, but want the url structure to reflect all the way down the chain. Is this possible?


texts:
I have a low-budget project where would like to migrate an academic website to Craft. The website contains 15000 proverbs about women in different cultures that can be searched, (http://www.womeninproverbsworldwide.com/the-proverbs/search/index.php).

I consider making each proverb an entry. Will search perform fast enough with 15000 entries or should I consider a different approach?

Thank you for sharing your opinion!


texts:
I see that there are Trimmer and Truncate out there that have been created for truncating text but I don't believe either does what it is I'm looking for.

I'd like to truncate text similar to how Hacksaw for ExpressionEngine works. Allowing me to allow or disallow html tags, and making sure that even if it cuts off before a tag is closed, that it automatically properly closes the tag. I wouldn't want to turn the entire lower half of my page into a hyperlink for instance if i happen to truncate mid-link. I do want to maintain the ability for links to be in the text that is being truncated, and multiple paragraphs, etc. however.

Any tips would be fantastic.


texts: Why would I choose Channels as opposed to Structures

texts: I can sort structures alphabetically, by date or by specific field. Structures also allow me to sort by the order specified in the Control Panel. So what is the use case for using Channels instead of Structures? Is there a performance cost? Is there anything that I'm missing?


texts: Redactor customisation not showing in Redactor text field

texts:
I've set up a custom redactor .json file which works and shows up on the dropdown, however, whenever I'm selecting one of the options the text in the field isn't updating to the chosen style.

I've attached some images so you can see what I mean:

It works on the front end but I'm a little puzzled why it's not showing on this side.

This is the first time I've done custom redactor options before so I could've potentially missed a step on getting it to work? I've had a look in the docs and couldn't find what I was looking for so any help would be appreciated.

Cheers


texts: How can I relate a FK back to the purchasable ID?

texts:
First off, HUGE thank you to Lindsey for opening this door for me. Opened up a whole new layer!

I have (another) plugin that is listening to the commerce_orders.onOrderComplete event. My plugin inspects the order, and if a specific product was purchased, I capture that and save the pre-defined values in a custom table.

For example, if you buy "Product A", you get to pick two "Product B" options (these options are defined in commerce/CP).

I am able to create the custom table and save the correct values - so far so good.

However, I would like to relate not only the user back to the user account, but the "Product A" back to the purchasable.

Something like this:

MyPluginRecord.php

public function defineAttributes()
{
    return array(
        'id' => array(AttributeType::Number, 'default' => null),
        'packageId' => array(AttributeType::Number, 'default' => null),
        ...
    );
}

public function defineRelations()
{
    return array(
        'element' => array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' => true, 'onDelete' => static::CASCADE),
        'package' => array(static::BELONGS_TO, '????', 'id', 'required' => true, 'onDelete' => static::CASCADE),
    );
}

I'm not sure how to get back to the commerce purchasable record?

Thank you for any suggestions!


texts:
I've created two global variables which my content creator is going to use to turn off a bunch of articles and turn on a bunch more which a slight change in the Global.  I have a page where there is a limit of 5 of these articles.

{% set entries = craft.entries.section('news').order('articleOrder desc').limit(5).find() %}

{% for entry in entries if entry.currentYear2 == currentEdition.currentYear2 and currentEdition.currentMonth2 in entry.currentMonth2 %}
    <h2>{{ entry.title }}</h2>
{% endfor %}

The problem with this is that the conditional only gets 5 entries to compare, and not the entire bunch. I want to first run an if statement on all the entries, then let me do a for loop with a .limit(5). I am not sure how to go about this. A conditional combined with a for loop in the same statement did not work either.


texts: Can't update or install plugins locally, macOS

texts:
I'm unable to update or install plugins in Craft 3.
Running in macOS via MAMP, PHP 7.0.8.

Error: The "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
Failed to enable crypto
failed to open stream: operation failed

Output: Loading composer repositories with package information
Updating dependencies
Package operations: 8 installs, 0 updates, 0 removals
  - Installing psr/cache (1.0.1): Downloading (connecting...)Downloading (failed)
Downloading (connecting...)
Downloading (failed)
Downloading (connecting...)
Downloading (failed)

Has anyone run into this situation or have any suggestions as to how to get around it?


texts: Erros when using Entry Variable in craft.app.feeds.getFeedItems

texts:
I'm processing some feeds using craft.app.feeds.getFeedItems() and it works if I pass the limit as a hard coded number like this:

{% set items = craft.app.feeds.getFeedItems(entry.rssURL, '5') %}

    {% for item in items %}

{{ item.title }}

    {% endfor %}

However if I change '5' to a field handle I get errors. where entry.feedLimit is a number such as 3 or 5

{% set items = craft.app.feeds.getFeedItems(entry.rssURL, entry.feedLimit) %}

    {% for item in items %}

{{ item.title }}

    {% endfor %}

The errors I get is:

  TypeError Argument 2 passed to craft\feeds\Feeds::getFeedItems() must
  be of the type integer or null, object given, called in
  /path/to/vendor/twig/twig/lib/Twig/Extension/Core.php
  on line 1619

This code was previously working on Craft 2, but after the update it is now broken. I've temporarily hard coded the limit in, but that's not ideal.


texts: doublesecretagency business logic module template: 404 on example form action

texts:
I set up the business logic module template following these instructions:
https://doublesecretagency.github.io/craft-businesslogic/installation

The test works out well, so everything seems to be in order.

However, when I add the example action to a form and submit it, I get a 404:

Unable to resolve the request "business-logic/example/example-form-submit".

How do I find and fix the underlying issue?

EDIT: I tried setting up a module via https://pluginfactory.io/ and that works like a charm.


texts: How do _you_ protect input against XSS? ("HtmlPurifier"?)

texts:
I've been playing with Craft for days now and love it. I'm new to Yii but I think I got the hang of everything and how you develop a Craft Plugin. My question is regarding security on input post/get vars.

Reading Yii's documentation is seems the "HtmlPurifier" filter is suggested to protect against XSS - but everything seems to be applied on output?

My question is: Does Craft do anything to "clean" input data OR how do you protect your data against malicious input?

I want to clarify that the data submitted by the user has gone through the validation rules in the Record/Model. Is there anything else you need to keep in mind?


texts: How can I automatically generate responsive images from a single hi-res asset?

texts: I want to be able to upload a single high resolution image, and output a <picture> element that outputs it with a few different sizes and resolutions automatically (using Picturefill to sort out which one actually shows up to the browsers). How can I do that?


texts: Simplifying code using the new andRelatedTo param

texts:
I have the following code that works with Sprig. But with the new andRelatedTo param, I am wondering if this could be simplified? However, I am a little unsure if/where to start on this and how the new andRelatedTo would replace existing code.
Can anyone steer me in the right direction?
{% set defaultLimit = 35 %}
{% set search = search ?? '' %}
{% set sort = sort ?? 'title ASC' %}
{% set limit = limit ?? craft.app.request.queryParam('limit') ?? defaultLimit %}
{% set page = page ?? 1 %}
{% set category = craft.categories.id(_categoryId).one() %}

{# {% set alllowedEntryTypeHandles = ['sponsored', 'free'] %} #}
{% set limitOptions = [2, 5, 10, 25, 35, 50, 100, 'All'] %}
{% set limit = limit in limitOptions ? limit : defaultLimit %}

{% set params = {
  limit:limit,
  page: page,
} %}

{% set relatedParams = ['and'] %}
{% set relatedParams = relatedParams|merge([]) %}
{% set filterIds = '' %}

{% set pcdQueryString = null %}
{% set cbQueryString = null %}
{% set finishQueryString = null %}

{% if craft.app.request.queryParam('pcd') %}
  {% set pcdQueryString = craft.app.request.queryParam('pcd') | join(',') %}
  {% set filterIds = filterIds ~ ',' ~ pcdQueryString|join(',') %}
  {% set relatedParams = relatedParams|merge([pcdQueryString]) %}
  {% set params = params|merge({pcd:pcdQueryString}) %}
{% endif %}

{% if craft.app.request.queryParam('cb') %}
  {% set cbQueryString = craft.app.request.queryParam('cb') | join(',') %}
  {% set filterIds = filterIds ~ ',' ~ cbQueryString|join(',') %}
  {% set relatedParams = relatedParams|merge([cbQueryString]) %}
  {% set params = params|merge({cb:cbQueryString}) %}
{% endif %}

{% if craft.app.request.queryParam('finish') %}
  {% set finishQueryString = craft.app.request.queryParam('finish') | join(',') %}
  {% set filterIds = filterIds ~ ',' ~ finishQueryString|join(',') %}
  {% set relatedParams = relatedParams|merge([finishQueryString]) %}
  {% set params = params|merge({finish:finishQueryString}) %}
{% endif %}

{# SAERCH #}
{% if craft.app.request.queryParam('search') %}
  {% set params = params|merge({search:search}) %}
{% endif %}

 {% set filterTags = craft.entries
   .id(filterIds)
   .orderBy('title ASC')
   .all() %}

{% set allProductsQuery = craft.products
  .relatedTo(category)
  .all() %}

 {% set productsQuery = craft.products
   .search(search)
   .with( [
     'department',
     'productImage',
     'finish',
     'pcd',
     'variants',
     'thread',
     'seat',
     'hexHead'
   ])
   .orderBy(sort)
   .limit(limit)
   .relatedTo(relatedParams) %}

{% do sprig.pushUrl('?' ~ params|url_encode) %}


texts: Get additional category field when outputing entries grouped by categories

texts:
I followed this sample code from craft cookbook to display my entries grouped together by category within a category group.

To add some context, the site I'm working on is for a dictionary and the words in the dictionary are the main entries. There are several category groups that I use to classify the words. For example, words can belong to different themes: household items are in the household category, names of animals are in the nature category and so on. So far, here is the code I have below:

{% set entriesByCat = {} %}
{% set entries = craft.entries.section('words') %}
{% set cats = craft.categories.group(themes) %}

{% for cat in cats %}
  {% set entries = entries.relatedTo(cat) %}
  {% if entries|length %}
    {% set entriesByCat = entriesByCat|merge({ (cat.title): entries}) %}
  {% endif %}
{% endfor %}

{% if cats|length %}
    {% for catTitle, catEntries in entriesByCat %}

{{ catTitle }}

        {% for entry in catEntries %}
          {# Entry content goes here... #}
          ...
        {% endfor %}
    {% endfor %}
{% endif %}

This works fine to output one field for the category (the category title). However, some of these categories have pictures associated with them, and I would like to be able to access those as well.

After the h2 tag I would like add a conditional to check if a category has an associated image in the "categoryImage" field for the category. If it does have an image I'd like to output the image.

I've been able to do this in other situations where I have more direct access to the category but I can't figure out how to access to the category image field within the loop structure that I have setup.

Any help would be greatly appreciated. I have to admit that I'm a bit beyond my depth with the twig template code above. :-)


texts: How can I filter/find on an ElementCriteriaModel?

texts:
I have already retrieved a set of all Entries from a channel and need to now find one in the template without hitting the DB again (this find is in a loop so I don't want to grab a single result from the DB for every iteration through the loop):

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

How can I then pluck out a specific entry by field match? I've tried this:

{% set entry = entries.find('myFieldHandle', mySearchVariable) %}

This doesn't seem to work for me though in that I don't get a match.


texts: Is there a way to create a new image transform 'onAfterInstall()' of a plugin?

texts:
As the title suggests, I would like my plugin to generate a new image transform automatically (with a few settings) when the plugin is installed.

The purpose is to avoid my plugin from crashing if a transform hasn't already been generated yet (or doesn't have the same handle names).

Thanks,

Mark


texts: Notes field only for certain product types

texts:
In my shop, I have two different kinds of products.type items and my products have variants.

For one of products type, I would like to show the note field in the cart.

My product types are:

products
options

For product type options, I don't want to show the note field.

How can I set this up?

Tried this without success.

{% for item in cart.lineItems %}
<form method="POST">
<input type="hidden" name="action" value="commerce/cart/updateLineItem">
<input type="hidden" name="lineItemId" value="{{ item.id }}">

{% if product.type('products') %}
<input class="form-control" type="text" placeholder="Productsort"  name="note" value="{{ item.note }}" required>
{% endif %}
<input class="form-control" type="submit" class="button" value="Bijwerken"/>
</form>
{% endfor %}


texts:
This should have been easy. But, I am dorking something up.

I am trying to point FeedMe to a local file.

In Finder, the file is located under /Users/shellyar/Desktop.  I also tried `file:////Users/shellyar/Desktop'.  Neither worked.


texts: Regex to remove trailing slash not working

texts:
I am trying to remove the http:// and trailing slash from a string, so my replace filter looks like this:

website|replace({ 'http://': '', '/\\/$/': '' })

The http:// part works, the trailing slash one doesn't. Why not?


texts: How I am supposed to send product data to stripe for web hooks?

texts: How I can add data to craft commerce stripe product while ordering, Actually I have used stripe webhooks so need meta data to identify the products


texts: Why when a task is marked as “Stalled” the following tasks can't automatically processed?

texts:
This is annoying to have to click on “Try again” to unlock the queued tasks. This could leads to dozen and dozen of stucked tasks that usually could be processed without any problem (like the Generating search keywords tasks).

I know there are recommandations about how to avoid stuck stacks, and we have setup a lot of these. But from time to time, we still face tasks marked as “Stalled” (and sometimes not) on several websites.

I know cron jobs using runTasksAutomatically setting or taskrunner plugin could also avoid this by calling the runPendingTasks at a more regular interval than connect to the Control Panel from time to time.

There's probably a good answer for that, but why when there's a task marked as “Stalled” in the Control Panel, this one is not ignored to automatically let the following tasks processing? And is there a way to automatically ignored these tasks marked as “Stalled”?


texts: How to get query or param from URL and then use in Links?

texts:
I'm trying to grab the query or param from an URL and then add it to an URL.

like products?price=15

How can I add the ?price=15 to a URL?

Like products/category?price=15?


texts: Getting image url from globals asset field

texts:
I can retrieve only the image title from the below code, I can't see why the image URL is showing as empty? its a global handle 'brand' and asset field 'logo':

{% set image = brand.logo.one %}


texts:
In short, I've got an extra background process running that syncs content for a given section to an external application as well whenever an entry in that section is saved and a certain toggle is set on that entry.

The background process itself runs smoothly, no problems at all there.

However I get a lot of questions from the end users saying they'd like to see some visual clue (besides the added job in the background processes queue) at the bottom of the sidebar. So I thought I'd show them a notice like you see when you save an entry (small blue bar at the top of the screen) indication when the external sync is triggered.

However I can't seem to find out how I can trigger such a message.

So I've got an Event::On block that does all the needed checks and triggers the jobs, and I'd like to expand that so it also shows a message.


texts:
I'm not sure what's wrong with this original markup:

Conditional One (doesn't work)

{% if entry.metaTitle is defined %}
  {{ entry.metaTitle }}
{% elseif title is defined %}
  {{ title }}
{% else %}
  {{ siteName }}
{% endif %}

This works but seems a bit much for some simple checks:

Conditional Two (does work)

{% if entry.metaTitle is defined %}
  {{ entry.metaTitle }}
{% endif %}
{% if (title is defined) and (entry.metaTitle is empty) %}
  {{ title }}
{% endif %}
{% if (title is empty) and (entry.metaTitle is empty) %}
  {{ siteName }}
{% endif %}

As you can see I'm checking first if metaTitle is set, then title then finally fallback to siteName. Entering data for the first two return results, but not sure why if metaTitle and title are empty why siteName doesn't return in the first conditional

#

Update based on Aaron's answer:

Tried this too:

{% if (entry.metaTitle is defined) and (entry.metaTitle is empty)  %}
  {{ entry.metaTitle }}
{% elseif title is defined %}
  {{ title }}
{% else %}
  {{ siteName }}
{% endif %}

#

Also tried this, Aaron was missing a ( in his answer :)

{% if (entry.metaTitle is defined) and (entry.metaTitle != '')  %}
  {{ entry.metaTitle }}
{% elseif title is defined %}
  {{ title }}
{% else %}
  {{ siteName }}
{% endif %}

But that doesn't work either with the same initial results.


texts: What files do you have to be aware of when migrating (i.e config files)?

texts: What files do you have to be aware of when migrating a craft application from one domain to another? Are the specific files one should be aware of?


texts:
'dev' => array(
        'siteUrl' => array(
            'de_ch' => 'http://blabla.dev/',
            'en' => 'http://blabla.dev/en/',
        ),
        'environmentVariables' => array(
            'basePath' => 'path',
            'baseUrl' => 'http://url-without-locale-segment.dev/',
        )
    ),

I set a baseUrl inside environmentVariables to be able to grab the url without a locale. But when I enter {{ baseUrl }} in the template it returns an error:

  Variable "baseUrl" does not exist

How do I have to write this?


texts:
I'm familiar with Heroku, but new to Craft CMS.
In order to get a site running, I followed this tutorial: https://medium.com/@aj1215/craft-cms-on-heroku-79b991665b0b#.8b561b1b4

But the site isn't functioning. My Heroku app just results in: Application Error An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details.

My development server runs fine. But I have no idea what I need to do to get the heroku app to function. I'm pulling my hair out.

I've tried everything I can think of, but can't get it to work. I'm not sure what I'm doing wrong.

These are messages toward the end of my Heroku logs:

2016–01–31T03:09:21.480751+00:00 app[web.1]: nginx: [emerg] “server” directive is not allowed here in /app/nginx_app.conf:1
2016–01–31T03:09:21.475721+00:00 app[web.1]: Starting nginx…
2016–01–31T03:09:21.481090+00:00 app[web.1]: Process exited unexpectedly: nginx
2016–01–31T03:09:21.481236+00:00 app[web.1]: Going down, terminating child processes…
2016–01–31T03:09:22.183035+00:00 heroku[web.1]: Process exited with status 1
2016–01–31T03:09:22.182791+00:00 heroku[web.1]: State changed from starting to crashed
2016–01–31T03:09:27.185620+00:00 heroku[router]: at=error code=H10 desc=”App crashed” method=GET path=”/” host=paradata.herokuapp.com request_id=1e502143–94ac-4aea-b34b-3087addd1d20 fwd=”172.11.56.78" dyno= connect= service= status=503 bytes=

enginx_app.conf file:

        location / {
            # try to serve file directly, fallback to rewrite
            try_files $uri @rewriteapp;
        }
        location @rewriteapp {
            # rewrite all to index.php
            rewrite ^(.*)$ /index.php?p=$1 last;
        }
        location ~ ^/(index)\.php(/|$) {
            client_max_body_size 20M;
            fastcgi_pass heroku-fcgi;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param HTTPS on;
        }

this is my craft/config/db.php file:

<?php

$url = parse_url(getenv("CLEARDB_DATABASE_URL"));

return array(

    'server' => $url["host"],

    'user' => $url["user"],

    'password' => $url["pass"],

    'database' => substr($url["path"],1),

    'tablePrefix' => 'craft',

);


texts: How to sort entries by their descendant count?

texts:
I want to sort (and paginate) entries from a structure section based on the number of descendants. This is the effective criteria I want to query:

craft.entries.section('myStructure').level(1).order('descendants desc')

Since getDescendants.count() is not a number stored against each entry in the database (AFAIK), how does one go about getting this result?


texts: How to define table attribute in the record file

texts:
Following code is working on Craft 2:
class My_TableRecord extends BaseRecord {
  public function getTableName() {
    return 'my_table';
  }

  protected function defineAttributes() {
    return [
      'title'         => AttributeType::String,
      'description'   => AttributeType::Mixed
    ];
  }
}

According to this documentation the defineAttributes() is not available in Craft 3. So how can I define table's attributes in Craft3 to complete following code:
class My_TableRecord extends ActiveRecord
{   public static function tableName()
    {
        return '{{%my_table}}';
    }

  //equivalent function of defineAttributes() of Craft3 will go here

}


texts:
I'm writing an LDAP authentication plugin, which, if the authentication matches, will log the user into a 'general' username/password, in order to view a protected page.  The 'general' username/password is part of a usergroup with restricted priveleges.

In my plugin, in the controller file, I have this:

craft()->userSession->login($username, $password);

with the $username and $password variables set just above that.  However, the login process does not appear to be happening, as my check in my template is not displaying the username:

{% if currentUser %}
Welcome, {{ currentUser.friendlyName }}!
{% endif %}

However, when I log on as that 'general' username/password, from the login page, and then refresh my template, it does show that the login for that profile has successfully occurred.

What may need to be done to effect a successful login, in the plugin?
Thanks!


texts: How to filter what is showed based on radio button checked

texts:
I am fairly new to Craft CMS coming from ruby on rails and angularjs.  I am running into an issue with attempting to display images on a home page based on whether or not the radio button titled "featured" ( a field) is selected.

I have searched around but was unable to find something addressing this, or at least in a way I understood to solve the problem.

I have been trying variations of...

{% if thumbnails.featured %}

...hoping it would only display what has "featured" selected but it either breaks and shows nothing or shows all the images.  Based on what I have found I think I have to "set" something but am unable to figure out exactly how that is set up.  This is exactly what I have right now and it is showing all images.

{% for thumbnails in craft.assets.thumbnails %}
    {% if thumbnails.featured %}

                    {{ thumbnails.caption }}

    {% endif %}
{% endfor %}

If anyone could suggest a solution or even point me in the right direction it would be greatly appreciated.


texts: How can I use a reference tag with a global set using the handle (not the ID)

texts:
https://craftcms.com/docs/reference-tags

In my tests, only using the ID with globalsets work, e.g {globalset:34:address}.

I'd like to do {globalset:misc:address}, with misc being the global set handle.


texts:
Currently I am using Sprout Email 2.4.7 to send newsletter mailings to mailchimp.

I am trying to prefill email.fromName, email.fromEmail, email.replyTo with default values so these don't need to be entered every time a new mailing is being set up in the Craft 2 cp section.

Setting this in the email template file does not work

{% set email.fromName = 'My Company' %}
{% set email.fromEmail = 'john@doe.com' %}
{% set email.replyTo = 'john@doe.com' %}

Any ideas how this could be done in a clean way?

thanks!


texts:
Problem
Hi all, I have been struggling with issuing the command ./craft gc. It shows the following
Delete all trashed items? (yes|no) [no]:yes
Running garbage collection ... PHP Fatal Error 'yii\base\ErrorException' with message 'Allowed memory size of 134217728 bytes exhausted (tried to allocate 16384 bytes)'

the allowed memory size equates to 128MB. I attempted to increase the limit but it still showed the 128M Allowed memory size.
What I've Done

I have set 'phpMaxMemoryLimit' => '1024M' in config/general.php
I have set memory_limit = 1024M in the php.ini
I executed the command php --ini |grep "Loaded Configuration File" which showed the correct path
I made a webroot/phpfile with <?php phpinfo(); which showed both the correct path, and correct memory_limit
I checked admin/utilities/php-info which showed the correct memory_limit

Information

PHP version   7.3.3
OS version    Darwin 19.2.0
Craft edition & version   Craft Pro 3.3.19
Mamp PRO version 5.3


texts: Generating thumbnails when using a memcache server for session storage frequently signs users out

texts:
I can't figure out why, but when I'm connected to a memcache server the thumbnail generation process in Assets hangs for long periods of time, the getElements process throws 403 errors, the generating thumbnails throw 401 errors and then the user is signed out.

This happens in 2 different AWS environments and on my local environment configured using MAMP. In total, three different memcache servers (production, stage, local) have this same thing occur.

The only thing I can find in the logs that seems like it could be related is an error message that reads:

Tried to restore session from a cookie, but the given login name does not match the given uid.
UID: LONG_UID_HASH_HERE and loginName: MY_EMAIL_ADDRESS.

I'm currently running Craft CMS 2.6.3019 (most current version of 2.x at the moment).

Edit: I also wanted to mention these assets all reside in an Amazon S3 bucket. Thought that might be relevant here, too.

Edit 2: I forced hasThumb() to always return false by commenting out these lines. The thumbnails don't generate 401 errors (because no thumbnails are being generated and the placeholder images are being used instead). And getElements runs much quicker, but it stills throws 403 errors after clicking around for some time.


texts: how to make required plane text fields or required firsrtName and lastName fields in users profile? I want to during the registration and profile changes were required. Maybe there is any plugin for this?


texts:
I'm building a small analytics plugin and as such, I don't need the dateUpdated and uid columns in my records, but I dind't find any way of disabling them.
Currently I have tried:

Not setting them in the install::safeUp: doesn't work as Craft adds the attributes to the list and PDO complains "column not found dateUpdated"
Making my record directly extend Yii2's active record and not craft's one

Nothing worked.
Is there any clean solution to this?
Thanks a lot for your help!


texts: Verbb Wishlist plugin see if item is in specific list

texts:
Looking at the docs, it says to check if an item is in wishlist using the below code:
{% set compare = craft.wishlist.item(entry.id) %}
{% if compare.inList %}
    Remove from Compare
{% else %}
    Compare
{% endif %}

I want to do the above but tell it what list to look in i.e craft.wishlist.type('compare').item(entry.id)
I cannot see how on earth to do this. I have multiple lists that an entry could be in, so need to specify.
Any help would be very gratefully received!!


texts:
I am building a timeline which I want to paginate. For this to be efficient, the timeline entries should be in a linear order.

The challenge is that entries before present (BP) have to be in descending order, i.e. going from 10,000 years BP to 1,000 BP, then in ascending order into the present, i.e. 1400 > 1700 > 2000 > 2018.

After discussing this challenge, a colleague recommended adding a minus to the BP entries' title. So now I auto-generate the titles to become

timeline-YYYY (before present)
timeline+YYYY (present)

The target sort order should then be:

timeline-10000
timeline-1000
timeline+1400
timeline+1700
timeline+2000

Unfortunately when I use SuperSort with natural sort order I get

timeline+1400
timeline+1700
timeline+2000
timeline-1000
timeline-10000

I assume this is because SuperSort sorts the titles as strings and follows the ASCII character sort order.

How can I get my target sort order?


texts: Optimizing working Code — reduce the loop

texts:
I have the current situation and already a solution for it. But I'm not feeling very well as it seem to have an unecessary loop?
Situation
Structure: itemCategories
Category A
Subcategory B
Subcategory C
Category D
Subcategory E
Channel: items
Item A
Item B
Item C
The entries in 'items' having a relation field to itemCategories. So I can select multiple categories within this field.
I render them as a navigation structure and it's related content.
Now I have the problem that I often want to output give items grouped in it's selected categories.
An item can be listed in multiple categories. Like:
CategoryA
Item B
Item C
Category D
Item A
Item B
This code snippet is based on outputting a search result:
  {# Get the search parameter from the call #}
  {% set searchQuery = craft.app.request.getParam('q') %}

  {# Fetch entries that match the search query #}
  {% set results = craft.entries()
      .search(searchQuery)
      .section('items')
      .all() %}

  {# Array to hold the categories from the found items #}
  {% set categories = [] %}

  {# I'm looping threw the search result and than loop over the category field in the item #}
  {# Than writing it into the created array #}

  {% for result in results %}
    {% for cat in result.category %}
        {% set categories = categories|merge([cat.id]) %}
    {% endfor %}
  {% endfor %}

  {# As it's possible the same category more than once I apply a unique filter #}
  {% set categories = categories|unique %}

  {# Now I loop over the unique list of categories #}
  {% for category_id in categories %}

      {% set category = craft.entries.section('categories').id(category_id).one %}

{{category}}

      {# Inside the loop I go threw the search results again and output them if the current category is in the item's category field #}
      {% for result in results %}

        {% if category.id in result.category.ids() %}
            {{result.title}}

        {% endif %}

      {% endfor %}

  {% endfor %}

As I said I feel like it's a little bit overused. Perhaps someone has a smarter solution for it.
Regards
Simon


texts: Is there a way to re-order states in Craft Commerce?

texts:
I'm setting up a Craft Commerce site and for some of the countries the user must specify a State. However, the order of states appears to be alphabetical.

The problem is that the site's traffic comes mainly from 2-3 states so it would be much easier for the vast majority of users to find those states if they appear at the top.

Craft Commerce seems to allow custom ordering for countries. Is there a way to do the same for States?


texts: Why is $DEFAULT_SITE_URL appearing in entries URL?

texts:
I have an entry loop on my homepage that uses {{ entry.url }} that links to the full entry. When I click on the entry, the url looks like this
mydomain.com/$DEFAULT_SITE_URL/the-entrys-slug
Even though my section settings just has the Entry URI Format set to {slug}
Here's my entry loop if you need it
{% set aBetterPost = craft.entries.section('aBetterPost').limit('6').all() %}
{% for entry in aBetterPost %}

            Entry Stuff...

{% endfor %}

How can I get rid of the $DEFAULT_SITE_URL ?


texts:
I am using Craft 3 with the default Craft 3 user registration form. Whenever I register I get an empty email. If I go to the cms and manually click on 'send activation email' I get a correct activation email like it should be. What could be causing this?

There are no errors in the error logs, the test mail is working just fine, all the other emails like the forgot password email is also working fine.


texts: htaccess www to non-www redirect (and config.php)

texts:
I need to set up a redirect from the www version of my site to the non-www version for SEO. I found a solution that would work here if it weren't for the fact that it breaks the index.php redirect that comes with craft.

Can anyone tell me how to implement a generic redirect from http://www.site.co.uk to http://site.co.uk and still keep the index.php craft redirect working?

Additionally, does this affect the config.php file, or does that get loaded AFTER the redirect?

Thanks!


texts: How to set Commerce 2 confirmation email in .env file?

texts:
We're just in the process of upgrading from Craft 2 with Commerce 1 to Craft 3 and Commerce 2. One of the issues we had before was that the client was getting confirmation emails for test orders.

Is it possible to set the confirmation email destination in the .env file so our team can set themselves as the target emails for their own local testing?

Thanks!


texts: Setting shipping costs on a per-product basis

texts:
Folks:

I've got a client with very specific shipping requirements. Essentially, he wants to assign specific shipping costs for every single zone for every single product. Like this:

Product A shipping to Canada = $25
Product A shipping to Continental US = $40
Product A shipping to Alaska and Hawaii = $60
Product A shipping to Europe Zone 1 = $100
Product A shipping to Europe Zone 2 = $125
Product A shipping to Europe Zone 3 = $150
Product A shipping to Asia Zone 1 = $200
Product A shipping to Asia Zone 2 = $220
Product A shipping to Asia Zone 3 = $230

Now multiply this by 25 products. And he wants to be able to change the shipping costs whenever he needs to so it will be essential that he can adjust it from the backend rather than through code.

Any thoughts on this? My initial idea was to use the Default Item Weight Rate option and have each product assigned a weight. Of course, the weight wouldn't reflect the actual weight of the product, it would just be a way of easily adjusting the shipping rate. The problem I see is that adjusting the weight would adjust the shipping cost across all zones rather than just the zone he wants to change.

Is my only option then to create a shipping category for every product and using Category Rate Overrides?


texts:
Is there a way to output the first image of a rich text field?

At the moment the template code is as simple as:

{{ entry.body }}

The purpose is so that I can use the image in the meta section of the template. If there is no easy solution I could change it to be a Matrix field.


texts: How to filter entries with null value in date field?

texts:
I have date field in entry that is empty therefore has null value.
I'd like to filter entries that have date field value equal to null.
How would I set that parameter on element criteria object? I don't want to achieve it by looping yet because I'm merging entries from another section.

Setting it to null returns entries with or without value.
{% set myEntries = craft.entries.section("mySection").date(null) %}

Setting it to "" returns entries with or without value.
{% set myEntries = craft.entries.section("mySection").date("") %}


texts:
I'm not sure if this is a bug or I'm doing this wrong. I have an asset volume called "Blog Images" and there is a custom required field called Image alt text. If I add images in assets section I'm required to put something in for the alt text, that's good because that what I intended. But I'm using a matrix block that has an asset field that looks to this volume and I am able to upload and image to this volume and not add anything in this field. What am I doing wrong?

Also I should mention this is using Craft 3.


texts: How can I set dynamic absolute Asset URLs?

texts:
I'm working on my first subfolder-based Craft site, so I'm relying on Asset URLs based on the {{ siteUrl }} variable. I cannot, however, manage to get them working. Any tags I add to the URL field in the control panel get printed literally (not parsed) in the template output.

My config.php looks like this:

return array(

    '*' => array(
    ),

    'foo.craft.dev' => array(
        'siteUrl' => 'http://foo.craft.dev/',
        'devMode' => true
    ),

    'foo.bar.com' => array(
        'siteUrl' => 'http://foo.bar.com/',
        'devMode' => true
    ),

    'example.com' => array(
        'siteUrl' => 'http://example.com/foo',
        'devMode' => false
    ),

);

My Logos Asset settings look like this:

And a relevant chunk of template looks like this:

    {% for logo in logos.logoImages %}
        {{ logo.companyName }}
    {% endfor %}

The background-image URL above renders out as {siteUrl}assets/logos/logo.gif, which isn't parsed as I would expect.

What have I done wrong?


texts:
Can anyone help identify why one on my entries is not being picked up in my search query?

The search terms are 'hampshire 10k' and the craft_searchindex table for this entry looks like this:

The search string param is added as follows (along with a handful of other params) for any search

{ search: '*hampshire* *10k*' }

Unsure if it's down to bug or a templating issue? The keyword search forms part of quite complex entry search.


texts: Cannot select subcategory field in entity

texts:
I have a Structure section fruit with a single entry type fruit.

I also have a Category fruitType with 2 levels:

Citrus

Orange
Lemon
Lime

Melons

Watermelon
Honeydew

The entry type fruit has a Category field for fruitType.

If I select a level 2 category for the fruitType field, say Orange:

Craft CMS dismisses the category selection pop-up and the parent category is shown instead, in this case Citrus.

From the browser's network inspector, I noticed that a POST request to /admin/actions/elements/getCategoriesInputHtml with the following form data:

categoryIds[]:893
locale:en_us
id:fields-fruitCategory
name:fields[fruitCategory]
limit:1
selectionLabel:Category

However, the response from the server is:

{"html":"<input type=\"hidden\" name=\"fields[fruitCategory]\" value=\"\">\n\n
\n\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t\t\t

<input type=\"hidden\" name=\"fields[fruitCategory][]\" value=\"887\"><\/a>
<\/span>Citrus<\/span><\/div><\/div><\/div>\n\n\t\t\t\t\t\t\t<\/li>\n\t\t\t<\/ul>\n\n\t
Category<\/div>\n<\/div>\n\n"}

Based on the response and what's rendered in the interface, Citrus is shown and not Orange, despite Orange being selected.


texts: Template cache table growing very big, best way to keep it in line?

texts:
So we have built a rather large site for a client, which has multiple regions, locales, user privileges, etc.
Some time ago the default cache of Craft couldn't cope anymore with keeping track. The cache clearing tasks always stalled so cache wouldn't be deleted anymore.

This triggered us to change the way we cache our pages. Unfortunately, the template cache table in the database is getting to its limits as we haven't found a good way to clear the old caches.

How it works:

We set 'cacheElementQueries' => false,

Every page gets its own cache (unique cachekey) which consists of:

Is the user logged in yes or no?
Which region is the user in? (one of 3 possibilities)
Which user type does the user have? (any combination of 3 types possible)
The page url
The last updated date of the entry (not always used)

We cache everything globally and cache some parts of pages separately, for example: the sidebar of a product page remains the same but the content changes.

We use a combination of coldcache and cacheflag plugins.

Issue:

As we create a lot of caches and a lot of them with a certain date in the key, the database table gets cluttered and grows to big in size (max limit for our DB is 1GB and the cache table is reaching 500MB).

The question

How can we delete old caches from the DB table?

The only two options I can think of now are:

Set cache duration to a certain time interval (but than all caches are deleted which will make the site slow every interval).
Create a plugin that runs every month with a CRON job and checks all of the cache keys and deletes everyone but the latest.

Any other ideas out there?


texts:
I'm using a route to use a different template, but whatever I try the page remains unchanged, my structure is set as:

entry url format: {slug}

entry template: _pages/_entry

I want an entry's slug to use a different template - would this possibly be affecting the route being followed?

I want the entry 'home' to use the 'index' template (and not the '_home' template which exists at _pages/_home)

I've cleared my cache and updated indexes


texts: How to reference a folder inside of a volume, Craft 3

texts: How do I reference a specific folder (by name) inside of a specific volume.  I cannot use the folder ID, I must use the folder name because the name of the folder is a variable related to specific entries.


texts:
Getting the following error on a site I'm developing:

  Instances of craft\awss3\S3Client cannot be serialized

Unsure if this is an issue with the Amazon S3 plugin or at my bucket's end. Any ideas much appreciated.


texts:
Live Preview isn't working for any kind of entry. Dev or production. I get the following error on chrome's console.

jquery-2.1.1.min.js?d=1409764106:4
POST http://undiario.dev/ 500 (Internal Server Error)

jquery-2.1.1.min.js?d=1409764106:4
k.cors.a.crossDomain.send

jquery-2.1.1.min.js?d=1409764106:4
n.extend.ajax

jquery-2.1.1.min.js?d=1409764106:4
n.(anonymous function)

craft.js:10520
Craft.LivePreview.Garnish.Base.extend.updateIframe

jquery-2.1.1.min.js?d=1409764106:2
n.isFunction.f

Anybody knows why this is happening?


texts: How to get data from a Global Set in a plugin?

texts:
I have a Global Set called "Settings" (handle = 'settings'); Within that I have a text field called "Address" (handle = 'address').

I have a function in my Plugin and I'd like to get the Address data.

In the front-end I would write this:

{{ settings.address }}

How can I get the same information in my plugin with PHP?

I've got as far as this:

$address = craft()->elements->getCriteria(ElementType::GlobalSet);

When I var_dump this array, I can see the address string. But I can't figure out how to filter down to the address correctly.

Thanks


texts: Less complicated local development w/Craft 3, is it possible?

texts:
I do not really care for WordPress, but one thing that it has going for is a dead simple local development environment. In fact, it free software called "Local". It took all of five minutes to get running.

Meanwhile, it took several hours to do a basic set up of Vagrant on Windows, configure Craft to run locally, and then there was various back and forth over obscure server issues until I could finally get it to work. And when it did, the control panel ran rather slowly. I gave up and went back to mapping an FTP connection as a network drive, and just working on files locally, saving them, and then hitting the live site.

I recognize these are different programs, but is there any way to set up Craft for local development that doesn't require an advanced degree in Apache/Vagrant/Docker/whatever the flavor of the month is?

I don't really care if I'm using WAMP, Docker, or whatever, but I would like to find something that is straightforward, with repeatable results, so the next time I have to spin up an install, I don't have to remember 50 steps to do so.

And yes, I am sticking to Windows 10.

Thanks in advance.


texts: Group by weekday and ongoing in Solspace Calendar

texts:
I'm using the Craft group filter to group events by day:

{% set week = craft.calendar.events({
  dateRangeStart: 'today',
  dateRangeEnd: '3 days'
}) %}

{% set weekByDay = week|group('startDate|date("l")') %}

{% for day, eventsInDay in weekByDay %}

{{ day }}

  {% for event in eventsInDay %}

{{ event.title }}

  {% endfor %}

{% endfor %}

How would I go about including events that are happening - but not necessarily starting - during each day?


texts: Using SSL for entire website on Arcustech server

texts:
I want to use SSL (https) for my entire website which is hosted on Arcustech.  I came across two instructions, one on Craft's site which discusses forcing SSL on the CP and the other is from Arcustech's site which discusses forcing SSL on entire site.  I'm not sure if I can just use the Arcustech's version or if I need a combo because I want the CP to be SSL too.

Here's the code for the two versions:

Craft Forcing SSL on CP (direct link)

<IfModule mod_rewrite.c>
RewriteEngine On

# Force SSL for CP requests
RewriteCond %{HTTP_HOST} example\.com [NC]
RewriteCond %{REQUEST_URI} ^/admin/ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L]

Arcustech Forcing SSL for entire site

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !^https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Thank you!

Lori


texts: Redirect to template from controller and pass data

texts:
I am building a custom login process which follow these steps:

Request user email (submits to custom controller)
Check if user has an account
If they have an account, show a form requesting their password. Or if they don't have an account then send them to the registration form.

The forms exist as front end templates.

I can accomplish all these steps but when the user is redirected I need to make the email address that they entered available to the template.

My custom controller calls a service to check if the user exists which is all fine.
And I can redirect the user to the appropriate URL. But I can't figure out how to retain the email address they entered.

Currently I've just done it by appending the email as a query string but this is undesirable for a couple of reasons.

The controller currently looks like this although I feel this is totally the wrong way to be doing things.

public function actionEmailCheck() {
        $this->requirePostRequest();

        $email = Craft::$app->request->post('loginName');

        $result = MyModule::$instance->order->checkEmail($email);

        if($result) {
            $redirect = '/login/password?email='.$email;
        } else {
            $redirect = '/register?email='.$email;
        }

        $this->redirect($redirect);
    }

I feel like I should be able to set some template variables and load the appropriate template but that doesn't seem to work.

I also tried this

if($result) {
            $this->renderTemplate('/login/password', array('email'=>$email));
        } else {
            $this->renderTemplate('/register', array('email'=>$email));
        }

But while the template was displayed, I couldn't access the value for 'email'.

So how should I approach this?


texts: Where should the .all() be placed in Craft 3

texts:
I'm confused, I have ended up with 2 similar queries in a template after converting them from Craft 2.

{% set events = craft.entries()
    .section('events')
    .eventDate('>' ~ now|date('Y-m-d H:i:s'))
    .limit(3)
    .orderby('eventDate')
    .all()
%}
{% for entry in events %}
...
{% endfor %}

and

{% set entries = craft.entries()
    .section('news')
    .orderBy('postDate desc')
    .limit('4')
    .with(['imageGallery'])
%}
{% for entry in entries.all() %}
...
{% endfor %}

Both work without any errors reported but which one is better or correct?


texts:
I have been importing data just fine using Feed Me Feed URLs that point to .json files placed above web root. (It's a great plugin.)
But for some kinds of import I now want a Feed URL to be an https addressable URL that is nonetheless not publicly viewable to anyone who knows the URL.
So I thought I'd be able to do the following:

Allow my client to compile JSON formatted data via a tool I've made
Paste that data into a Globals field that generates a template generated URL with a JSON mime type
Have that template only render its content if the viewer is logged in
Point Feed Me at that URL, on the assumption that it too is 'logged in' to its own CMS

But it turns out that Feed Me doesn't play with step 3, even though it's a relative URL specified as:
@web/path/to/json

I guess I can have the template be sensitive to an obscure URL parameter instead of logged in state.
Any other ideas?

Update 1
FWIW the param approach works fine, so that:
@web/path/to/json

…renders nothing but…
@web/path/to/json?myWeirdParamName=obscureValue

…renders the data.
So I point Feed Me at the latter.

Update 2
I just found the docs section on configuring requestOptions, which suggests to me that there is a way to have Feed Me be governed by authentication, but I'm too dumb to make sense of what it might be trying to tell me.
Can someone help me join the dots?


texts: Updating an entry record programatically?

texts:
I need to update the value of an entry attribute programatically. I've tried a couple things, but the record is not updated. The code I am using is below.

      $criteria = craft()->elements->getCriteria(ElementType::Entry);
      $criteria->section = 'affiliates';
      $criteria->limit = null;
      $criteria -> search ='email:'.$email;
      $criteria = $criteria -> first();

      $criteria->getContent()->setAttribute("optOut", "true");

      craft()->entries->saveEntry($criteria);
      return $criteria->title;


texts:
When logging in indicates the 'account has not been activated', how do I create a link for resending the activation email?

Update
I want users to be able to enter their email address in an input field and have that resend their activation link. Not in the backend, just frontend only!


texts:
Craft is a miracle for us but we've hit a snag.

We have about 100 products with around 10 images each.

We've scraped the images from the old site and put them into the appropriately named folders in assets.

Each time we add more, we have to run the asset reindexer which will only reindex the entire section. So even if we add a single folder of images, the entire lot are indexed again. If you've ever used the asset indexer you'll know that for whatever reason it is dog slow.

Why is this?
Could the immediate folder not be quickly indexed when the asset viewer is opened in the back end or at least provide an option to reindex that specific entrys assets?

Future projects may have 10,000 assets+ so it is a concern.

I'm open to better workflow suggestions as well.

Thanks :)


texts: Organizing repeating content on a single page

texts:
I have a page with a slider on it, which includes three rotating slides. In Craft, I am currently setting up each slide as an entry under a "Home Page Content" channel, and then creating an entry field for them on the home page single.

Is that the simplest/correct way to do it? Is there an alternate way that allows me to enter the number of slides and the information for each directly on the home page single?


texts:
Our Shop-Customers should upload an image per Item they add to the basket. I managed to upload the image and insert it to an asset folder.

How can i assign the image to the lineItem (maybe as an option)?

This didn't work, as options is not writable:

craft()->on('commerce_lineItems.onBeforeSaveLineItem', function($event){
    $imageId = craft()->ultraschall->uploadCustomerImage(); // add image to asset folder
    if(isset($imageId) && is_numeric($imageId)){
        $lineItem = $event->params['lineItem'];
        $lineItem->options['imageId'] = $imageId;
    }
});


texts:
I am building a site for a travel agency. Each agent needs to have his/her own public profile page. I want each agent's profile page to be accessed at agencyname.com/agentname, with agentname being the agent's username. This would load an agent profile template populated with the given agent's profile data.

I still need other non-agent segment-1 pages to continue working also, like agencyname.com/cruises or agencyname.com/group-travel. These would be 'normal' template pages.

Is there any way to make this work dynamically? Creating a dynamic route with only a token in Segment 1 breaks access to other regular pages. I don't want to have to create a hard route every time we add an agent, and we don't want to add another segment like agencyname.com/agent/agentname. We want the URL each agent puts on their business card to be as clean and easy to remember as possible.

I'm thinking something along the lines of this logic:

If Segment 1 matches a username
   Display the profile template for that user
Else
   Continue routing per the normal routing checks

I don't have the knowledge to build a plugin, or the budget for someone else to. I'm seeking solutions that could be implemented without a plugin (unless there's already a plugin available).

Any constructive thoughts are appreciated.


texts: CSRF error with Contact Form and a new domain name

texts:
We are using Pixel & Tonic's Contact Form plugin. It was working fine. We just assigned a new domain name to the Craft subsite whose template uses the Contact Form. The form has stopped working. We believe this is due to CSRF token/cookie since we get a “Bad Request. Unable to verify your data submission” error when we try to submit the Contact Form.
Any ideas how we might fix this? I can’t find many resources on Craft and CSRF other than clearing browser cache/cookies (which did not solve the problem) and making sure to include the CSRF input field, which we have. I try to compare CSRF token value and cookies but they don’t look similar at all.
[We tested in dev by disabling the general.php ‘enableCSRFProtection’ flag. When we did this, the Contact Form submitted and sent us the email as expected. Strangely, the flash message did not show. Since we don’t want to set that flag to false in prod, not sure where to go from here.]


texts: Issues with picture and image transforms

texts:
I'm having some issues with  when applying image transforms. Hopefully it's something obvious I'm over looking. The code is as follows:

<picture>
    <source media="(min-width: 401px)" srcset="{{ imageUrl.getUrl('homeBanner') }}">
    <source media="(max-width: 400px)" srcset="{{ imageUrl.getUrl('iphone400x710') }}">
    <source srcset="{{ imageUrl.getUrl('iphone400x710') }}">
    <img src="{{ imageUrl.getUrl('iphone400x710') }}" alt="Image Desc">
</picture>

Images uploaded are all 2000px x 1330px and the transform should crop from center to the specified size in the handle.

My problem is it works on my local server but once uploaded to my (shared) dev server I am getting php out of memory errors on this script

craft/app/vendor/imagine/imagine/lib/Imagine/Gd/Image.php on line 617

Am I doing something incorrectly that is causing the script to run for too long?

Cheers


texts: Restrict entry editing to category / topic

texts:
How can I implement security which allows members to only publish an entry in an assigned category / topic?

Example:

The site is a business directory.
Business listings are published in cities: New York, California.
Content managers are assigned to either New York or California.
Content managers can only publish in the city they are assigned to.
Content managers can only see entries in the city they are assigned to.

I first thought this could be done with a custom field that only shows the cities a content manager is assigned to. That shouldn't be so hard.

However I'd need to also limit the entry indexes in the Control Panel.

Edit: Just found the onBeforeBuildElementsQuery event: https://craftcms.com/docs/plugins/events-reference#elements-onBeforeBuildElementsQuery

    craft()->on('elements.onBeforeBuildElementsQuery', function(Event $event) {
       // $event->params['criteria']['tennant'] = 'new-york';
    });

Any ideas?


texts: Eager loading for fields attached to commerce variants when listing products

texts:
Let's say that I perform element query for commerce products and want to display an image that is attached to the default variant of each product.
How can I eager load these images, if they are not attached to products, but variants within these products?


texts: Converting images to WebP - Overcoming Timeout Errors?

texts:
I have over 1500 images... I'm trying to improve performance on our site and want to create WebP versions of our images.

WebP is installed - new images we upload get converted. When I resave the image variant it begins the process of conversion and optimisation of previous images but then we bump into timeout errors.

What is the best way to do this process in an efficient way? I'd be interested to know how we overcome the timeout error.

Note:

images are in a Digital Ocean S3 bucket.
we are using the incredible imageOptimize plugin
we host the site on Laravel Forge


texts: Unknown error when trying to upgrade license

texts:
I just pushed a site live, and now when I log in to the control panel and get the message to upgrade my license, when I click "upgrade your license", I get a blank modal and a message that "An Unknown Error Occurred".

Everything has been running fine up to this point on the same server, using its ip address, rather than the url.

I'm getting the following errors in my log file:

015/09/21 22:30:32 [error] [exception.Craft\HttpException.403] exception 'Craft\HttpException' in .../craft/app/services/UserSessionService.php:442
Stack trace:
#0 .../craft/app/controllers/AppController.php(118): Craft\UserSessionService->requireAdmin()
#1 .../craft/app/framework/web/actions/CInlineAction.php(49): Craft\AppController->actionGetUpgradeModal()
#2 .../craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#3 .../craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#4 .../craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#5 .../craft/app/framework/web/CWebApplication.php(282): CController->run('getUpgradeModal')
#6 .../craft/app/etc/web/WebApp.php(784): CWebApplication->runController('app/getUpgradeM...')
#7 .../craft/app/etc/web/WebApp.php(276): Craft\WebApp->_processActionRequest()
#8 .../craft/app/framework/base/CApplication.php(184): Craft\WebApp->processRequest()
#9 .../craft/app/index.php(62): CApplication->run()
#10 .../index.php(19): require_once('/storage/av0308...')
#11 {main}
REQUEST_URI=/index.php/admin/actions/app/getUpgradeModal
HTTP_REFERER=http://gtcarts.com/admin/dashboard
---
2015/09/21 22:30:32 [trace] [system.CModule] Loading "errorHandler" application component
in .../craft/app/etc/web/WebApp.php (584)
2015/09/21 22:30:32 [error] [application] in .../craft/app/etc/errors/ErrorHandler.php (95)

Is there a way to troubleshoot this?


texts:
Just installed the cms last night. I am looking for a step-by-step instruction on how to create a gallery and display it.

So far I have created the:
- channel called: Gallery
- section called: Gallery
- entry type: Gallery
- the assets field named: gallery
- added 4 images
- created a new entry called: Gallery (only the Title is visible so far) and this is where I got stuck.

Any help would be greatly appreciated


texts: Switch Matrix block on handle rather than type

texts:
I've got a matrix with a Block type called textBlocks which Craft seems to be having trouble seeing.

The error is:

Craft\MatrixBlockModel and its behaviors do not have a method or closure named "textBlocks".

My template code is:

{% for block in entry.clientsContent %}

 {% switch block.type %}

{% case "text" %}

{{ block.blockTitle }}

{{ block.blockContent }}

{% case "images" %}

  {% for asset in block.images %}

  {% endfor %}

 {% case "textBlocks" %}

  {% for row in block.textBlocks %}

{{ row.title }}

{{ row.content }}

  {% endfor %}

{% endswitch %}

{% endfor %}

Am i getting this right here? When you do switch block.type is block.type the Block Type name?

See pic for my Matrix setup:


texts: Getting entries related to current entries categories

texts:
Trying to get 10 entries related to the current entry categories excluding a category called featured. I don't have the category name(s) in the url.

This currently what I tried but this does not work, confused about how to do this.

{# Fetch all of the categories related to this entry excluding the featured category#}
{% set categories = craft.categories.relatedTo(entry) %}

{# Output them #}
{% set thecategory = [] %}

{% for category in categories %}
    {% set thecategory = craft.categories.group('resource').slug(category.slug) %}
{% endfor %}

{# Set featured category name to exclude #}
{% set category = craft.categories.group('resource').title('featured') %}
{# Set featured ID's we dont want to show... #}
{% set featuredArticleIds = craft.entries.section('articles').relatedTo(category).ids() %}
{% set featuredArticleIdsString = featuredArticleIds | join(', not ') %}

{% set entries = craft.entries.section(articles).relatedTo('and', thecategory|join(',')).id('and, not '~featuredArticleIdsString).limit(10) %}


texts: Using Twig's replace filter with getURL()

texts:
I have a template that displays in both http and https environments. When pulling my images for the https environment I need to be able to change the URL to https:// from http://. I tried

{{ gist.gistImage.first().getUrl('gistUnit')|replace({'http': https}) }}

based on the documentation here twig.sensiolabs.org/doc/filters/replace.html

Not working. Is this because getURL() gets processed after the filter?


texts:
I have a list of people with skills defined by a category group.

I have a category field within the 'people' Section so when a new person (entry) is created, the category field allows the admin to assign appropriate skills to that new profile.

I have a series of category entries for the 'skills' available.

When a user visits an "Our Skills" entry page, I need to display the title (name) of the people who have had that particular skill assigned to their profile via the category field.

I think this is reverse relations but I can't get my head around it?

Would appreciate some help.

Many thanks

Martin


texts:
I am getting a strange whitespace character when using a different language.

All languages use the same templates/database/plugins etc.
But when I go to any other language except the default I get a whitespace character before the

I have no idea what this is coming form. Its there when I disable all plugins and use a blank template.


texts:
I loaded redactor. When I try to run the install command
./craft install/plugin redactor
I get an error back that says craft is a directory.

It appears the plugin may already be installed.
But I do not know the next step to access it.
I thought I might have a Redactor field type available to select but I do not.

Also the plugin store does not load on my local install.
It says plugin store not available at this time.

Under settings > Plugins nothing shows.


texts:
Can entries of type structure have multiple parents?

https://docs.craftcms.com/v3/sections-and-entries.html#sections says that they can be hierarchical, but the UX doesn't seem to let me have more than one parent for any given child structure.

Not sure if that is a hard limit or just something misconfigured on my end.

I searched around a bit and saw this answer: Structure entry connected to multiple parent entries which implies that the way to do this is to use relations, not structures, but wanted to confirm.


texts: How do I create database tables for a craft cms plugin on install?

texts:
I am absolutely new to craft plugin development and could not find any documentation on creating database tables specific to a new plugin. How are new tables created when a plugin is installed?

I am browsing through the source code for the CocktailRecipes plugin: https://github.com/adrianmacneil/cocktailrecipes/ and I cannot find how the craft_cocktailrecipes_ingredients table gets created when I install it.

Is it merely a matter of defining a record class like CocktailRecipes_IngredientRecord and then overriding the getTableName and defineAttributes methods?

Is that how craft cms builds the tables?


texts:
I'd like to manage access to assets with public URLs.
Is there a way to set permissions for anonymous users?


texts: How to create CRUD operation in Craft CMS?

texts: In front-end can simply create CRUD operation. Pls help


texts:
I created a new section (single) on my  local environment.

Then I pushed it to LIVE. There it is not showing up in the entries CP.

But it is showing up in the settings.

So I guess the project.yaml hasn't been applied correctely or something.

If I excecute ./craft project-config/rebuild on LIVE I get the error:

  Exception 'yii\base\InvalidConfigException' with message 'The
  directory does not exist:
  /path/assets'

  in
  /path/vendor/yiisoft/yii2/web/AssetManager.php:213

But this has nothing to do with assets

Also. If I go to said section in the settings and try to save it there is the following error:

  2019-07-15 14:06:43
  [-][1][aaa64a91c1fffdd268c2d774dc31daa4][error][yii\base\Exception]
  yii\base\Exception: Couldn’t save single entry due to validation
  errors on the slug and/or URI in
  /path/vendor/craftcms/cms/src/services/Sections.php:1561

What now?


texts:
I have a section called Services. I have another section called Case Studies.

For each Case Study I want to show which service is being used so I add an entry field and choose the right service. On my case study I can see that the service is showing as it should.

On the Service page I want to see which case studies are being associated with the Service.


texts:
I've got the ol’ DeleteStaleTemplateCaches issue breaking the Craft task manager/process. I've tried switching the offending task over to error from running but is still stuck.

Any thoughts on debugging/resolving? Can I just clear out the tasks table?


texts: How do you download multiple plugins vis Command Line?

texts:
Coming from Drupal, we often use drush to download modules (plugins) and install them. For example this is what we might do using drush:
drush dl bootstrap mailchimp stripe-php
This would download the modules (plugins), then we'd have to install/enable them.
On CraftCMS the ./craft utility is great for installing, but not downloading. I know you can use composer require vendor/plugin-name — but that requires me to know the vendor name as well. This came up when I was applying a project.yaml file to a fresh CraftCMS install and it notified me that a bunch of plugins were not installed — but only gave me the plugin-name for each — meaning I would have to look up the vendor -or- search for each in the plugin store and install.
Is something like the drush dl command available with the ./craft cli utility at this time?


texts:
Redactor I had a feature that allowed editing of image alignment (via the image popup) and size (by dragging the square bounding box), is it possible to enable this functionality in Redactor II?

Is this something that can be done with formattingAdd?


texts:
I'm using a gallery where when an image is clicked it opens a larger version in a modal.

Initially the larger 'galleryLarge' images wouldn't load because the transform hadn't been created. After some digging around on here I found that adding 'generateTransformsBeforePageLoad' => true, to craft/config/general.php would create the transforms (all of them) before the page loads.  This worked a treat and now my modal works as expected!

Problem:  The page now takes forever to load.  I stopped this issue by removing the line from general.php but now of course, any new images added by the client won't get transformed.

Any ideas around this issue would be great.

Many thanks

Martin


texts: How Can I load Inline CSS in the Redactor Editor?

texts: In Redactor I put some content but I don’t know why Inline CSS is not load? Is there any way to solve this problem?


texts: Export static html including images, CSS, JS etc

texts:
For a client I need to export websites as static html (/w images, CSS, JS etc.), which I have created in Craft.

Unfortunately, I cannot find a plugin for this.

Can someone give me a hint, how do I start with this?


texts: SPA style entry rendering, SEO implications

texts:
I'm working on implementing a layout that involves a listing page, that when an entry is clicked, the content slides in from the side and fills the screen.

Doing this in the style of an SPA via ajax or Vue.js is fairly straightforward, but I'm unclear on how to implement in Craft while maintaining SEO "crawlability" via something like server-side pre-rendering or such.

I'm not even sure where to start, any direction would be much appreciated!


texts: How to add a custom tab in the user editing page

texts:
I try to add a custom tab to user account editing page, but there is only one default tab called 'profile' to use and we are not allowed to add another tab there. I am just wondering if this is the case and if Craft CMS will allow us to add a custom tab there in future versions.

Thanks.
Spencer


texts: Events calendar for Craft - which one should I use?

texts:
The current state of events/calendars in Craft is:

Calendars - https://topshelfcraft.com/calendars/introduction
Venti - http://tippingmedia.com/venti
Solspace Calendar - https://solspace.com/craft/calendar

Whats the benefits of each? Anything to note?


texts: How does the negative (not) conditional work in Twig?

texts:
If I write:

{% if entry.section not 'Homepage' %}Blabla {% endif %}

this results in the error:

  Unexpected token "operator" of value "not" ("end of statement block"
  expected)

But if I write:

{% if entry.section != 'Homepage' %}Blabla {% endif %}

It works.

In the twig docs there is no mentioning of != as an operator but it seems to be working just fine. Is != a craft specific operator?

So whats the difference between not and != ?


texts:
I'm getting SSL errors when developing using .dev as a domain name. I believe it's because browsers are now automatically forwarding these to HTTPS://.

Any ideas how to get around this with Craft? I can change the extension but Craft requires .dev for local development I believe.