texts: Why are there now blank entry folders in my image assets folder?

texts:
There are folders in my images asset folder craft/public_html/images/ named for individual entries (posts).  But, the folders are empty.  This is something new.  Only recent posts are represented.  The actual images for these and all posts are still there, the settings have not changed and everything seems okay. And, it appears I can delete one of these empty folders without negatively impacting the actual post.

Is this a quirk or associated with a recent update and therefore has some purpose?  Should I delete them or leave them?

Thanks


texts: Update entry Enabled value based on field value when saving

texts:
I am trying to update the value of the entry enabled field depending on a certain field value.

I am listening to the EVENT_BEFORE_SAVE event and have it updating as such $entry->enabled = $status == 'signedOff' ? true : false;

The issue I have is, if the entry is disabled at the start, then I edit the entry so that the status field to be signedOff, it updates the enabled value to true and it shows the lightbox field as being on, however it does not set a post date, and the entry can't be view on the frontend.

If i then resave the entry, it gets a post date and is visible on the frontend.

It seems that it may not be doing all it needs to when updating the enabled field to  be true on the EVENT_BEFORE_SAVE event.

Is there something I need to call, or another way I need to achieve this for it to be done correctly?

I have other plugins which listen to the EVENT_AFTER_SAVE event, so ideally would like to do it using EVENT_BEFORE_SAVE, so that the entry does not have to be saved.


texts: User restricted access to content via a common template

texts:
I’d like be able to restrict access to the content of entries, served by a common template, subject to the user group of the logged in user.

For example:

There is a template T
User U is a member of group G
Users V and W are members of group H
Entry A, served by template T, is accessible by group G, and therefore only by user U
Entry B, also served by template T, is accessible by group H, and therefore only by users V and W

Is this possible with Craft out of the box? Or does it require custom plugins?

I’ve done this kind of thing in ExpressionEngine using its ZooVisitor add-on, but this is my first foray into user restricted access to content with Craft.

If a sticking point is the single template, could it be done with a template per user group?

I'd be grateful if someone could point me in the right direction, as I can’t quite see the wood for the trees on this scope in the Docs.

Update:

I infer from https://craftcms.com/docs/templating/usermodel I can…

{% if currentUser.isInGroup(group) %} {# do something… #} {% endif %}

So I guess I just need a way to feed entry specific stuff into the conditional.

Or more ideally, dynamically write the conditional as an outcome of creating a new entry that has user group requirements assigned to it. Though that sounds a bit tricky.


texts: Multiple Site Manager Homepages and Fields

texts:
Apologies if this is a simple question :/

I'm using Multiple Site Manager for the first time and although I get it in principle i'm struggling to understand how to setup homepages.  Here's what I have got so far and then what i'm trying to do...

Done
1. Created multiple sites in CP (done)
2. Created templates/siteHandle directories (done)
3. Pointed webserver (done)
4. Confirmed correct index.twig is loaded on correct url (done)

I have then created a 'Single' section called 'Homepage' and checked both available sites to recognise this as the 'homepage'.  I then assigned a field called 'Introduction'.

My instinct is that any content applied to this 'Introduction' field should be different depending on which site was selected in the CP when adding and saving the content. So I can have a different homepage per website... because they use different index.twig which are loaded depending on url.

No... what actually happens is that any content I add or change in the homepage entry under 'Site One' in the CP immediately overwrites whatever was in 'Site Two' homepage entry and vice-versa!?

I did see a (untried) solution from a couple of years ago which was to create 'Homepage One', 'Homepage Two', ... and only assign each to the appropriate 'Site'.  But surely if Craft is loading a template based on a url and an assigned index.twig via 'siteHandle' directory, one 'Homepage' under each 'Site' should work?

Thank you for any explanation and/or guidance :)


texts: Got 404 on login attempt (Template not found: actions/users/login)

texts:
Can't login in my staging env since last full plugins/craft update (still able to in my local env).

I already...

Remove my composer.lock and /vendor files and re-install all components
Rename/delete the /web/cpresources directory
Flush all caches throught CLI command
Try to login in Private mode and other browsers

And still, I got this as a response :

{"error":"Template not found: 403.shtml"}

Here's the trace

https://pastebin.com/63NA1XQy

Here's the composer.json

{
    "require": {
        "craftcms/cms": "3.1.31",
        "vlucas/phpdotenv": "^2.4.0",
        "spicyweb/craft-neo": "2.3.5",
        "anubarak/craft-relabel": "1.3.1",
        "ether/seo": "3.5.4",
        "verbb/super-table": "2.1.20",
        "verbb/expanded-singles": "1.0.7",
        "verbb/field-manager": "2.1.0",
        "craftcms/redactor": "2.3.3.2",
        "verbb/navigation": "1.1.12",
        "pennebaker/craft-architect": "2.3.1",
        "marionnewlevant/twig-perversion": "2.1.0",
        "clubstudioltd/craft-inline-svg": "v0.1.1",
        "marionnewlevant/snitch": "3.0.0",
        "selvinortiz/patrol": "3.1.3",
        "fruitstudios/linkit": "1.1.11",
        "craftcms/contact-form": "2.2.5",
        "tomodomo/twig-pluralize-extension": "^2.0",
        "verbb/icon-picker": "^1.0",
        "craftcms/element-api": "^2.5"
    },
    "config": {
        "optimize-autoloader": true,
        "platform": {
            "php": "7.2.10"
        }
    },
    "autoload": {
        "psr-4": {
            "modules\\businesslogic\\": "modules/businesslogic/src/"
        }
      },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ]
    }
}

–

EDIT: Apparently this issue happens on all our Craft sites (both 2 and 3) on our server, will update as soon as I found out more


texts:
I have a situation where a form needs to have the ability add additional fields on the fly. For example, if the user clicks "add cat" a new section/tab appears with the fields to add a new cat. So if the user wanted to add 10 cats to the form they would have that ability without issue.

My first thought was that we could use a matrix field to dynamically add fields, but the field type is unsupported. Any help or ideas would be appreciated.

Example:


texts: Invalid Configuration Error in Craft CMS 3 using Nitro 2

texts:
I'm getting into Nitro 2 and so far loving it. I decided to create a scaffolding project to jump start other projects. Along the way, I ran into this error:
Invalid Configuration – yii\base\InvalidConfigException
/Users/cbad/websites/nitro/core/cms/web/cpresources doesn’t exist or isn’t writable by PHP.

The path exists and the permissions, look correct. They are drwxr-xr-x. I removed the contents of cpresrouces based on another solution found on google but didn't help. I'm missing something!
I was syncing my .env file and general.php when this began. In .env I made WEB_ROOT_PATH like this:
WEB_ROOT_PATH=/Users/cbad/websites/nitro/core/cms/web/

In general.php I did this:
'resourceBasePath' => App::env('WEB_ROOT_PATH').'cpresources',

If it helps, here are the permissions on the folders. They seem to be the same as those on a site that doesn't get this error:
drwxr-xr-x  2 cbad  staff    64 Mar  7 16:55 assets
drwxr-xr-x  2 cbad  staff    64 Mar  7 16:27 cpresources
-rw-rw-rw-@ 1 cbad  staff   604 Feb  5 20:12 index.php
-rw-rw-rw-@ 1 cbad  staff  1202 Feb  5 20:12 web.config

It seems to resolve to the correct location, but I get the error listed above. Is it obvious what I'm doing wrong?
Thanks!


texts: Element API with multiple categories gives back error 500

texts:
This works fine on localhost but crashes on remote Server. I can return one category, but it will crash when I try to display multiple categories. I also tried to save the categories in a variable and return the variable, which again worked on localhost but not on remote Server.

'programevent.json' => [
    'elementType' => ElementType::Entry,
    // 'cache' => true,
    'elementsPerPage' => 999,
    'paginate' => false,
    'limit' => 999,
    'criteria' => ['section' => 'program','type' =>'Event'],
    'transformer' => function(EntryModel $entry) {
        HeaderHelper::setHeader([
            'Access-Control-Allow-Origin' => '*'
        ]);
        $parent = $entry->getParent();

        return [
            'title' => $entry->title,
            'url' => $entry->url,
            'id' => $entry->id,
            'description' => (string) $entry->description,
            'level' => $entry->level,
            'themes' => array_map( function (CategoryModel $category) {
                return [
                    'id' => $category->id,
                    'title' => $category->title
                ];
            }, $entry->themes->find()),
            'kindOfEvent' => array_map( function (CategoryModel $category) {
                return [
                    'id' => $category->id,
                    'title' => $category->title
                ];
            }, $entry->kindOfEvent->find()),
            'languages' => array_map( function (CategoryModel $category) {
                return [
                    'id' => $category->id,
                    'title' => $category->title
                ];
            }, $entry->languages->find()),
            'parent' => $parent ? [
                'title' => $parent->title,
                'number' => $parent->number,
                'url' => $parent->url,
                'shuttleLine' => array_map( function (CategoryModel $category) {
                    return [
                        'title' => $category->title,
                        'color' => $category->color
                    ];
                }, $parent->shuttleLine->find()),
            ] : null,

        ];
    },
],


texts: multi-domain setup: template entry.url includes index.php

texts:
.htaccess is working fine. If I manually type url.com/about it shows the page. If I manually type url.com/asdf it shows 404 template page.

url.com/index.php/testPathInfo shows success

general.php has

return array(
    '*' => array(
        'omitScriptNameInUrls' => 'true',
    ),
...

but when templates contain {{ url('about') }} or {{ entry.url }} I get url.com/index.php?p=whatever-this-is-supposed-to-be

I'm probably missing something easy and obvious but I've been staring at it all morning. Could it still be the mod_rewrite enabled thing even though it's rewriting fine?

.htaccess content

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /

   # Send would-be 404 requests to Craft
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
   RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

AuthType Basic
AuthName "*DEV*"
AuthUserFile /home/username/public_html/dev/.htpasswd
Require valid-user


texts:
When using EVENT_DEFINE_RULES in module adding items to cart fails as address validation is run.
Should address validation only happen when address fields are present in the post data to 'commerce/cart/update-cart' or when progressing to payment as it is normal practice for users to add items to cart before submitting a shipping address.
module function;
Event::on(
            Address::class,
            Model::EVENT_DEFINE_RULES,
            function(DefineRulesEvent $event) {
                $rules = $event->rules;
                $rules[] = [['firstName', 'lastName'], 'required'];
                $event->rules = $rules;
            }
        );


texts:
I'm trying to create somewhat of a clever search for which only searches through certain pages of my site. At the moment, it can search those pages, but instead of the result returning the page name, I want it to return a field within the matrix field which the search query can be found in.
As an example below, if a user were to search for Lorem Ipsum, I want it to return the page name as well as the matrix field title.

This is my title
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

Desired result:

Page Name: This is my title

So far, the code I have can be found here, but I'm unsure how to access to exact matrix field title and add it to the query.
{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).order('score').section(['pageOne', 'pageTwo', 'pageThree']) %}

{% if entries|length %}
    {% for entry in entries %}
        {{ entry.title }}
    {% endfor %}
{% endif %}

Is this possible to achieve?


texts:
How would I sort blog entries displayed using AJAX?

What I want to achieve is initially show all posts from a channel (All) but then let my users sort through these posts with a sub navigation using the categories I've applied to the channel entries.

I can doing basic templating in CraftCMS but there seems to be very little clear documentation on how to this.

Thank you


texts:
I'm lost when it comes to adding a new admin user account. In the dashboard, I go to Settings -> Users, where I'm expecting to find a form where I could input a username, email address, password, etc.  Instead, I'm presented with a blank field layout. So I'm supposed to manually create fields for the username, email address, and password? What fields do I need to add and how do I know what to name the fields? Is there any documentation on this?
Neither the users documentation page nor the user management page offer any help. However, on the User Management page I read this sentence:
  To enable public registration, go to Settings → Users → Settings, and check the "Allow public registration?"

When I go to Settings -> Users -> Settings, all I see is a field to change the User Photo Location and a Save button, nothing else. I'm not trying to enable public registration, but the fact that that option is missing makes me wonder what else is missing.
I don't even know where to begin. Can someone point me in the right direction? Your help is greatly appreciated.


texts:
Hope this kind of question (a pointer request, actually) is alright with StackExchange guidelines. We're looking to store all our data in ES. Is this possible at the moment? Any plugin to do so? We're happy to explore Enterprise pricing if needed.

Thank you!


texts: Adding custom "keywords" to the search index

texts:
Is it possible for us to manually inject our own keywords into the searchindex via an event or something? eg.
Event::on(Entry::class, Entry::EVENT_AFTER_SAVE, function (ModelEvent $event) {
    $event->sender->addKeywords('blah blah blah');
});

We want to be able to automatically append extra keywords to some posts to increase the searchability, e.g. The Author name, API results etc.
Thanks


texts: How can I set the postDate and expiryDate from a front-end date picker via plugin?

texts:
I am working on a plugin that has a date picker only (no time). I am attempting to set the postDate to the value of whatever date was chosen on the front-end. I realize I need to save in this format: Y-m-d H:i:s

$start = craft()->request->getPost('startDate'); // 09/27/2015

// I'm not doing this right as it returns nothing.
$post = DateTime::createFromString($start);

// Returns a datetime object, but doesn't save.
$post = new \DateTime($start);

DateTime Object (
    [date] => 2015-09-27 00:00:00.000000  // trim the last decimal?
    [timezone_type] => 3
    [timezone] => UTC
)

I don't really care what the time is. It could always be midnight, or get the current time from the server. What is the best way to "assemble" the datetime?


texts: Database documentation / tips / resources

texts:
Hope this question isn't too vague.

I was wondering if there was any documentation or guidance on the database(s) underpinning Craft?

I am going to be working on a website with a fair amount of data and, crucially, the need to pull quite a lot of pieces of data frequently.

You can see a version of it here: http://unlockinglovelocks.co.uk

At the moment, using the dropdowns, you can navigate to a large picture which is mapped, so that clicking on each padlock will bring up its details. Eventually, my friend who requested the site expects to catalog a large number of these (potentially several large images, each featuring dozens of locks, related to just one site --- multiple sites per area --- multiple areas)

Am looking for a setup that won't end up being slow or inefficient. Basically want to understand a bit more about how the data storage with Craft works, so I can try and do it right :p

Any recommended resources would be welcome - I have had a google, and a browse of the Craft docs, without much luck.


texts:
I have a local site that was running perfectly, but last year when I ran the auto-update it seems that it did not finish the process. At that time didn't have time to have a look to what happened (please bear in mind I'm a designer, and this is not a client site :D), and yesterday I saw that the admin dashboard was not working, and some pages were not loading too.

I downloaded the files again from the website, replaced the craft/app folder following the manual update instructions, and all seem to be fine (site works and dashboard works), except that when I go to entries I get this error:

  CDbCommand failed to execute the SQL statement: SQLSTATE[42S02]: Base table or > view not found: 1146 Table 'craft.craft_elementindexsettings' doesn't exist

Other pages of the admin side works fine, I've cleared the cache and that made no difference.

When I uploaded the new craft/new and went to /admin, I did not get any message about updating the database as the instructions say.

I also can't recall why the auto-update didn't work properly. I kind of remember that the page got stuck, or I got an error, but as the internet in this office is quite bad, I thought the problem was at my end, not craft.

Any ideas on how to solve it?
Is it possible to re-run the auto-update of the database?


texts: Get Related Entries and then filter those by specific category in url segment

texts:
Channels:
  Photographers
  Photos - entries field handle "photographers"
         - categories field handle "category"

url structure where segment 2 is the photographer slug and segment 3 is the photo category slug:

domain.com/photographers/john-doe/food

On the photographers detail page I need to pull up the photos entries that are related to that photographer and in the category determined by segment 3

Set at the top of the page and used in a couple of different spots

{# set segment variables so we can use shorthand #}
{% set segment_2 = craft.request.getSegment(2) %}
{% set segment_3 = craft.request.getSegment(3) %}

{# get related photo entries #}
{% set photos = craft.entries.section('photos').relatedTo(entry) %}

Then where I want the photos to display I have the following code which outputs 2 entries from the photos channel. These are both related to the current photographer but in different categories. Only the one entry that is both related to the photographer and the current category should be output.

  {# set currentCategory to category id from segment 3 #}
  {% set currentCategory = craft.categories.slug(segment_3).first() %}

  {% set photos = photos.relatedTo(currentCategory.id) %}

  {% for photo in photos %}
    {{ photo.title }} <br>
  {%endfor %}

I'm not sure how to combine and filter these relations. Please advise.


texts: Template variables from active record on NULL value

texts:
I have a template variable thus

public function twitterAccounts()
{
  return craft()->myPlugin->getAllAccounts();
  //Craft::dd(craft()->myPlugin->getAllAccounts());
}

it calls the following service method

public function getAllAccounts()
{
  return MyPlugin_TwitterAccountRecord::model()->findAll(array('order'=>'oauth_token'));
}

the record is set up like this:

class MyPlugin_TwitterAccountRecord extends BaseRecord
{
    public function getTableName()
    {
        return 'myPlugin_twitter_accounts';
    }

    protected function defineAttributes()
    {
        return array(
            'screen_name' => AttributeType::String,
            'id_str'      => AttributeType::String,
            'password'    => AttributeType::String,
            'oauth_token' => AttributeType::String, // this is a reference to the oauth_tokens table ID, not the actual token.
            'last_tweet'  => AttributeType::DateTime,
            'is_company'  => AttributeType::Bool,

            //array(AttributeType::Enum, 'values' => "alcohol,mixer,other"),
        );
    }
}

I have three records in that table 2 have values for the oauth_token field and one is NULL.

Before the NULL value row the following worked fine in a template...

{% set twitterAccounts = craft.myPlugin.twitterAccounts %}
{% for thisAccount in twitterAccounts %}
  {% if thisAccount.oauth_token is defined and thisAccount.oauth_token is not null %}
    {{ thisAccount.screen_name }} is oauthed
  {% else %}
    {{ thisAccount.screen_name }} is not oauthed
  {% endif %}
{% endfor %}

but now I'm getting (devmode)

Craft\MyPlugin_TwitterAccountRecord and its behaviors do not have a method or closure named "oauth_token".

The annoying thing is when I comment out the return in the template variable method and use the Craft::dd() I see all three rows with their proper attributes, including the null value.

If I change the conditional to

{% if false and thisAccount.oauth_token is defined and thisAccount.oauth_token is not null %}

...in order to always be false and skip into the else, it lists all three accounts in there!

Can someone point me in the right direction here please? Is there a bug in templating with a NULL value in an activerecord collection? (this happens whether or not I have that orderBy oauth_token in the findAll())

Cheers.


texts: "The license located at config/license.key belongs to gridserver.com"

texts:
Getting this notification at the top of the control panel. This is a solo/free license version of Craft.

It happened after I updated my client's domain's DNS to point to my server.

When I originally set it up, I installed craft on my media temple grid server. The access domain for it at that time was: http://centraldsmhomes.com.s179491.gridserver.com. As soon as I updated the DNS for centraldshhomes.com to point to my mediatemple server, I got the license issue.

Can't seem to find any solutions to this problem.


texts: Segment to filter through categories slug

texts:
I've seen plenty examples of using the uri segment like below, but it ain't working for me, anyone had same sort of issue?

{% set segment = craft.request.segment(2) %}
{% set pageCats = craft.categories('photoCategories').slug('segment') %}
{% set entries = craft.assets.group('photoUpload').relatedTo(pageCats).find() %}

{% for entry in entries %}
    {{ entry.stuff }}
{% endfor %}

It works if I hard code the segment name .slug('skateboards') and the segment does render when {{ segment }} on other areas of the same page.


texts:
I couldn't find this anywhere so I thought I would post the answer. How do you limit the output of a navigation element to a specific entry type.

This question is explicitly for the navigation element - I only want to show a specific entry type in a navigation element.


texts: Change the name of 'CraftSessionId' from HTTP header requests?

texts:
I am running a Nginx server and tried to hide the 'Set-Cookie' parameter from the HTTP header output when using curl -I hostname.com - I applied the Nginx configuration using:

proxy_hide_header Set-Cookie;

Using this worked as intended - until I noticed that any request to login to the control panel simply resulted in reloading the admin login page.

Is there a way to change or hide this that still allows users to login to the control panel?


texts: Problems cloning an old production Craft CMS project

texts:
I'm attempting to clone a craft CMS (v3.3.15) project into a new local development environment and as expected, I'm experiencing many dependency issues. For various reasons, including having to replace my original development machine, the production site has gone without any attention for over a year, although it still works perfectly. I'm having issues with the fxp/composer-asset-plugin and several tables although present in the database dump, are not available on the local site (users, entries, assets, etc), templates work fine. My cloning process which used to work is now failing.
I've tried using composer at v1.x and the plugins at the same versions currently running on the server and also tried updating composer to 2.x and updating the plugins to their latest version, however, neither seems to work. I've also tried updating using php craft. I'm obviously missing something major. Any help would be appreciated.


texts: Fire event first time future dated entry goes 'live' from 'pending'

texts:
Is there a way I can run some code from a plugin when a future dated entry goes 'live' from 'pending'? I am trying to send an email update that a new entry has been posted. The related post below helped me with this, but it doesn't seem to cover future dated entries.

Here's what I have so far...

craft()->on('entries.onBeforeSaveEntry', function(Event $event) {
    $entry = $event->params['entry'];

    if ($entry->section->handle !== 'blog') {
        return;
    }
    if ($entry->status !== 'live') {
        return;
    }

    if (!$entry->getContent()->emailSent) {
        // send email
    }

    $entry->setContentFromPost(array('emailSent' => true));
});

Related to: Checking for first time an entry is "published" i.e. saved with a Live status

Thanks!


texts: Custom routes using kebab {type} in URL segment

texts:
I have a section that has multiple entry types. I would like to use kebab-style url segments in the URL format. I can get the articles to serve kebab URIs using this for the section's Entry URL Format:

our-firm/{type.name|kebab}/{slug}

However, this will not call the template when making the page call — needs to be:

our-firm/{type}/{slug}

So, how do you set things up to have the best of both worlds: kebab'd url segments and working templates?


texts: How to change the Slug in case of copied entries?

texts:
I have a channel, where entries do NOT have their own URLs. But a slug is created automatically every time I save an entry. And I have auto-generated titles.

Often I save an existing entry as a new entry and just change something which changes then my auto-generated titles also. But the slug does not change (only a number is added).

Now my problem: The search function also searches the slug what then results in wrong search results.

My question: The only solution I've found is to manually delete the existing slug and to save the entry again. Is the a better solution for my problem?

Thank you very much for your help!


texts: Removing index.php from URL even after .htaccess updates?

texts:
I am a little afraid to post this, but I'm running into an issue and haven't found a solution yet. I've been able to successfully remove the "index.php" from all my URLs, however I'm still finding that if I manually add "index.php" to any URL, I can still view the page and am not redirected to a URL without "index.php". For example:

http://domain.com/events/

Works just fine, but if I visit http://domain.com/index.php/events/ I can still view the page. Any idea on how to force it to redirect me to just http://domain.com/events/?

Here's my .htaccess file for reference:

# ----------------------------------------------------------------------
# Remove index.php from URLs
# ----------------------------------------------------------------------
<IfModule mod_rewrite.c>
  RewriteEngine On

  # Force trailing slash
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

  # Force www
  RewriteCond %{HTTP_HOST} =domain.com [NC]
  RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

  # Send would-be 404 requests to Craft
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
  RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

Is this even possible with Craft? Thanks in advance!


texts: Change currency in Craft CMS using the Charge plugin

texts:
Okay so I have Charge setup with Stripe. I have entered in the connection details and selected the currency to pounds in the Stripe credentials in the plugin settings. However when I view the charges the money is correct in pounds but the symbol is a dollar sign... I need to change it to the pound symbol.

Has anyone come across with this issue and have I missed something of.. EG. Config file needs currency symbol override etc.

Hope this makes sense.


texts: Why the entry-Variable doesn't exists after search?

texts:
I created a search form in my navigation and as it is described in the documentation, I created an search/results.html. And actually it works so far.
Now comes the problem: The results.html extends the "_base.html" and in this file I set the meta properties like this:
{% if entry.seoPageTitle is defined and entry.seoPageTitle != null %}
  {% set metaTitle = entry.seoPageTitle %}
{% else %}
  {% set metaTitle = entry.title %}
{% endif %}

and the HTML:
<title>{{ metaTitle }}</title>

And also this works so far.
But in combination it doesn't work. When I tipe in a Word in my Searchform and click "Search", then it gets "Variable "entry" does not exist". How can I fix it?


texts: Editing a users custom fields from a plugin action Craft 3

texts:
Does anyone know if there is a block on updating users form an action?

Trying to update a users custom field in craft 3 via plugin in the admin. The admin template calls an ajax call to the action when a drop-down is changed.

This works ok in the base of the plugin, but not in an action.

    public function actionUpdateuser()
    {
        // Update user data
        $userId = 67852;
        $user = Craft::$app->users->getUserById($userId);
        $user->setFieldValue('userCompanyName', 'New Name 2');
        $result = Craft::$app->elements->saveElement($user);

        return $result;
    }

The action fires ok and can return other things just does not update the user.


texts:
I've recently built a site on Craft, and while developing it locally I had purchased a license for Craft Client. After publishing the website to the production server the administration panel is showing a modal window with the text "You're running Craft Client with a Craft Personal license."

I've checked and made sure the license.key file is where it's supposed to be, and that the file is accessible. I've built a couple of websites on Craft before and have not had this issue until now.

I've tried re-uploading the site to a different server/domain, and it said in the admin panel that the license didn't belong to this domain, but the other domain it was originally uploaded under. So it obviously is reading the license file. I clicked to transfer the license to the new domain, and the same issue started occurring (modal window the the message "You're running Craft Client with a Craft Personal license. What would you like to do?").

As Craft initially read the license file (otherwise how would it know that the site didn't belong to the domain?), it means the license file exists and is valid, so I suspect it's an issue on Craft's side. Unfortunately their support is taking a little long so I thought I'd come to the community to hopefully get some help.

Thanks, Ben.

Edit: From what I remember from a year ago, this was entirely my own fault. I had purchased the license on the staged version of the site. My bad.


texts: Is it possible to use `guestEntries.beforeSave` to validate custom fields?

texts:
Say, I want to validate an email address or a special URL e.g. YouTube URL, would I be able to use a custom plugin with the guestEntries.beforeSave hook to do this?

The basic hook call:

craft()->on( 'guestEntries.beforeSave', function(Event $event) {
    // Call custom validation here
});

Would I be able to setup a model with the method defineAttributes and run that?


texts: Matrix Gallery, with every image having it's own unique URL?

texts:
As of right now I have nine or so structures created, each including it's own Image Gallery created in a Matrix.

Is it possible to give each image inside that matrix a unique URL?

What I'm trying to accomplish is to be able to create multiple galleries, each gallery when clicked will just pull up into a Fancybox. The problem with this, is there also needs to be social media sharing (Facebook, Twitter, Pinterest, and Google+) for each item in the gallery. After a bit of research the Facebook og:image tag only shares what is in that URL being shared. So I will need to be able to create pages for each item in the gallery. Would this be possible?


texts:
We are encountering an issue where some/most of our blog pages are not indexing with Google. Some random blog pages are indexed but most are not.

The pages are being rendered correctly by the google bot but are not being indexed.

This is our _entry.html that pulls in the craft blog and renders the individual blog view:

{% set title = entry.title ~ " | Blog" %}

{% if entry.metaDescription | length > 0 %}
    {% set description = entry.metaDescription  %}
{%else%}
    {% set description = entry.body|split('
') [0] | striptags | slice(0, 144)  %}
{%endif%}

{% block meta_tags %}
    {{ siteMacros.returnMetaTags({
            'description' : description,
            'og:title' : entry.title ~ ' | Default Titlge Here',
            'og:image' : siteUrl ~ 'assets/favicons/favicon-196x196.png'
        })
    }}
{% endblock %}

{% block content %}

{{entry.title}}

            {% include 'content_blocks/_entryBody.html' %}

            {% include 'content_blocks/_blogCategoryList.html' %}

{% endblock %}

This just filters everything through the _entrybody.html which looks like this:

{% import '_macros' as siteMacros %}

{%if entry.subHead | length %}

{{entry.subHead}}

{%endif%}
    {% if entry.image | length %}
        {% set image = entry.image.first() %}
    {% elseif entry.curataImage | length %}
        {% set image = entry.curataImage %}
    {%endif%}

    {% if image | length %}
        {{ siteMacros.responsiveImage(image) }}
    {%endif%}

    {%if entry.video | length %}

    {%endif%}

        {% set paragraphs = entry.body|split('
') %}
        {% set pfirstBreak = (paragraphs | length / 2 ) | round - 1 %}
        {% set firstParagraphs = paragraphs | slice (0, pfirstBreak) %}
        {% set lastParagraphs = paragraphs | slice (pfirstBreak, paragraphs | length ) %}

        {% for p in firstParagraphs %}
            {{p|raw}}
        {%endfor%}

        {%if entry.pullQuote | length %}

                {{entry.pullQuote}}

        {%endif%}

        {% for p in lastParagraphs %}
            {{p|raw}}
        {%endfor%}

        {% if entry.pdf | length %}

                Related Documents:
                {%for pdf in entry.pdf %}

{{pdf.title}} [pdf]

                {%endfor%}

        {%endif%}

        {% if entry.referringSite | length  and  entry.readMoreLink | length %}

Read the full article at {{entry.referringSite}}

        {% endif %}

    {% if not hidePostDate %}
        {% set category = entry.category.first %}

Posted {{ entry.postDate.format('F j, Y') }}{% if category | length %} in {{category.link}}{%endif%}.

    {% endif %}

I'm unsure why any of this would cause the pages not to be indexed by google. Some pages are indexed that go through this same code but others are not.


texts: Using a variable with array of ElementIds to use in craft.entries.id

texts:
I want to show entries according to an array.

This is my code:

            {% set navsubids = craft.amNav.getNavRaw("hoofdnavigatie", {startFromId:25})  %}
            {% set navsubidarray = [] %}

            {% for navsubid in navsubids %}
                    {% set navsubidarray = navsubidarray|merge([navsubid.elementId]) %}
            {% endfor %}

            {% set navsubidarray = navsubidarray|join(', ') %}

            {{ navsubidarray }}

            {% for entry in craft.entries.id('{{ navsubidarray }}') %}
                {{ entry.title }}

            {% endfor %}

The variable gives back that what I need (18, 17, 19, 4, 20, 21, 22, 23) but the for entry loop isn't returning anything.


texts: Populating an RSS feed with full post content?

texts:
I'm using Matrix to give loads of flexibility with blog posts, but it means things aren't as simple when it comes to RSS than if just using a single field called Body.

How is everyone else dealing with this?

EDIT: As Christian points out, I'm party asking what is best practice for RSS feeds. But I'm also exploring the extra flexibility or complexibility offered by using Matrix for blog post content. Best practice is constantly evolving, and I think it quite possible best practice for creating an RSS feed using Craft may turn out to be different best practice to feeds generated by something else, simply because the flexibility is there (just as long-form content is becoming more commonplace as CMSs start to deal with it better). For example, using Matrix we can pick and choose which types of content are included within the feed to a much greater degree. Or do we just say, no, a feed should contain this, this and this and you shouldn't mess with that, no matter what the tool?


texts: Need help trying to pass a variable of a related entry

texts:
On my page, I have a form which is using Freeform (Solspace).

I'm attempting to setup a custom redirect URL for the form. The form will apply to numerous entries in a channel and some will require different redirect URLs. The main channel in question (Animals) has a relation field which relates it to another channel (Adoption Price). This channel contains a URL field which ideally, I would like the user to be redirected to upon submitting the form. Below is what I have tried so far but with no luck.

  //Setting the variable

  {% for priceBracket in entry.relatedAdoptionLink %}
      {% set priceURL = priceBracket.adoptionPriceLink %}
  {% endfor %}

  //The Form

    {% set form = craft.freeform.form("animalAdoptionForm", {
        labelClass: "form-label",
        inputClass: "form-control",
        instructionsBelowField: true,
        overrideValues: {
          animalToAdopt: entry.title,
        }
    }) %}

    {{ form.renderTag({returnUrl: "{{priceURL}}"}) }}

Can anybody help me out with this? Setting the variable directly via the entry would be more straight forward but I'm trying to pull the information I need from a relation in another channel.

Thanks


texts:
We've got a large formerly custom form which we're having problem saving.
Saves fine with eleven fields but any more than that and it is not saving, returning the error message: Couldn't save form

Any idea why this might be a problem?


texts: Using Solspace Craft Calendar plugin, how can I get random events within a defined timeframe?

texts:
I'm trying to achieve the following (without much luck), using Solspace Calendar plugin:

All events (no calendar specified)
A defined timeframe (one week)
Only unique events, that have at least 1 occurrence in that week, so no reoccurrences
In a random order
Limited to a specified number

I tried, without satisfying result:

{% set events = craft.calendar.events({
    dateRangeStart: now |date('Y-m-d'),
    dateRangeEnd: now |date_modify('+7 days') |date('Y-m-d'),
    order: 'RAND()',
    loadOccurrences: false,
    limit: 3,
}) %}

Any Calendar experts out there?


texts: Routing: ignoring a segment from the URL

texts:
I am trying to configure my routes so that the last segment of the URL is ignored and can be used as parameter in the twig file.

for example, the following URL should ignore the city-segment

/services/name-of-the-service/city

and should be routed to

/services/name-of-the-service

I have currenty set up the following routing-rule

'services/<service:{slug}>/<city:{slug}>' => 'service/<service>'

Which results into a 404 and says
Unable to resolve the request "services/name-of-the-service".
Which is the exactly the URL that I want to get parsed...

When I am trying to route to the template

'services/<service:{slug}>/<city:{slug}>' =>  ['template' => 'services/_entry']

Which seems to load the correct template but the entry can not be parsed...

Any ideas how to solve / work around this problem?


texts:
I've been working on a site locally in devMode. I moved it from Craft 2 to Craft 3. I set devMode to false in config/general.php file and in admin it doesn't show the devMode bar at the top, but everything in the front of the site was pointing to my local environment.

The only thing that has worked is setting my siteUrl in the 'dev' to the actual site

// Dev environment settings
'dev' => [
    // Base site URL
    'siteUrl' => 'https://footwearoutfitters.net',

    // Dev Mode (see https://craftcms.com/support/dev-mode)
    'devMode' => false,
]

While this works, I'm concerned if it thinks it's running in devMode I'll have potential security threats.


texts:
How do I pull in entries from every site? I can't even seem to pass more than one argument to the .siteId parameter:

{% set entries = craft.entries({
    section: 'resources',
    siteId: [1,2,3],
}).all %}

That gives me the error:

  Argument 2 passed to craft\services\Elements::getPlaceholderElement()
  must be of the type integer, array given

I also tried:

{% set entries = craft.entries({
    section: 'resources',
    siteId: craft.app.sites.allSiteIds,
}).all %}

But got the same error.


texts:
I'm trying out the Image Optimize plugin (with Lazyload) but not convinced I have set it up correctly.  The resulting code is quite a lot and it's also creating breakpoints I didn't create on the field?  Additionally, the plugin is creating a lot of individual directories on my S3 server.
Here's the output HTML for just one image...
<img class="lazyload" src="data:image/jpeg;base64,%2F9j%2F4AAQSkZJRgABAQEAYABgAAD%2F%2FgA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2OTApLCBxdWFsaXR5ID0gNTAK%2F9sAQwAQCwwODAoQDg0OEhEQExgoGhgWFhgxIyUdKDozPTw5Mzg3QEhcTkBEV0U3OFBtUVdfYmdoZz5NcXlwZHhcZWdj%2F9sAQwEREhIYFRgvGhovY0I4QmNjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2Nj%2F8AAEQgAAwAQAwEiAAIRAQMRAf%2FEAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC%2F%2FEALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29%2Fj5%2Bv%2FEAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC%2F%2FEALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5%2Bjp6vLz9PX29%2Fj5%2Bv%2FaAAwDAQACEQMRAD8Ay9HANwhPXy26fVKj1HKTsATgEEZOev8A%2BqiioW5pI%2F%2FZ"

data-srcset="
https://url.cloudfront.net/general/_2200x412_crop_center-center_82_line/679/pexels-florent@2x.jpg 2200w,
https://url.cloudfront.net/general/_1600x300_crop_center-center_82_line/679/pexels-florent@2x.jpg 1600w,
https://url.cloudfront.net/general/_1280x240_crop_center-center_82_line/679/pexels-florent@2x.jpg 1280w,
https://url.cloudfront.net/general/_1024x192_crop_center-center_82_line/679/pexels-florent@2x.jpg 1024w,
https://url.cloudfront.net/general/_2048x384_crop_center-center_61_line/679/pexels-florent@2x.jpg 2048w,
https://url.cloudfront.net/general/_730x410_crop_center-center_82_line/679/pexels-florent@2x.jpg 730w,
https://url.cloudfront.net/general/_1460x821_crop_center-center_61_line/679/pexels-florent@2x.jpg 1460w,
https://url.cloudfront.net/general/_320x60_crop_center-center_82_line/679/pexels-florent@2x.jpg 320w,
https://url.cloudfront.net/general/_640x120_crop_center-center_61_line/679/pexels-florent@2x.jpg 640w"
sizes="100vw" />

Here's my template code...
{% set optimizedImages = staff.photo.one().fd_optimised %}

My Image Optimize field (fd_optimised) has width variants for:
2200px, 1600px, 1280px, 1024px, 730px and 320px.  So where are the 2048px, 1460px and 640px variants coming from?
Many thanks for any advice!


texts: Speeding up the pageload of a page with a huge Matrix

texts:
We've got a site with a navigation on top, which navigates to anchorpoints on the page, but the whole page is built with 1 matrix. The page will probably be very long and will have all kinds of images (small & big) in it. I've set image transforms, so images won't be a problem.
BUT: is it possible to speed up the site with lazyloading or something like that when there's 100+ matrix elements in it?
And on that note I guess the biggest problem we'll face is having the anchor points still working: if they click the anchorpoint they should be able to scroll to that point, even if it's not visible yet.

Is this possible?


texts: Query for multiple date ranges on a date field

texts:
I'm able to successfully query a date field for a date range using this syntax:
{% set entries = entries.startsOn(['and', '>= '~firstDay, '< '~ lastDay]) %}

What I would like to do however is query that field for multiple date ranges at once with an or operator.
I can do this with other fields but the date range already using an and operator complicates matters so I can't do the same.
{% set data = data|merge(['or']) %}
{% for item in items %}
     {% set data = data|merge(['*'~item~'*']) %}
{% endfor %}

Any suggestions gratefully received!


texts:
When trying to upgrade Craft CMS automatically we get a message relative to the SSL certificate of the CDN being incorrect, though it works fine on a local machine.

  Craft was unable to install this update :(

  [curl] 51: SSL: no alternative certificate subject name matches target
  host name 'download.craftcdn.com' [url]
  https://download.craftcdn.com/craft/2.6/2.6.2967/Patch/2.6.2962/41d682834df8c739ead7a1abab6a4571.zip

Anybody else getting this?


texts:
I'm uploading a PNG image into my assets folder and linking to it from my css file - standard stuff, nothing special. However the PNG image is returning with a 500 error in the console and not displaying. When I visit the image directly in the browser I get a lot of numbers and:

Template Error

Unexpected character ""

I'm working locally with MAMP Pro and I've only recently restored my computer from scratch. I'm wondering whether this is a Craft issue or potentially a MAMP issue. It works fine if I use a Jpg instead or an externally hosted PNG.

This is also happening when I link to it with an img tag


texts: How to create manually an Entry from command line

texts:
I would like to migrate content from external source to my Section model. So I have to create Entries manually. Is there any better way to do this beside this snippet from the documentation:

$entry = new Entry();
$entry->sectionId = 10;
$entry->typeId = 1;
$entry->fieldLayoutId = $entry->getType()->fieldLayoutId;
$entry->authorId = 5;
$entry->enabled = true;
$entry->title = "Hello World!";
$entry->setFieldValues([
    'body' => "
I can’t believe I literally just called this “Hello World!”.
",
]);
$success = Craft::$app->elements->saveElement($entry);
if (!$success) {
    Craft::error('Couldn’t save the entry "'.$entry->title.'"', __METHOD__);
}

reference: https://docs.craftcms.com/api/v3/craft-services-elements.html#saveElement()-detail

I am looking for a factory method, or a Builder to properly create the object. Using EntityController is not an option, because I would like to use it from CommandLine interface.


texts: How do I check if a given number is prime in twig?


texts: Craft 3.1.7 live preview multi-site only works on home page

texts:
I am running sta-A and site-b on same installation.
I have cookie set for domain and have htaccess with CORS origin set to allow *, and also updated the nginx config to allow CORs. I know this last one works as font-awesome was blocked and is now working once i had updated the local nginx conf file.

The second domain only has live preview available on its home page. Any other entries created for the second domain have the link icon in the entries list in CP but when editing have no live preview option.

I thought 3.1.7 tokenized this?


texts: Multiple regexes/masks in Sprout Field validation

texts:
Is there a way to include multiple validation masks in Sprout Fields? I've tried to do this (for my phone number validation):

#### ####|### ## ###

Since both of those are valid. If I try to write it out as a real regular expression, like this:

^([0-9]{4}) ([0-9]{4})|([0-9]{3}) ([0-9]{2}) ([0-9]{3})$

it just fails: preg_match(): Empty regular expression


texts:
I am working on a site that requires a filter option based on tags.
Each entry will have two sets of tags (e.g., colors and shapes)

{% for tag in craft.tags.group('colorTag') %}
{% for tag in craft.tags.group('shapeTag') %}

How can I create a filter that allows you to check boxes for those tags and display the results that match ANY of the selected tags?

The results will show entries with the Blue tag, entries with the Yellow tag and entries with the Triangle tag.

Thanks so much!


texts: craft.matrixBlocks element queries with .type()

texts:
I'm using Craft Pro 3.0.0-beta.19 and I try to query matrix blocks with craft.matrixBlocks(). Background: I have event series (=structure) with a matrix block containing 1:n dates for each series. My block type in the "dates" matrix block is "eventDate" and looks like this:

this works:

{% set entries = craft.matrixBlocks() %}

Since this is the first matrix block I have I get all the entries I have (2):

{{ entries | length }} will output: 2
{{ entries.one().type }} will output: eventDate

Good.

Now I want to limit the blocks to eventDate only

{% set entries = craft.matrixBlocks.type('eventDate') %}

On the first glance this seems to work, I get the same results.

But when I change this to

{% set entries = craft.matrixBlocks.type('WhateverGoesHere') %}

I still get the same results. Am i not understanding this or is it a bug?

Thanks,
Matthias


texts: How can I return only 1 random block in a Matrix in Craft using Twig?

texts:
I have a matrix with a couple of text fields for a caption, location and URL and an image

Every time this page loads I want a random slide to show - so the background image is random, as well as the relevant text fields.

I've tried several variations of the below but keep getting a template error of "Array to string conversion"

Why is this happening? How can I achieve the desired result?

{% if entry.carouselMatrix is not empty %}
    {% set currentSlide = shuffle(entry.carouselMatrix.slides).first() %}

        {% for slide in currentSlide.first() %}
            {% set image = slide.image.first() %}

                    {{ entry.heroText }}

                    {{ slide.caption }}

        {% endfor %}

{% endif %}


texts:
I'm dealing with the import plugin, processing a .csv file.
in the .csv there's a column with | separated values that shoud be inserted in a table field.
The entry are created correctly, also the table field ( just 1 column ) has the correct number of rows, but the content is empty ( $featureContent length is > 0 ).
Here's the code, what am I missing?

foreach ($fields as $handle => $value) {

   $value = explode('|', $value);
   $content[$handle] = array();

   foreach ( $value as $featureContent ) {
      $featuresRow = array( 'singleFeature' => $featureContent );
      array_push( $content[$handle], $featuresRow);
   }

 }

--- Edit ---

According to this response the table data is stored in Json format, so now I'm trying to create the table providing a json formatted string.
As this:

[
  {"col1":"very beautiful"},
  {"col1":"really beautiful"},
  {"col1":"astonishing beautiful"}

]

Still, this doesn't work for me. It doesn't even creates the 3 rows as the other approach.


texts: Get the ID of a new entry when it's saved

texts:
Is there a way to save a new entry with a template form, then pass the ID of that new entry along to the redirect location?

The use case is, I'm interacting with a scheduling service and want to pass along the new craft entry ID in a query string to their API. The service has a webhook that fires on successful scheduling (and provides an appointment ID).

Currently, I'm getting the user's email address returned from the API, then assuming that user's most recent section/entry in craft is the one I'm looking for. After that, I can unambiguously handle reschedules and cancellations by referencing the appointment ID.

The form has the following inputs

<input type="hidden" name="action" value="entries/saveEntry">
<input type="hidden" name="redirect" value="/schedule">

and I'd like the /schedule page to get a entryId passed into it


texts: What happens when extending an extended template?

texts:
If template2.html contains {% extends 'template1.html' %}
and template3.html contains {% extends 'template2.html' %}, what happens to things like {% block %}{% endblock %} and variables?


texts:
I'm implementing a site with just one very big matrix field called 'blocks', and all my frontend is designed with BEM CSS with a lot of components.

But i'm facing problems with this big field.

1) If two block types have a field called 'cssClasses' of type 'Multi-select', it's not validating correctly and is saving just one of this fields. I've found a workaround, changing the name of second field, but frequently i lost a lot of field values with this problem. (i really don't know exactly why this problem is happening sometimes)

2) If i have too many fields on my block items, there are some implicit field limit that i don't know where is, that all block item fields after this limit are deleted when save... its a very big problem, because all my entries loose all the data for these fields. It's really a big problem for me... (maybe can be max_input_vars value and/or post_max_size)

3) It's very slow to page render this big field when testing on Amazon(rds large + 1000 IOPS SSD) or Heroku (clearbit database high io), compared to my localhost.

PS:
I'm using LinkIt plugin and SuperTable plugin for some fields...


texts: Is it possible to skip Craft Installer through command line or something similar?

texts:
I´m trying to automate the installation process of Craft as far as possible.
So my question is the following:

Is there a way to automate the Craft installer (the one with the monkey), possibly through a config file or through the command line or whatever. Of course there are possible solutions using headless browsers, but I think that would be too much of an effort for that task.

I´m really looking forward to your replies!

Thanks in advance and cheers!

Ferdi


texts: A for loop within a for loop that is split

texts:
Possibly a bad question title...sorry but wasn't sure how to describe it.

Basically I have a for loop that every 4 items I want to pull in a different item from another loop. This is a series of Q&A's in a staff interview, and each 4th item I want to break the side by side and pull in a full width quote.

Here is the breakdown of the code.

{% set pullQuotes =
  [
    'My biggest source of pride to date is my involvement in the Olympic Park Project: that’s part of my personal legacy.',
    'Frosts is a family environment. We’re successful from within. With our recent management acquisition of Frosts Landscapes, we’ve developed a new atmosphere, new business, and a great environment to work in. '
  ] %}

    {% for row in entry.questionsAndAnswers %}
      {#            {% set width = loop.index is divisible by(3) ? 'lg:w-full' : 'lg:w-1/2' %}#}

{{ row.question }}

          {{ row.answer }}

      {% if loop.index % 4 == 0 and not loop.last %}

        {% for entry in pullQuotes %}

              {{ svg('@icons/quote.svg', class="w-20 h-20  text-lime-500 flex-shrink-0 fill-current") }}

              {{ entry }}

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

The problem I have is that the loop of the pullQuotes is being iterated each time after every 4th item. What I want to do is pull the first item from the pull Quotes in position 4 and the second item from pullQuotes in position 8 and so on...

Both of these will be CMS managed and so the number of Q&A's and pullQuotes could vary, so it needs to be flexible.

Anyone able to help me figure this one out?


texts:
I'm creating a very basic message board type of thing and want to show new posts since as user's last visit. I'm looking to use Cookies, but need some help with the logic.
Should I be setting a cookie when the user visits, and then retrieve that next time and delete the previous one? If so, how can I set the expiration for next session? Would I leverage the Craft login session. This will only be for logged in users, so can I leverage that?
{% do craft.cookies.set('userReturns', 'userReturns', now | date_modify("+5 minutes").timestamp) %}
{% set timestamp = getCookie('userReturns') %}
{% if element.postDate >= timestamp %}
  New
{% endif %


texts: Craft CMS and LiteSpeed (403 error on login)

texts:
When trying to login to the administration section on a server running LiteSpeed, half the time LiteSpeed triggers a 403 Forbidden message and locks that computer out of the entire server Craft is running on. I'm assuming Craft is doing something that LiteSpeed deems as suspicious but I have no idea what that could be.

I'm currently trying to get access to the logs but the host is taking it's sweet time. In an ideal world I would just find another host but in this situation that's just not feasible. I'm pulling my hair out trying to get this to work, and I found love with Craft that I don't want to deny.

If anyone could point me in the right direction I would be so grateful!


texts: So how do i redirect to error/inferior template.  I could add my template at the templates folder but thats not really nice.  Is there something like {% exit 404 %} but for the inferior page?


texts: Get the territory / country belonging to a locale?

texts:
I'm asking, because I was trying to find out the whole afternoon. Found some posts, but they were related to getting all territories.

Example:

I have locales like English, French, Chinese and I'd like to add country to each related locale from territories, because each locale.php in /data folder has the values.

So it would looks like: Territory(United Kingdom) locale(English)

Code I'm working on:

{% set locale = craft.i18n.getCurrentLocale() %}
    {# Configure site locales #}
    {% set locales = ['en', 'en_gb', 'sk'] %}
    {# Check if locale equals the requested page locale #}
    {% if locale == craft.locale %}
        {% set current = true %}
    {% else %}
        {% set current = false %}
    {% endif %}

  {% for locale in locales %}

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

  {% endfor %}

The output is a list of locales with native name:

(English)
(British English)
(Slovak)

If there would be a way to relate it's country to each locale from territories, that we wouldn't have to touch app folder to customize the lang files, like I read in other posts.
By doing so, We could achieve this:

World (English)
United Kingdom (British English)
Slovakia (Slovak)

Update

I think it moved on a little bit. With the code @carlcs provided, Craft was able to get a territory. There must to be some bug in it, because from 3 locales, It got assigned to only one territory (United Kingdom - British English).

Here is updated code.

 {% set locales = ['en', 'en_gb', 'sk'] %}
   {% for locale in locales %}
      {% set subTags = locale|split('_') %}
         {% set territory = subTags|length > 1 ? craft.i18n.getLocaleData(craft.locale).getTerritory(subTags|last) : '' %}

                 {% if territory %}{{ territory }}{% endif %} ({{craft.i18n.getLocaleById(locale).nativeName }})

  {% endfor %}


texts:
My client has asked that I track and send campaign information through a contact form.

So basically a user might come to the site on this type of URL:

domain.com/?utm_source=Facebook&utm_medium=social&utm_campaign=paid16-03-2022

I can certainly get the query string information into a form (if they come directly to the form page) but if they go to multiple other pages and then fill in the form it gets a little more difficult to track.

My thinking was to:

Set a cookie to capture the query string variables when they come to the site
Put these cookie variables into a hidden contact form field/s  (if they go to this page)

I just wanted to double-check if this is the best way, if anyone had done this before or if there was a plugin or something else to help?


texts: Changing product type for products in Craft Commerce

texts:
At the moment there seems to be no UI / function for changing the product type for an existing product?

I see theres a typeId column in the products table. Would it be as simply to change this? Would this cause any issues elsewhere?


texts:
I am trying to build a query to fetch some entries which I want filter on a table field between multiple values. The table field is "filterTestWidth" and has 1 col named "size" (number type). There are multiple entries with multiple values in col1.

{% set items = craft.entries({
    "section": "catalog",
    "filterTestWidth": [
        "and",
        "> 180",
        "< 190"
    ]
}) %}

Unfortunate the Craft manual is limited on this subject. Does anyone know a more detailed article about element criteria?


texts: Can a User Group Create Drafts of New Entries Only?

texts:
I'm trying to set up a workflow where I have a group of "Drafters" who can create new entries but the new entry is not published by default. I've made the following setting for this group.

However, when I log in as a user within this group, the user is not allowed to create a new entry, even though their permission explicitly says they can create new entries. Am I missing something here?


texts: Is it possible to create a fieldtype that creates a many to many relationship between two entry sections?

texts:
So, for example:

Say I have two sections:

- Recipes
- Ingredients

Recipes can have many ingredients. Ingredients can have many recipes.

If I'm editing a Recipe, I can edit the ingredients. This updates the relationship so that when I edit ingredients it can show the associated recipes (and they are editable from the ingredients as well).

Is this possible with Craft?

Thanks!

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

Just to make this more clear. What I'm trying to do is create a Many to Many relationship between two Sections of Entries so there is an association between the two that works both ways.

Another example of this would be if you have a User with many Roles. I can manage which Users belong to which Roles from the Roles section, and/or I could manage which Roles a User belongs to from the Users section.


texts: How to extract static messages from templates into translation files?

texts:
I use Craft on multilingual site and I'm having some difficulty in getting the static messages on templates added or changed on every translation file I have.

Is there any way to extract those static messages changed or not already translated from templates into all translation files?

I'm looking for a functionality like of "yiic message" which searches for messages to be translated in the specified source files and compiles them into PHP arrays as message source.


texts: Get the Category name into the URL for an entry

texts:
I have a gallery which is categorised. The gallery is a Structure section where the user adds an entry and then assigns it to a category - all good.

At the moment, when clicking on an entry title the URL is mysite.com/gallery/entry-slug  but I would like it to be mysite.com/gallery/category-name/entry-slug.

I've looked around the Docs and StackExchange for a simple answer (assuming it would just be the addition of a tag) but the solutions seem very convoluted and way outside my grasp of understanding.

Any help appreciated

Thanks


texts: Plugin: Making a record's dateUpdated column update to CURRENT_TIMESTAMP

texts:
When creating a record in a plugin it automatically creates dataCreated and dataUpdated columns.  However, it doesn't look like the dataUpdated columns is updated on update.

Is there a way to set the dataUpdated column attribute to on update CURRENT_TIMESTAMP?

Or is that column manually updated in the background when using active record's update()?


texts: How to get Category URL from field in Matrix

texts:
This is my Matrix set up:

I'm stumped to how to get the Categories URL.

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

        {% case "galleriesItem" %}

                    {% for asset in block.image %}

                    {% endfor %}

                        {{ block.galleryType }}

    {% endswitch %}
{% endfor %}

I previously used:

{{ block.linkTo.first().url() }}

when the field type was an entry.


texts: Conditional logic to add class for specific section entries

texts:
I'm trying to create a conditional logic so that the class 'white-nav-bg' is added to the  element on the 'blog' section entries only.

Below is the code I'm currently using to try and achieve this with a logic tag but it is adding the 'white-nav-bg' class to all pages on the site rather than just the blog section entry pages.

<nav class="navbar navbar-default navbar-fixed-top
  {% for entry in craft.entries.section('blog').limit(1) %}
    {% if entry.type.handle == 'post' %}white-nav-bg{% endif %}
  {% endfor %}">

This code is in the '_layout.html' file, hence needing to figure out how to do conditional logic tags rather than adding the code differently in the blog template files.

After much time looking through Craft documentation I can't seem to find an example of how to do this. Any help would be gratefully received.

UPDATE:

Following helpful answers I have come to the following code, which works and allows me to define multiple sections to have the 'white-nav-bg' class.

{% set segment1 = craft.request.segment(1) %}
<nav class="navbar navbar-default navbar-fixed-top
  {% if segment1 == 'blog' %}
    white-nav-bg
  {% elseif segment1 == 'our-work' %}
    white-nav-bg
  {% endif %}">


texts: How to add a conditional elements into the title of a page?

texts:
I need to set the page title like this:

{% if entry.artistFirstName | length %}
    {{ entry.artistFirstName | capitalize }}
{% endif %}

{{ entry.title | capitalize }}

So if a first name is set I need to display it, but if not I only need to display the entry's title.

Here is one of the solutions I've tried but unfortunately does not work:

{% set title = {% if entry.artistFirstName | length %}
    {{ entry.artistFirstName | capitalize }}
{% endif %}

{{ entry.title | capitalize }} %}

It does not seem possible to define something in something that is being defined. Any idea how to get around this?


texts: Element API: Entry field inside a Channel entry being passed into JSON file

texts:
Hopefully my titles makes some sense but I will try to elaborate.

I have a Channel entry called Movies that I am using the Element API to turn into JSON. There is a field inside that called Movie Genre which is an Entry type field.

When I create this transformer:

'transformer' => function(EntryModel $movie) {

                return [
                    'name' => $movie->title,
                    'genres' => $movie->movieGenre[0]->title
                ];
            },

This is the JSON I get now, which looks to me like it is gathering all entries, not just the ones inside the channel.

  {"data":[{"name":"Harry Potter and The Order of the
  Phoenix","genres":"Fantasy"},{"name":"Jurassic
  World","genres":"Science
  Fiction"},{"name":"Romance","genres":null},{"name":"Science
  Fiction","genres":null},{"name":"Comedy","genres":null},
  {"name":"Fantasy","genres":null},{"name":"Guardians
  of the Galaxy","genres":"Action"},{"name":"Horror","genres":null},
  {"name":"Action","genres":null},{"name":"Home","genres":null},
  {"name":"Thirteen Ghosts","genres":"Horror"},
  {"name":"Movies","genres":null},{"name":"Genres","genres":null}],"meta":
  {"pagination":
  {"total":13,"count":13,"per_page":100,"current_page":1,"total_pages":1,"links":[]}}}

What I need to happen is only the Movies get returned as an item in the JSON and the movieGenre entry type not as its own item.

This is the desired JSON outcome.

  {"data":[{"name":"Harry Potter and The Order of the
  Phoenix","genres":"Fantasy"},{"name":"Jurassic
  World","genres":"Science Fiction"},{"name":"Guardians of the
  Galaxy","genres":"Action"},{"name":"Thirteen
  Ghosts","genres":"Horror"}],"meta":{"pagination":{"total":13,"count":13,"per_page":100,"current_page":1,"total_pages":1,"links":[]}}}


texts: .limit(1) on asset field loop is effecting another loop on same page

texts:
I have an Asset field where the first image is used as a big 'feature' and then the rest are used as support further down the page.

When I add .limit(1) to the for loop for the 'feature' image it effects the for loop further down the page by also only showing 1 image.

This is my code...

{% set entries = craft.entries.section('abstractionProjects').type('abstractionProjects').all() %}
{% for projectPanels in entries %}

    Some HTML...

    {% for asset in projectPanels.projectImages.limit(1) %}

    {% endfor %}

    Some HTML.....
    More HTML...

    {% for thumbs in projectPanels.projectImages.offset(1) %}

    {% endfor %}

    More HTML...

{% endfor %}

If I remove the .limit(1) from the first loop all the images are shown in both loops :/

Help appreciated

Thanks


texts: Got an "Oops" Screen While in Installer, Exited to Try Again, and Now I Can't Get Back to Installer

texts:
Background info: trying to install Craft CMS on a Vm running on Xubuntu

So, I was finally able to see the glorious monkey screen to signify that I'd made it to the installer successfully, when disaster struck soon afterward... I began the installation, enter my info, and ended up waiting on a very, very long "Oops" screen that just seemed to keep going and going. I looked up some resources about the install process while I waited and thought I'd done something wrong, so I exited the window to try again, because no "back" option was available. When I went to the URL again to reenter my info, I got a screen saying "Page Not Found: The requested URL was not found on this server." I did absolutely nothing after exiting the installer, checked to see that the file I was using in the URL is still where it should be, and restarting Apache (and then my VM) didn't help either, so now I'm stuck.

What should I do? Any and all advice will be very greatly appreciated. I can't find the answer anywhere I've looked!


texts: Reverse the seomatic title and site name for a specific template

texts:
Let's say my seomatic Site SEO Name = My Site and my Site SEO Title = A Wonderful Website

With the default values for seomatic's Site SEO Name Placement and Site SEO Name Separator, this will output the following title:

<title>A Wonderful Website | My Site</title>

This makes sense for the majority of pages on my site, where by setting a custom title for the page I'll get something like About Us | My Site

But on the homepage, I actually want to swap the order of these, so that the title becomes:

<title>My Site | A Wonderful Website</title>

This seems like a fairly common thing to do, but I can't seem to find a way to trick seomatic into allowing this without setting Site SEO Name Placement to None (which I don't want to do because the default value works well on all other pages).

Even trying to manually set the entire title won't work, because it will insist on adding the Site SEO Name to the end:

{% set seomaticMeta = seomaticMeta | merge({ seoTitle: 'My Site | A Wonderful Website' }) %}

Any way around this?


texts:
Forgive the simplicity of this question but I am in the early stages of my first Craft implementation.

My simple question is: how do I display a category name in a template. This is the code I am using:

{% for entry in craft.entries.find({section: 'blog', limit: '3'}) %}

{{ entry.blogCategory }}

        {{ entry.title }}

{% endfor %}

The error I am getting says "Object of class Craft\ElementCriteriaModel could not be converted to string"

Any help is appreciated.


texts:
I have created a new account and attempted to verify the account by clicking the activation link in the verification email.  On doing so I get the following error.

Bad Request
Param “id” doesn’t exist.

Any ideas how I can resolve this issue.

I am running the latest version of Craft.

I have replicated the issue locally and on our staging server.

Thanks in advance


texts:
I'm quite new to Craft. I was working on templates, then I logged in to create a new section and now any frontend route is returning a blank page.
500 Internal Server Error.

I restarted, Nginx, reboot Ubuntu server, etc.

Control Panel is working fine, I haven't touched any configuration file that I'm aware of.

Any idea what I did wrong?


texts:
We have a setup where we have a Contact Us page that submits a form using the plugin from P&T.
We will have quite some load on the site, so want to keep all of the GET responses in a CDN cache, CloudFront.

We have an issue where the CSRF token is of course cached in the page and so when the form is submitted by AJAX the token is invalid.

How do we ensure CSRF protection for the form and still have CDN caching enabled for the page?


texts:
Im looking up the last 2 entries like this

{% set entries = craft.entries.section('report').limit(2) %}

My entry got an assets field called 'portfolio'. I would like to retrieve 8 images in random order. How would I do this?


texts: Is there a way to to fire some code before user validation?

texts:
Am wondering if there is a way to fire some code prior to user validation being actioned? I have code running in a plugin that fire onBeforeSave but validation is actioned before this. So was wondering if there is a function that can be run onBeforeValidation specifically for users.

Cheers


texts: Can craft omit default locales from generated paths?

texts:
My bilingual site works fine, but it is not optimal from a url and SEO perspective because Craft is outputting duplicate content on different paths.

My default locale is en and the secondary locale is cy, this means many English pages can be reached by omitting the local from the path (which is the behaviour I want).

The problem is that certain pages craft generates via the {{ entry.url }} parameter contains the locale in the path even for the default one. i.e., Craft is spitting out paths like http://mysite.com/en/section/entry-title when I'd prefer it to be http://mysite.com/section/entry-title. It's actually accessible from both URLs, which is a bad thing for SEO. I only want the locale parameter added into the path when it's actually needed (i.e., for when we switch to cy).

Is this possible? If not, is there a work-around?


texts: Autogenerate complex Date / Count based Title

texts:
I might be pushing the limits of what's possible with Craft's autogenerated title capability, but in any event I'd like to figure out the best path to arrive at my goal.
We have an internal parts inventory with unique IDs assigned in the format YYYYMMDD-NNN. I'd like to recreate that same autogenerated format as we move our data to Craft.
Logically, the concept is "today's date plus the sequential ID incrementing for the parts recorded one that day". Each day, we start back at  '-001' (e.g., '20210305-001', '20210305-002',...).
I've tried the following code in Title Format autogeneration input, but either have the syntax messed up or am pushing beyond the capability of what's possible with autogenerating for a title field in craft.
{# Desired unique ID format = 'YYYYMMDD-NNN' #}
{% if not object.id %}
    {% set uniqueID = craft.entries.section('inventory')
    .order('postDate DESC')
    .first()
    .title %}
    {% set datePortion =  uniqueID | slice(0, 8) %} {# extract YYYYMMDD from string #}
    {% if datePortion == 'now'|date('Y-m-d') %}
        {% set count = uniqueID | slice(9, 3) %}
        {{ datePortion ~ '-' ~ count + 1 }} {# increment today's count for next part #}
    {% else %}
        {{ 'now'|date('Y-m-d') ~ '-001' }} {# first entry in a new day #}
    {% endif %}
{% else %}
    {{ object.title }}
{% endif %}

Hope someone has a more clever and elegant solution - thanks!


texts: How to create multisite in Craft CMS v3?

texts: I am looking to create multisite in Craft 3. Is there any way to create multisite in Craft?


texts: How do I add a new item or object to an existing object?

texts:
I'm using the Imager plugin and Craft for image compression.

Currently, I have something like this:

{% set imagerConfig = { jpegQuality: 80, pngCompressionLevel: 4 } %}

In another part of my code, I want to do something like:

 {% set largeLogo = craft.imager.transformImage((logo.getUrl('LargeLogo')), imagerConfig) %}

Where I want to do something like this to imagerConfig above:

{% set width = {width: 1000} %} or {%set widthRatio = {width: 1000, ratio: 4/2} %}
imagerConfig.Add(width) //what's the proper syntax for adding an item or even another object(like widthRatio above) to imagerConfig here?


texts: Using pagination on a page with url with query string data

texts:
I have an index page that filters entries based on url query strings, eg: site.com/inductees?county=123.

I put together a very simple pagination setup with next/prev links. However, when I click "next" I am brought to site.com/inductees/p2 and I lose my filtered set of entries from the ?county=123 bit.

How can I get pagination working and keep the query string in my url?

Thanks!


texts: How do I configure multiple environments for console commands?

texts:
I have built a plugin with some console commands for automating some regular tasks that will be run by a cron job for my site.

In order to get the commands working, I had to replicate my database configuration for the console environment in db.php.

All was well until I realized that each of my environments, local, staging and production will have unique database credentials, but there is only one console environment.

Is there a way I can force the yiic command to use a specific environment via a command line switch, either passing the domain name of an existing environment or additional additional arbitrarily named console environments?

Or is there another way to accomplish this so that the console environment has a unique configuration for each copy of the site?

For the time being I've been able to add an --environment switch to craft/app/etc/console/yiic.php which defines the CRAFT_ENVIRONMENT constant ahead of it defaulting to console, but this seems rather hacky and I'd hope there's a better way to do this.

// Existing switch check starting on line 18
if (isset($_SERVER['argv']))
{
    foreach ($argv as $key => $arg)
    {
        if (strpos($arg, '--configPath=') !== false)
        {
            $parts = explode('=', $arg);
            $frontConfigPath = rtrim($parts[1], '/').'/';
            unset($_SERVER['argv'][$key]);
            break;
        }

        // New environment switch added here
        if (strpos($arg, '--environment=') !== false)
        {
            $parts = explode('=', $arg);
            $environment = $parts[1];
            define('CRAFT_ENVIRONMENT', $environment);
            unset($_SERVER['argv'][$key]);
            break;
        }
        // end new environment switch
    }
}


texts: Show all discounts at checkout with Craft Commerce

texts: I've taken the difference between the actual price and sale price of items and created a variable to hold the total value to give me a total discount at my checkout. I am curious if there is a way to do this with less code though? If I try to show {{ cart.totalDiscount | currency(cart.currency) }} it just comes up as $0.00, and this is with promotions -> sales at 10% off for all products. If there is a simple snippet like the one I referenced I'd love to know about it. Thanks!


texts: How to get parent categories from an entry?

texts:
I have a pretty standard type entry page (_entry.html) which displays the details of an entry having navigated to it through 2 levels of categories. On this page I'd like to be able to query the two immediate category parents of this entry (sub-cat & cat) for use in a breadcrumb and page title variables.

I'm not sure how to approach this, or what the correct dot syntax is - I'm just getting up-to-speed with Craft CMS.

Any tips/references?


texts: "Invalid username or password" when registering and logging in a user

texts:
I'm having a really weird issue with user registration. I've got verification turned off, and logging in after activation turned on, so that when a user registers then checks out, it's a seamless flow. And this works. But the login form at /login does not. Whenever I try to create an account I get this in the logs:

$_POST=array (
  'action' => 'users/saveUser',
  'redirect' => '/confirm-account',
  'firstName' => 'Test',
  'lastName' => 'User',
  'email' => 'testuser9181@gmail.com',
  'password' => REDACTED,
)

$_SESSION=array (
  '8dfc5494412903b44af114111435fc5cYii.CWebUser.flash.error' => 'Invalid username or password.',
  '8dfc5494412903b44af114111435fc5cYii.CWebUser.flashcounters' =>
  array (
    'error' => 0,
  ),
)

Any idea what might be going on here? I have no idea what's causing this, and why it's working on one page and not the other. I can copy/paste the registration code from the checkout page and it will not work at /login. The same template is being extended.


texts:
In a custom plugin, I'm able to easily add a new Category:

$category = new CategoryModel();
$category->groupId = 1;
$category->getContent()->title = $categoryName;
craft()->categories->saveCategory($category);

That part works great! But for some reason, I can't figure out how to save a nested category.

I'd imagine it's something like this, but it doesn't seem to be working:

$childCategory = new CategoryModel();
$childCategory->groupId = 1;
$childCategory->level = 2;
$childCategory->parent = $parentCategory->id;
$childCategory->getContent()->title = $childCategoryName;
craft()->categories->saveCategory($childCategory);

Unfortunately that code is giving me an error:

  Internal Server Error

  Trying to get property of non-object

And if I drop the ->id portion of this line:

$childCategory->parent = $parentCategory;

... it will save the category, but it won't be nested.

What am I doing wrong?


texts:
I can see that normal caching can have it's storage specified, but I would specifically like to be able to set the caching storage method for the template tag {% cache %}.

At the moment it appears to be hitting our MySQL database very hard and so I would like to consider using something like Redis instead.


texts:
I'm using the craft contact form plugin and I am trying to format the sent email as html. I have added the following to the primary contact form plugin class:

public function init()
    {
        craft()->on('contactForm.onBeforeMessageCompile', function(Event $event) {
            $postedMessage = $event->params['postedMessage'];
            $event->messageFields = $postedMessage;

            $html = '';
            foreach ($event->messageFields as $field) {
                $html .= '<p>'.$field.'</p>';
            }

            $event->message = $html;
            $event->htmlMessage = $html;
        });
    }

Simply to format into paragraphs. The event is fired ok and the desired output is being created. However the plugin service does not seem to be picking up the the htmlMessage variable has been set.

Currently this sends the email as plain text showing the paragraphs in the text as per $event->message but even if I remove $event->message it still sends the default plain text message ignoring the html one has been set. Any ideas anyone?

Cheers


texts: Internal Server Error Regarding ElementHelper.php.bak

texts:
I am getting the following error on my local machine when updating Craft 2.6.

  /craft/app/helpers/ElementHelper.php.bak: failed to open stream: Permission denied

I don't even see that file in the directory.

Any ideas?


texts: entries related To category not working with getNext function

texts:
I currently have one entry in a page and would like to display next and previous arrows. The next/previous entries should be in the same section and related to the same category. To do this I have written this code:

{% set category = craft.categories.group('seasons').title(entry.season.title).first() %}
{% set arrowsParams = craft.entries.section('blog').relatedTo(category) %}
{% set nextEntry = entry.getNext(arrowParams) %}
{% set prevEntry = entry.getPrev(arrowParams) %}

For each entry I have added a field 'season' which maps to a category.

When retrieving the nextEntry, the relatedTo category is being neglected and an entry in a different category is being returned.

When I do

craft.entries.section('blog').relatedTo(category).first()

it works fine and actually retrieves the first entry in that category.

Am  I missing something? Could this be done?


texts:
The issue arises from inline three buttons (Viewer, Video, Photo) via CSS.

The idea was to make the buttons more responsive for example if I want to display just one button than stretch to 100% width within the parent. Two buttons (50% each) and three buttons (33.33% each).

I guess if I setup radio field and the values are displayOne, displayTwo and displayThree.

{% for option in entry.viewerOption %}

{% if option in entry.viewerOption.value.selected(displayOne) %}
Viewer
{% else %}
Photo
{% else %}
Video
{% endif %}

{% else %}

{% if option in entry.viewerOption.value.selected(displayTwo) %}
Viewer
Photo
Video
{% endif %}

{% else %}

{% if option in entry.viewerOption.value.selected(displayThree) %}
Viewer
Photo
Video
{% endif %}
{% endfor %}

I am not sure what is the best method to dynamically single, duel or triple buttons base on selected radio value.


texts: JQuery $.ajax ":success" form logic with Plugin Controller?

texts:
I'm working on a simple plugin to facilitate front-end, anonymous lead generation forms submitted to Salesforce via cURL to it's Web-to-Lead servlet. The logic and data transfer are working (debug showing positive receipt of the query from the servlet), but no matter what the :success function on the $.ajax call isn't triggered.

I'm getting a 200 OK back from the cURL, so my assumption is that the :error function is being triggered because the result isn't properly formatted JSON. I'm calling the returnJson function from the baseController, however all I can see in the response object is "responseText" with the raw HTML of the servlet response.

Controller PHP

protected $allowAnonymous = array('actionPostLead');

public function actionPostLead()
{
    $this->requireAjaxRequest();

    // Initialize the $kv array and query var for later use
    $kv = array();
    $query_string = '';

    //If there are POST variables
    if ($_POST) {

        // For each POST variable as $name_of_input_field =&amp;gt; $value_of_input_field
        foreach ($_POST as $key => $value) {

            // Set array element for each POST variable (ie. first_name=Arsham)
            $kv[] = stripslashes($key).'='.stripslashes($value);
        }

        // Create a query string with join function separted by &amp;amp;
        $query_string = join('&', $kv);
    }

    // Check to see if cURL is installed ...
    if (!function_exists('curl_init')) {
        die('Sorry cURL is not installed!');
    }

    // The original form action URL from Step 2 :)
    $url = 'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';

    // Open cURL connection
    $ch = curl_init();

    // Set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, count($kv));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);

    // Execute SalesForce web to lead PHP cURL
    $result = curl_exec($ch);

    // close cURL connection
    curl_close($ch);

    if ($result) {
        $this->returnJson(array('success' => true));
    } else {
        $this->returnErrorJson($e->getMessage());
    }
}

Javascript

$.ajax({
    type: 'POST',
    url: '/',
    data: data,
    dataType: 'json',
    success: function(response) {

        formBlock.removeClass('submitting');
        var successMessage = $('.formBlock.on').data('success-message');
        showFormSuccessBanner(successMessage);
        hideForm(id);
    },
    error: function(err) {
        console.log("Error");
        console.log(err);

        formBlock.removeClass('submitting');
    }
});

I think I'm close, but I've been digging for several hours and can't figure out what I'm doing wrong with the response.


texts: Activation Email for Pending User Doesn't Work

texts:
User account is "pending"
verificationCode is created in database, and erases when visiting the hyperlink.
I'm able to successfully produce an activation email using the code below:

Code:

$user = craft()->users->getUserByEmail($emailAddress);

if ($user->getStatus() != "active")
{
    craft()->users->sendActivationEmail($user);

I'm redirected to the page set for activateAccountSuccessPath in config/general.php which an account edit page.
I'm "sort of" half logged in... able to see the email address for my account filled in the edit profile form, but the CMS otherwise does not recognize me as logged in.

Any ideas?


texts: How to set the value of a Date field from PHP?

texts:
I'd like to set the value of a Date field from my custom PHP code.
How can this be made? Which format does the Date field expect when using the setValue() function?


texts: How can I manually update the URI of an entry?

texts:
Is there a way to manually change the URI for an entry?
for instance where is this stored in the database (is it?)

I need to update one that is: /vacancies  to /vacancies-1444 for example
the 1444 never got added to the URI when created by an API entry creation and /vacancies is the root of a list of vacancies.


texts:
I'm in the midst of setting up a bilingual website. English and Welsh.

I have set up the locales in my settings (en and cy_gb)

My directories have the necessary folders for each language, with each containing their respective index.php and htaccess files.

Craft's general config file is changed. Basically I have followed the steps in the Craft docs. My site loads and clicking links loads them fine, but when I add a cy to the URL, I get a Craft 404 page

Is there anything I maybe missing? Do I need to add something to the templates themselves? Any help would be appreciated.

General config

return array(
// Base site URL
'siteUrl' => array(
    'en' => 'https://site.domain.net/',
    'cy_gb' => 'https://site.domain.net/cy/'

),

/cy_gb/index.php

// Path to your craft/ folder
$craftPath = '../../craft';

//Tell Craft to serve the Welsh content
define('CRAFT_LOCALE', 'cy_gb');

/en/index.php

// Path to your craft/ folder
$craftPath = '../../craft';

//Tell Craft to serve the English content
define('CRAFT_LOCALE', 'en');


texts: How do I get get clean URLs in twig templates

texts:
When I use {{page.link}} or {{page.url}} in a template I am getting

http://mysite.dev/index.php?p=pages/about/history

when what I really want is

http://mysite.dev/pages/about/history

The latter URL works fine on the site, but I'm using the above code to try and create a menu, and don't want the menu item linking to the first URL.

How do I fix this?


texts: Restrict Sources on element select field

texts:
I'm building a module with a form that includes an element select field that I want to restrict to specific volume. So far this is what I have:

{{ forms.elementSelectField({
    label: "Asset"|t('app'),
    id: 'images',
    name: 'images',
    elementType: 'craft\\elements\\Asset',
    selectionLabel: "Choose"|t('app'),
    criteria: {
        kind: ['images']
    },
}) }}

I can see there is a 'sources' attribute, but I don't know how to structure the value. I've tried:

sources:[1] and the handle sources:['images'] without luck.


texts: Freeform plugin unique submission amount

texts:
I'm needing to get the unique entry submission amount for a value.

Example:
Item1, Item2, Item1, Item3, Item1

Would return:
3

I was able to use the workaround here Search/Filter Freeform submissions by field value to get the specific submission amount but only wanting to know the number of unique submission values.

Can anyone help?


texts:
I have two structures: Focus Areas & Initiatives.

I'd like to be able to associate the two of these structures. Here's a potential example:

Focus Areas:

Sports
Music
Art

Initiatives:

Basketball
Soccer
Trumpet
Painting

My organization has a number of Initiatives, each fit under a certain Focus Area.

On each Focus Area page, I would like to show all Initiatives associated. Currently, for each Initiative, I have a Radio Button for each Focus Area it fits under, but am having trouble thinking of how to further narrow down entries to show from the example below (which shows all initiatives):

{% set entries = craft.entries.section('initiatives') %}
{% for entry in entries %}
    {{entry.title}}
{% endfor %}

Would this be an appropriate use case for Categories? Should I instead be using Entry Types for each Focus area?


texts: In the CP there is a button which allows you to log in as a specific user. Can this be called from the Frontend/plugin or is it strictly a CP function?


texts: Ordering/sorting products by their variant stock level

texts:
I'm trying to implement a sort order in my product listings so that all of the out of stock products are last.

I'm unsure how or if this is possible because the stock is set on the variants of a product and I'm listing the products.

The stock level would need to take into account the stock of all the products variants.

I know we have the ability to only fetch products that have stock with the criteria hasVariant: { hasStock: true }, but is there a way I can sort them using the .order() criteria?


texts: Image transforms returning cpresources url

texts:
I'm trying to get Craft to render an image transform defined in the control panel. No image is added to the "filelocation/_transformhandle" folder and returns the url "/cpresources/transforms/98" where 98 is the transform index.

I have tried clearing the cache and db table already as well as updating the asset index. I have double checked the sources paths and it is not a file permission issue.

Code example as a matrix block:

{% elseif block.type == "slideShow" %}
{% if block.galleryImages|length>0 %}

{% for image in block.galleryImages %}
    {{ image.aboutText }}
    <img src="{{ image.getUrl('galleryHorizontal') }}">
{% endfor %}
{% endif %}

I tried using the other methods on this page in the docs with the same result. http://buildwithcraft.com/docs/templating/assetfilemodel

Thanks!


texts: Can I set the same relation in a field multiple times?

texts:
My customer wants a videoplaylist for users.

Idealy I'd like to have a assets relation field for the playlist and relate all the videos in said playlist.

The problem is if a user wants the same video several times in the playlist.
( like in a loop ).

As far as I know it's only possible to relate an entry/asset once in the same relation field.

The solution for me would be to add a matrix-block for each video in the playlist, but since there are thousands of playlists the db grows way more than expected.

Without matrix field: around 30MB
With matrix blocks: around 200MB.

The site slowed down quite a bit and the searchindex table grew to about 80MB.

Is there another way to implement this or a ideally a way to relate an entry several time in one field?


texts: Hi guys does anyone know how I might go about creating a dynamic navigation using a global with the navigation items as fields, is this even possible?


texts: Section permissions are ignored when linking to an entry

texts:
Users with permissions to limited sections can still “link to an entry” in any section from within the WYSIWYG (Redactor) editor.  I'm using Craft 2 with a Rich Text (Redactor) field.

Is this a bug or is there a way to fix this?

Here's some screenshots of the flow of what I'm talking about:


texts: Non-numeric characters in number field producing errors

texts:
Craft 3 is giving me this error when my client enters non-numeric characters into a number field on an entry:

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

Is there a way for it to check and remove non-numeric characters from the field on save? Or maybe my setup is incorrect?