texts:
I am trying to get results from a relatedTo query, but only if there are more than say 1 results. Right now I am using two queries to achieve this, like so:

{% set authors = craft.entries({
    section: 'authors',
    with: [
        'authorImage',
    ],
    limit: 18,
    order: 'authorSurname asc'
}) %}
{% for author in authors %}
    {% set relatedEntries = craft.entries.section('articles').sponsoredAuthor('= 0').relatedTo(author) %}
    {% if relatedEntries|length > 1 %} ... {% endif %}
{% endfor %}

But this messes up pagination (amongst other things) because the loop will iterate no mater if the related entries have more than 1 result. So I was wondering if it is possible (without using a custom query) to have the same result as a single query, so that the results match the number of the items in the loop and pagination does not break. Something like:

authors = craft.entries.section('authors').relatedTo('articles where articles results > 1)

or something like that. Is it possible?

Thanks!


texts: Checking for existence of a field within a Matrix block

texts:
In trying to test for the existence of a field within a Matrix block I think I may have stumbled upon a bug, or I'm missing something and approaching this the wrong way.

I've setup a simple test using a fresh, standard Craft install with a very basic Matrix setup. I've pasted the Matrix template code below.

    {% if entry.matrix is defined and entry.matrix|length %}

        {% for block in entry.matrix %}

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

                {{ block.richText }}

            {% elseif block.type == "plainText" %}

                {{ block.plainText|markdown }}

            {% elseif block.type == "blockquote" %}

                {% if block.test is defined %}

Uh oh! This field doesn't actually exist.

                {% endif %}

{{ block.quote }}

                    – {{ block.attribution }}

            {% endif %}

        {% endfor %}

    {% endif %}

Within the blockquote block I am checking if block.test is defined, this check always evaluates to true despite the fact that it doesn't exist and if I add any additional checks it bombs out the template.

Any insight is greatly appreciated!


texts: Mailer config in Craft 3 not getting merged

texts:
I have this custom config in config/app.php,
but Craft seems to keep using the default Control panel Sendmail config.

It seems this doesn't get merged in the main.php file. (as promised)

 return [
 'components' => [
     'mailer' => function() {

        // Get the stored email settings
        $settings = Craft::$app->systemSettings->getEmailSettings();

        // Override the transport adapter class
        $settings->transportType = craft\mail\transportadapters\Smtp::class;

        // Override the transport adapter settings
        $settings->transportSettings = [
            'host' => 'xx',
            'port' => 'xx',
            'useAuthentication' => true,
            'username' => 'xx',
            'password' => 'xx'
        ];

        return craft\helpers\MailerHelper::createMailer($settings);
     },
 ],

];


texts: Is it possible to convert plain text array to an unordered list?

texts:
I have a front end form with checkboxes which submits the data as an array into a plain text field in craft (named logGeneral_logInputIndications).

Here's an example of what the content looks in the plain text field in Craft CP:

["Abdominal Pain","RUQ","Vomiting",""]

Instead of outputting the field content in it's default state into my template, I'd like to convert it to an unordered list.  If I were to code it by hand it would look like this:

Abdominal Pain

RUQ

Vomiting

Any ideas if it's possible to do this?

(Mats answered the above question and his suggestion worked perfectly.)

However, I just realized that I have checkbox choices that contain non-alphanumeric content like Normal CBD (<0.4cm)  Is there a way to pick and choose which non-alphanumeric content I'd like to strip out vs keep?

Here's a new question that builds upon my initial one...

Is it possible to add a conditional to this?  Some of the text is really a child so it should be inset by another unordered list.  What my initial thought was is that perhaps I could add an identifier to the form input text if it's a child like "•" or something else, and then in the template, use that identifier in a conditional to say if you see "•" indent it and then strip the marker "•".

So then my plain text content would be:

["Abdominal Pain","•RUQ","Vomiting",""]

And my template code would look like this:

Abdominal Pain

RUQ

Vomiting

I was able to combine the suggestion Mats gave me with the following to conditionally indent child items.

{% set listItems = entry.logGeneral_logInputIndications|replace('/[^,()<>• a-zA-Z0-9_-]|[, ]$/s','')|split(',') %}

    {% if entry.logGeneral_logInputIndications|length %}
        {% for listItem in listItems %}
            {% if listItem starts with '•' %}

{{ listItem|trim|slice(1) }}

            {% else %}

{{ listItem|trim }}

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


texts: Error accessing entry when title has special characters

texts:
I came across a weird bug with a title containing a "%" character not converting into a proper slug. So the website editor created the title "Berlenga: a 100% sustainable island" that didn't get turned into a proper slug. It generated the slug exactly as the title. When she went to make changes, Craft threw in a bad request error.
I was able to edit the slug inside the database and she got back access the entry, but I am wondering if there is a way to prevent this from happening again. I'm using the "Slug Equals Title" plugin, which works greatly for localised entries, and I did activate "limitAutoSlugsToAscii". Is there something else I need to do?
Thanks!


texts: Freeform: query form object for presence of field type (or other criterion)

texts:
I want to be able to check if a form object returned by a query has fields of a certain scope before I generate its markup.
I have a test case where I want to know if a form has a checkbox field type in it, but I can't figure out how to query just the fields in the form with something like:
{% set hasCheckbox = form.fields.type('checkbox').one() ?? null %}

I know that doesn't work, so I've got a workaround, but it would be good to know if this kind of thing is possible.

My workaround is to do something like:
{% set hasCheckbox = false %}
{% set formMarkup  = [] %}

{% for row in form %}
    {% for field in row %}
        {% set fieldMarkup %}
            {# Do stuff #}
        {% endset %}

        {% if field.type == 'checkbox' %}
            {% set hasCheckbox = true %}
        {% endif %}

        {% set formMarkup = formMarkup|merge([fieldMarkup])" %}
    {% endfor %}
{% endfor %}

{# Do something with hasCheckbox #}
{# Output formMarkup #}


texts: Craft 3 Image Editor / Redactor - Remove?

texts:
TL;DR
Can the button for "Image Editor" be removed from Redactor in Craft 3?

I've looked around the Craft docs and web, but I can't find a way to remove the button that appears within the Redactor when an image is clicked.

At first glance it seems like Redactor's imageEditable config should just be set to false, but unfortunately that only removes a small amount of features in the "edit" modal, not "Image editor" button itself [below].
https://imperavi.com/redactor/docs/settings/image/#s-imageeditable

Has anyone tried to remove option for Image Editor before? Is this even possible?


texts: Removing index.php causes Not Found error on secondary pages

texts:
I'm moving an existing site to the new server and spent a couple of days trying to make this work.

Home page of the site loads just fine. Other pages load too if I add /index.php/ to the url. Otherwise I get 'Not Found' error.

Have gone through all the suggestions here: https://craftcms.com/support/remove-index.php, here: https://craftcms.com/support/why-index.php, and here: https://craftcms.com/support/enable-path-info. Everything checks out.

My .htaccess in /public_html:

<IfModule mod_rewrite.c>
   RewriteEngine On

   # 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>

I'm on a clean install of Apache server. Made sure I have all the required extensions and config matches suggestions on the Craft site.


texts: Can I get Assets from a specific Matrix block?

texts:
When they exist, I'd like to get specification PDFs from a product entry. They're stored in a productInfo Matrix field, in a specifications block that has a downloads Assets collection.
Naturally I attempted the following...
{% set specFiles = entry.productInfo.specifications.downloads %}
{% for specFile in specFiles %}
    {{ specFile.title }}
{% endfor %}

...and Craft thought I was being greedy:

Internal Server Error
Craft\ElementCriteriaModel and its behaviors do not have a method or closure named "specifications".

I noticed in this SE question that examples skipped referencing the block type and went straight for the field name, so I tried that next...
{% set specificationDownloads = entry.productInfo.downloads %}
{% for specFile in specificationDownloads %}
    {{ specFile.title }}
{% endfor %}

This didn't throw any error, but it didn't return any results either.
I know that I can loop through the blocks and then the downloads, it just seems excessive...
{% for block in entry.productInfo %}
    {% if block.type == 'specifications' %}
        {% for specFile in block.downloads %}
            {{ specFile.title }}
        {% endfor %}
    {% endif %}
{% endfor %}

So what is the most straightforward way to get results when I want to limit them to a specific (Assets) field within a certain Matrix block type?


texts: How do I access a specific element of a supersorted array?

texts:
Let's say we have this setup:
{% set myArray = [9,3,5,7,2,1] %}
{% set mySortedArray = myArray | supersort() %}

It gives us:
myArray = array(6) {
    [0]=int(9)
    [1]=int(3)
    [2]=int(5)
    [3]=int(7)
    [4]=int(2)
    [5]=int(1)
}

mySortedArray = array(6) {
    [5]=int(1)
    [4]=int(2)
    [1]=int(3)
    [2]=int(5)
    [3]=int(7)
    [0]=int(9)
}

How can I access say the second element of mySortedArray?
If I do {{ mySortedArray[2] }} I get 5, but I want the 3.


texts: AJAX CSRF Producing Inconsistent Results

texts:
I am using CSRF tokens in a form on CraftCMS. Submissions are successful with a standard configuration.

Introducing "fresh" CSRF tokens via AJAX on page load is causing some trouble. This is necessary as production has caching.

Here are some observations:

Disabling CSRF validation in config/general.php resolves the issue entirely; however, of course, this is not the solution.
Disabling CSRF cookies does not resolve the issue.
Failed attempts appear most commonly in iOS on Safari. It also occurs sometimes on Edge. It appears to work always in Chrome.
Regarding Safari: one idea here was that the browser disrespects Cache-Control and thinks it should be caching this request, hence resulting in a failed CSRF validation. Adding in a timestamp to the request in a query string did not resolve the issue.
Failed attempts result in a "400 Bad Request" response. The body sometimes reads: Bad Request: Unable to verify your data submission.
Failed attempts occur regardless of server side caching. This has been tested on local environments (Homestead) with no non-standard caching configurations.
The token returned on the CSRF AJAX request is different each time.
The form is built with FreeForm, but I do not think that is of significance.

Questions:

How does one track the request further to find the reason for failure?
Is providing CSRF tokens via an AJAX request sensible? The typical response I see is adding in the token via an inline Javascript variable. (Read) That route is not an option here.

Any pointers here would be very appreciated. Thanks in advanced!


texts: Specify a field dynamically using section handle

texts:
I'm using a single template to display entries from several structures. Each structure has a cooresponding global field that is an entries field. I use this to display related entries as a sidebar. These fields are named sidebars.[structure handle]Sidebar, so fore example my blog sidebar global field would be sidebar.blogSidebar.

Coding the sidebar manually works fine, like this:

{% for block in sidebars.blogSidebar %}
    ...
{% endfor %}

But I'm trying to dynamically set the related entries field, and it isn't working:

{% set sidebar = "sidebars." ~ entry.section.handle ~"Sidebar" %}
{% for block in sidebar %}
    ...
{% endfor %}

This code doesn't output anything. If i just output {{ sidebar }}, it shows what I expect, ex: sidebars.blogSidebar.

And if I manually add it to the for loop {% for block in sidebars.blogSidebar %}, it works as expected.

Is there a different way to concatenate the name to make this work?


texts:
Is there a way to delete specific tags from the db? I have one tag that does not seem to work. I have used the following code to see all tags used from a specific section, knowing I have entries using a tag called Logos

{% set test = craft.entries.section('projects').limit(null) %}

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

{{ tag.title }}

    {% endfor %}

This outputs a list of all tags used in the section called projects, Logos is not listed.

I have a sidebar that outputs each tag a single entry was assigned. Logos is output when viewing an entry that was tagged with Logos. Clicking on the Logos link loads a page that should list all entries that use Logos etc but for this specific tag it doesn't find any entries. I have a feeling this tag is corrupt somehow in the db as this was working fine a while back.

I noticed someone had duplicated this tag... if I start typing Logos in the Add a tag when editing an entry I see four results Logo, Logo, logos, Logos.

Neither logos, or Logos returns entries. And only one of the Logo returns entries.

I then decided to add all of those Logo, Logo, logos, Logos. And renamed the three that didn't work to blank. This then causes the tag to display as "Tag 686" etc. Clicking the tag then loads all of the entries using that tag. So for some reason it just doesn't seem to like the tag being named Logos...

Anyone have any ideas on what could be going on here?


texts:
I have created a global menu for my website and there I have a label and an entry section selection that I use for directing when clicking.

However, I just need the URL of that section and loading the whole section data is way too much overhead that its not needed.

I have 4-5 menu items so I am loading 4-5 sections for no reason.  Imagine the overhead.

Can I somehow use the section selector in CMS but get only the section URL without loading all the section data?


texts: Can I downgrade my craft version from Client to Personal using the CP?

texts: I have already downgraded from Craft PRO to Craft Client and am wondering if I can downgrade again from Craft Client to Craft Personal as the project I'm working on does not need anything more.


texts: I have an entry that is currently password protected and I am looking for a way to give access to this entry to non-craft users temporarily access either by a token or something else. Anyone know how I can accomplish this?


texts: Matrix block Element API call on null error

texts:
I get this JSON error when trying to output content of a matrix block called proLinks using the Element API.

  Call to a member function all() on null

The code is as follows (I've shortened it and removed the other content, this is the only one that I can't get to work):

<?php

use craft\elements\Entry;

return [
  'endpoints' => [
    'discproj.json' => function() {
      return [
        'elementType' => Entry::class,
        'criteria' => ['section' => 'dPs'],
        'transformer' => function(Entry $entry) {

          $linkBlocks = [];
          foreach ($entry->proLinks->all() as $block) {
            switch ($block->type->handle) {
              case 'external':
              $linkBlocks[] = [
                'externalTitle' => $block->externalTitle,
                'externalLink' => $block->externalLink,
              ];
              break;
            }
          }

          return [
            'projectLinks' => $linkBlocks,
          ];
        },
      ];
    },
  ]
];

I've looked at the other questions about this here, and they all seem to do things a little bit different from each other. I think I have the general structure, but there is obviously something missing.


texts: How to fetch only selected child category?

texts:
I have some parent and their child categories which has more than one child.

In an entry I have a category field where I selected a single child category (Bourbon) which is visible like so:

Now I want to show the title and URL of the only selected single child category which is Bourbon.


texts:
How can I log in a user in Craft 3 and redirect to a url?

This doesn't work:

$username = $user->username;
$userCode = $user->teamCode;
Craft::$app->user->login($username, $userCode);

Thanks!


texts: Best Practice for Templating-Workflow, coming from static HTML

texts:
I hope this question does not sound to banal:
I am currently switching to Craft CMS and I am used to build my HTML/CSS/JS templates as static pages with dummy content.

This (seemingly?) has 3 advantages for me:

I have an early, clickable prototype, presentable to the client
before I have to touch any CMS
I am not forced to insert real content via the CMS yet
It gives me a very clean Git Repository for the frontend without any
CMS dependencies yet

The disadvantage is of course that I have to manually split my static pages up later to work with Craft CMS (or any other CMS) templating logic.

Thus I was wondering how you approach templating, especially with Craft: Whether you start directly building your frontend from scratch in Craft’s Templates folder or if you start independently, and do the splitting of files every time as a necessary step …

Any suggestions?


texts: Where to put where() for a query looking for a lightswitch field

texts:
Struggling with syntax here. I'm trying to query entries in the "resources" section, ordered by postDate desc, limit 1 and that also has the lightswitch "featured" as true. Here is what I have.

        {% set featuredEntry = craft.entries({
            section:            'resources',
            orderBy:            'postDate desc',
            limit:              1,
            where:              {'featured': 1},

        }) %}

Also to note I'm on craft 3.


texts: How to send email from Craft 3 custom plugin?

texts: I have created custom plugin in Craft 3 and want send email to receiver or site email when user submits a form.


texts: Getting previous order history in a Commerce 2 adjuster

texts:
I am trying to write a Commerce 2 adjuster that will apply a discount on all items from a specific type if a customer bought a specific item with another product type in the last year as well as a minimum price.

It's my first attempt and I'm already stuck trying to retrieve the order history from a specific user.  I can't find anything in the Commerce 2 docs. That's what I have so far. Please be gentle :-)

<?php
namespace craft\commerce\adjusters;

use Craft;
use craft\commerce\base\AdjusterInterface;
use craft\commerce\elements\Order;
use craft\commerce\models\OrderAdjustment;

class FriendDiscount implements AdjusterInterface
{

    // get the current user and check if the discount condition is true
    public function checkIfDonated()
    {
        $user = Craft::$app->getUser();
        if ($user) {
            // check if user bought line item with product type 'typeA' in the last 365 days and spent at least 100$ on it, then return true
            return true;
        }
        return [];
    }

    public function adjust(Order $order): array
    {

        $friendAdjuster = new OrderAdjustment();

        // apply discount if checkIfDonated() returned true
        if ($this->checkIfDonated() == true) {
            // apply discount only on items with the product type 'typeB'
            $friendAdjuster->type = "Discount";
            $friendAdjuster->name = "-14$ Off";
            $friendAdjuster->description = "-14$";
            $friendAdjuster->amount = -14;
            $friendAdjuster->orderId = $order->id;
            return [$friendAdjuster];
        }
        return [];

    }

}


texts:
I have two channels, Courses and Instructors. In Courses I'd like to have a an entries field called "Instructor" so that this will display on the courses page.

I can't seem to figure out how to do this. I have found a few tutes but nothing I have tried has worked. Whats the best way of doing this?


texts: Incorporating data from an external database into Craft pages

texts:
I'm looking at how best to incorporate various sets of data from another MySQL database into a Craft site. Using the Feed Me plugin would be one way, if the data source had feeds, but I'm thinking about alternatives. Does this make sense:

There is an Entry whose page should display data from the external DB.
The admin user can, using standard Fields, select the criteria for which data it is (eg, category, number of items, timespan, etc).
In the Entry's template, a template hook calls a Craft plugin.
The plugin makes a request to the external DB, tidies the returned data, and renders it into the page with a twig template.

Does that make sense? Anything that sounds impossible or stupid? Can you think of a better solution?

It looks like I could cache that part of the template so that it didn't make requests to the external DB with every page request. Is that right?

(For context: I haven't used hooks yet, and have only written the most basic of Craft plugins. I have years of general PHP experience, but little with Craft or Yii.)


texts:
I'm trying to find documentation on how the queue system works, and what parts of craft relies on it. To my current understanding, the queue is normally executed when users are logged in to admin, and search indexes are updated via queue?
Also, I use webhooks, which seems to be executed the same way.
Publishing pending posts though, doesn't seem to use the queue?
I don't have any queue/listen task running, but since I'm running a dockerized version I could run a parallel container which just invokes craft queue/listen if needed, would that be favorable, and then I would disable the runQueueAutomatically setting I assume?
Since I'm also running this in AWS, I have the option to run the queue via SQS, what would be the benefits of that? I assume the default queue is just stored in the database, but I assume it is doing some sort of locking to prevent multiple executions, if I would have multiple queue daemons running. So only real benefit would then be, that the information isn't stored in database (thus, not part of backups for instance), because the load on the database seems abysmal for any normal scenario.


texts:
I'm trying to figure what would be the simplest way to do such filtering:

I would like to make it in that way that selecting one of "Specialities" category would limit results from the selected "Plant" category.

Though I want a selection of the second category to be optional, so everyone can browse live and dried i.e. Mint plants or only herbs from all plants if they want.

Also, I would like to implement shipping to/from drop-downs with the same functionality.

Expected result:

How can I start? Any help would be greatly appreciated :-) Thank you.


texts: Using the Charge plugin to store customer credit card info, how to re-validate the credit card when customer submits order

texts:
We able to use charge plugin to store customer credit information as "Customers" in Stripe, however, "Customers" information might be saved awhile ago, we would like to re-verify the credit card information is still valid when the customer submits an order. Does anyone know how to do it?

Thanks


texts: Implementing two factor authentication / TOTP for CP logins

texts:
We have a client with fairly extensive security requirements. They have asked us if it is feasible to implement something like Authy in Craft.

I'm provisionally planning to disable the "normal" CP login form and implementing a new login flow via a plugin that checks the OTP first and then hands off to UserSessionService for the actual login. Is there any reason that wouldn't work?

If it will, what's best way to effectively disable the default CP form and direct users to the plugin's form instead?

Lastly, are there any gotchas that I should look out for in terms of maintaining as close to "normal" Craft behaviour as possible.

PS I know there's the userSession.onBeforeLogin event, but unless I'm missing something, that looks fairly limited (only receives the username of the User as a param etc)


texts:
I'm new to Craft CMS and can't figure out how to link images with the code below to its own page. Any suggestions?

{% for asset in entry.mainImages %}

{% endfor %}


texts: Showing Reverse Relationships in CP | Products  Categories

texts:
My clients would like to be able to see what products (Artworks) are added to a category (Collection), and vice versa in the CP.
Relating on the front end is fine, but on the backend there seems like no obvious way.
Craft support have indicated that it would involve 'Product::EVENT_AFTER_SAVE event to take the selected categories and create the relation on each of the category's custom product field.' but I'm not sure what would be involved to implement this.
Has anyone solved this need? Or is there a plugin that solves it?


texts: How to install Craft on live server parallel to existing CMS?

texts:
I'm in the process of migrating a large, complex site to Craft.

I've reached the stage where I like to install Craft in parallel to my existing CMS with the intention of allowing users to help me check the content is migrated correctly.

It's also with a view to keep parts of the existing site in the current CMS and migrate them later.

Do you have advice on how to best do this? How would I redirect requests for different parts of the site to the correct CMS?


texts: 404 message after following Craft installation instructions

texts:
I'm installing Craft CMS on my domain which was formerly functional (previously used Wordpress). I removed all Wordpress files through FileZilla FTP and uploaded Craft files.
I put the /Craft folder in its entirety above the root.
I put the files in /Public in the Public_html folder.
I set up a new Database through my hosting provider and edited the db.php file with the credentials.
Now when I go to mydomain/admin I get an Apache 404: "Apache/2.4.10 (Debian) Server at chrislee.is Port 80"
I've triple checked the installation instructions given on the Craft site and can't see any mistakes. Any ideas about what may have gone wrong would be greatly appreciated!


texts:
This may be a silly question or a pipe dream, but i was wondering if there is a way to have a live preview for entries without a URL. For instance i have a complicated layered slider on the homepage of a site I am building and due to it's complexity it can not simply be a field or series of fields on the homepage entry, thus i've simply created a channel called 'slides' and I include that in my homepage template.

It'd be really great if there was someway to allow live-preview to show the slides while editing, or allow editing of them while in live-preview of the homepage.

Does this capability exist or am I out of luck?


texts: How do I create console commands for my module or plugin?

texts:
I would like to create a custom console command for my Craft 3 plugin. I've looked at the Yii docs and understand commands are defined using controllers extending \yii\console\Controller but cannot work out how these controllers should be registered with the application.

To register site routes in Craft 3, we listen for the UrlManager::EVENT_REGISTER_SITE_URL_RULES event and then define rules. What's the equivalent for registering console commands?

Thanks


texts:
I've tested the webhooks plugin. Awesome. Works brilliantly.

How how about incoming webhooks? What if my 3rd party ERP system has changes that it wants to put into my Craft site. How do I go about getting the changes into Craft?


texts: What's the proper way to create a plugin that uses and extends another author’s plugin?

texts:
I’m creating a plugin that will ultimately create new entries using the Moves API (https://dev.moves-app.com). The Moves API needs OAuth make authenticated calls on a user's account, so I'm using Dukt's OAuth plugin (https://dukt.net/craft/oauth) to handle the OAuth authentication process.

I actually have it up and running, but to create an Oauth provider that isn't supported natively by Dukt's plugin, I've added files to their folders.

Here’s what I’ve done.

Created a Moves.php file in the craft/plugins/oauth/vendor/chrisnharvey/oauth/src/Oauth/Provider/ folder that sets up the necessary info to communicate w/ the Moves API - Link to source: https://gist.github.com/bwlng/2cb486c8d83001deae19#file-moves-php
Created a MovesOAuthProviderSource.php file in the craft/plugins/oauth/vendor/chrisnharvey/oauth/providers/folder that echoes the other providers Dukt supports out of the box. Link to source: https://gist.github.com/bwlng/2cb486c8d83001deae19#file-movesoauthprovidersource-php

Is there a better way to do this? Ideally want to require the Dukt plugin be installed, and then keep the code I've linked to above in my own folder in craft/plugins/moves.


texts: How can I populate a drop-down on the front-end using Sprout Forms?

texts:
I have a contact form where I can choose the current state (U.S states).
I have the field created in Sprout forms as "state" and is populated with all 50 states.

I would like to use "custom" html and loop through the values of that field. I just can't figure out how to get to it.

I know I can output the whole field/element using:

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

But that outputs a whole html element. I only want the options so I can loop over them like this:

....
<select>
    <option value="">Select</option>
    {% set states = form.getField('contact.state') %}
        {% for option in states %}
            <option value="{{ option.value }}">{{ option.label }}</option>
        {% endfor %}
....
</select>


texts: Craft can't connect to db.php on live server

texts:
My Craft files are structured correctly, I have the Craft file level with the public_html file on the server (which contains the index.php file), within index.php I have set my $craftpath correctly to $craftPath = '../craft';.

But when I go to my live url I get a Craft styled error of:

Service Unavailable
Our site is temporarily unavailable. Please try again later.

When I try to reach my admin I get an error of:

Error error
Craft can’t connect to the database with the credentials in craft/config/db.php.

If it helps, my general.php file looks like this:

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

    // development
    'example.dev' => array(
        'environmentVariables' => array(
            'devMode' => true,
            'siteUrl'  => 'http://example.dev/',
            'assetPath' => 'http://example.dev/assets/'
        )
    ),

    // production
    'example.com' => array(
        'environmentVariables' => array(
            'devMode' => false,
            'siteUrl'  => 'http://example.com/',
            'assetPath' => 'http://example.com/assets/'
        )
    )
);

And the db.php file is as such:

return array(
    '*' => array (
        'tablePrefix' => 'craft',
    ),
    'example.dev' => array (
        'server' => 'localhost',
        'user' => 'root',
        'password' => 'root',
        'database' => 'localdatabase',
    ),
    'example.com' => array (
        'cooldownDuration' => 0,
        'server' => 'server',
        'user' => 'user',
        'password' => 'password',
        'database' => 'database',
    )
);

I hope you can help becuase I'm lossing my mind as to whats wrong, but I'm sure it's something minor that I'm overlooking.


texts: Installing the Charge plugin breaks plugin page

texts:
I am attempting to install the Charge plugin on a Craft site.  When I upload the plugin folder I get an error when opening the plugin page that says that the page cannot be loaded.  It works locally.  If I remove the plugin folder that page loads.  There is not a Craft error, I get an error that the page is "unable to handle the request", or just a total white screen. Anyone aware of an issue with the plugin?  I could not find anything here or online about it.

The folder is in the correct place and all the files are there, nothing has been tampered with or altered that would cause an issue.


texts: Craft Commerce: After add to cart, redirect to specific line item

texts:
I'm building a craftcommerce based site, where each item added to the cart must be individually customised through a wizard interface.

When the item first gets added to the cart, I'd like to immediately redirect to a page where we can customise the item further

Something like the redirect shown below:

<input type="hidden" name="action" value="commerce/cart/updateCart">
<input type="hidden" name="redirect" value="commerce/item?item={id}">
<input type="hidden" name="qty" value="1">
<input type="hidden" name="purchasableId" value="{{ purchasable.purchasableId }}">
<input type="submit" value="{{ "Buy"|t }}" class="btn btn-default"/>

This is possible with user form submission for instance, where the newly created user id is accessible via the method described above.

Any ideas on how I would go about doing this?


texts: Is there any way to change the CP navigation item for a plugin?

texts:
I'm wondering if I can have another name for my Plugin CP navigation item?

Let's say my plugin is called "Company name Social Media" but I want the navigation item to just say "Social Media". Might be a bad example but I think you understand what I mean. Let's say I'll release a commercial Craft plugin w/ my company name in it, but I want the customer to be able to add the plugin for a client without my name visible (more then on the plugins page).

Also is there any way to add dropdown-like sub-navigation items to the CP navigation for a plugin?


texts: Errors Trying to Install Craft Commerce on MAMP Pro

texts:
I've installed Craft Commerce locally on MAMP Pro a few times. When I click the install button it takes awhile and then finally I get a 500 Error.

My Apache Log shows only these two lines:

[Thu Jun 09 15:09:06 2016] [error] [client ::1] FastCGI: comm with server "/Applications/MAMP/fcgi-bin/php7.0.0.fcgi" aborted: idle timeout (30 sec), referer: http://craft-prototype.dev/admin/settings/plugins
[Thu Jun 09 15:09:06 2016] [error] [client ::1] FastCGI: incomplete headers (0 bytes) received from server "/Applications/MAMP/fcgi-bin/php7.0.0.fcgi", referer: http://craft-prototype.dev/admin/settings/plugins

After I receive the error if I go to /admin/settings/plugins the plugin will show as installed and it's completely fine. The issue doesn't happen when I try to uninstall it. The issue will still happen even if I uninstall and reinstall it.

I should also mention that the Craft CMS install and all other plugins are working great and I receive no other errors until this comes up.

I'm assuming this is probably a MAMP configuration issue. Has this come up for anyone else?


texts:
I have a Structure that has the URL setup like this..

Top-Level Entries - {slug}
Nested Entries - {parent.uri}/{slug}

How do I list all entries that have the same segment1 of their URL as to what is on the current page the user is on.

i.e if I am on page  http://example.com/vacation

I want to list all structure entries that have 'vacation' as the first segment of the URL.

i.e

/vacation/snow
/vacation/coastal

but it would not show any entries from the structure that are like this:

/advice/what-to-bring
/advice/weather-warnings
/contact

So basically I want to do this...

if segment1 = entry url segment1 display entries.


texts:
Long story short, I migrated from Craft 2 to Craft 3 but had an issue with a plugin.

Database Exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emailTemplateId' in 'where clause'
The SQL being executed was: UPDATE craft_sproutemail_notificationemailsSET emailTemplateId='barrelstrength\sproutforms\integrations\sproutemail\emailtemplates\basic\BasicSproutFormsNotification' WHERE emailTemplateId='sproutforms-basicsproutformsnotification'

I was told to reinstall Craft 2, update the plugin, and then migrate over to Craft 3.

I moved the Craft 3 files, reinstall Craft 2 and am trying to import the backup database. The problem is my backup database has existing tables that cause errors.

According to this post:

Best practice on importing Craft db backups?

They key is to get the database from the "backup database" function in
the control panel that includes

DROP TABLE IF EXISTS craft_analytics_settings; ...

before it creates all the tables so you shouldn't have to delete any
tables first, been working for us that way since the beginning.

I just don't know where to begin doing so. Is there any suggestions? At this point, I just want to get any version of the site back.

Thank you


texts:
Is it possible to create a hidden page within a Structure similar to how the Structure addon in EE does? It is still available at the url, but is excluded from the navigation.

I know there are several ways I could handle this, 3rd level nav, possible custom field (lightswitch), additional structure for hidden items, etc. These just don't sound like perfect solutions. Any other ideas?


texts: How do I find the category an entry belongs to?

texts:
I have a channel with entries which have a category field which is required.
When the entries are listed on a page how do I find the category that it belongs to?

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

Code so far is above.

The category has a background color field which I want to apply to the .


texts: Faceted navigation plugin problem installing

texts:
I get the errors below in the Command Prompt when trying to install.

helloswish/craft-faceted-navigation

Does anyone know why this is not working?

  [InvalidArgumentException]
  Could not find a matching version of package helloswish/craft-faceted-navigation. Check the package spelling, your
  version constraint and that the package is available in a stability which matches your minimum-stability (stable).

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--update-with-all-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...


texts: How to render an entry template in plugin?

texts:
I have a section "Emails" which has an entry 'Welcome Email'. The template assigned for it under Section is '_email/welcome'. This works fine when viewed in frontend. But I want to render the same template in my plugin services. The code I have used is:

$template = 'welcome';
$data = 'foo';

$oldPath = craft()->path->getTemplatesPath();
$path = craft()->path->getTemplatesPath().'_email/';
craft()->path->setTemplatesPath($path);
$html = craft()->templates->render($template,$data);
$breaks = array("
","
","
");
$text = str_ireplace($breaks, "\r\n", $html);
craft()->path->setTemplatesPath($oldPath);

But this gives an error "_email/_layout" not found in craft.log . What am I doing wrong ? Could anyone please help.

Thanks in advance.


texts: Can profile fields be limited to user groups in backend? It seems that if you want required front end fields for users registering then admins in backend have to have these as compulsory when creating admin accounts.


texts: How to use license in different environments

texts:
We have a very simple development process, and I believe this process has messed up the license.

app-client.local.mycompany.com.br => developer environment (intranet only)
app-client.qa.mycompany.com.br => quality insurance environment (openshift)  (intranet only)
app-client.hom.mycompany.com.br => client test environment (openshift) (intranet only,client access via vpn)
something.com.br => client website

local/qa/hom I'm using "environment = dev", but somehow local is working but qa and hom is not.

The database is a copy =>

from local to qa/hom when is a website in development
from prod to local/qa/hom when it is an already made website

It means every environment has its own database.

How to proceed to use dev licensing at local/qa/hom ?


texts: Cycle tag - last cycle returns same cycle

texts:
I have this code:

{% for entry in craft.entries.section('gigs') %}

{{ entry.title }}

{% endfor %}

This returns the same cycles for the last two entries like so:

Title 1

Title 2

Title 3

Title 4

Title 5

Title 6

No matter how many entries, the last two entries have always the same class. Why is that?

Edit: Okay, I figured the problem. It's not a bug:

I filter the entries by date:

{% set present = now|date_modify("-1 day") %}
{% for entry in craft.entries.section('gigs') %}
   {% if entry.datum < present %}

{{ entry.title }

    {% endif %}
 {% endfor %}

so the cycle filter works, but since some entries are filtered the odd/even schema doesn't work any longer. I guess I have to filter the entries first and then apply the cycle filter. But how would I have to write do that?


texts: How to handle two Redactor fields in one entry page in Craft 3.3?

texts:
I have an entry for blogs page. It contains 2 Redactor fields named content and body. I upgraded Craft 2 to Craft 3.3. Then the old editor changed to Redactor plugin, but that Redactor worked for body tag and not working for content tag. When I take an entry with content tag means, getting an error like:

  Invalid Configuration – yii\base\InvalidConfigException
  Redactor plugin not found:
  1. in {sitepath}/vendor/craftcms/redactor/src/Field.php

The entry works perfectly for the body tag.

My standard.json is like below:

{
    "buttons": ["html", "format", "bold", "italic", "lists", "link", "file","unorderedlist","orderedlist","image","video","table"],
    "plugins": ["fullscreen"],
    "toolbarFixed": true,
    "script": true,
    "paragraphize": false,
    "replaceDivs": false,
    "linebreaks": true,
    "enterKey": false,
    "replaceTags": false
}

Please help.


texts: Update billing details for a subscription

texts:
The Craft Commerce config allows you to set updatebillingdetailsurl. The docs say,

The URL for a user to resolve billing issues with their subscription.

There’s an example of this in the example templates that come with Commerce and this uses getBillingIssueResolveFormHtml().
However, rather than resolve an issue, what I’m looking for is a way for customers with a subscription (via Stripe) to be able to update their billing information before there is a billing issue. Often customers realise their card has expired or want to change their card before the subscription renews, especially as we send emails to notify them about renewals. What’s the best way to create that form, or allow someone to do that?


texts:
I can't, for the life of me, find an answer to this question.

I have a global called work.  It has three Asset fields.  One is called mediakit, which is an upload of a PDF.  I am trying to get the file name of that asset and add it into the template but cannot find anything giving me the proper way to do this in the template

Based on the documentation I thought:

 {{ work.mediakit }}

would output something at least but nothing shows and so whittling away from there to get it to call the correct path has eluded me.

Can anyone give me the correct way to call that?

The path is:

  "/assets/medikit/{{ the filename of the pdf uploaded}}"


texts: Locales - New locales not copying assets across

texts:
I have a site made in English and need to add another locale that will be almost identical to the original site. However while adding new locales everything bar the asset entries are being copied. This is a problem as there are already many articles with image asset fields and new articles are not copying assets across locales either.

I have tried making the asset field Translatable and Not Translatable. These fields are not in a matrix.

UPDATE: Solved - What was needed was to use the Update Asset Indexes tool in the settings of craft. If I do this just after creating a new Locale, before doing anything else, when my articles are created they know where to look for their assets. So relieved


texts: Multi site live preview not working on index page

texts:
I'm on Craft 3.1.17.2

My multisite setup is using different domains.

If I'm on a.com, I can Live Preview everything on b.com fine, except the homepage.

I get the error Access to XMLHttpRequest at 'b.com' from origin 'a.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

If I add Access-Control-Allow-Origin * to my Nginx config, none of the pages work and it complains about a duplicate value of (a.com, *).

Any ideas? Other questions I've browsed all suggest this has been fixed in Craft 3.1, and none of the docs indicate the I need to do anything to get this to work.


texts:
I'm setting up a dynamic thank-you page for all forms added to the site. Client can add forms with freeform to any page and I have set the return url to this:

{{ form.renderTag({
    class: "w-full pb-4",
    returnUrl: craft.app.request.absoluteUrl ~ 'thank-you/'
    }) }}

Which works. However on the thank-you page I would like to set the entry to be the slug of the second last url segment

i.e. if the thank you page is https://domain.com/foo/bar/thank-you then I need to be able to get bar however if the url is https://domain.com/foo/thank-you then I need to get foo

How can I do this? if only craft.app.getSecondLastSegment() were a thing.

so ideally something simpler than this:

{% set entrySlug = "" %}

{% if craft.app.request.getSegment('4')|length %}
  {% set entrySlug  = craft.app.request.getSegment('3') %}
{% elseif craft.app.request.getSegment('3')|length %}
  {% set entrySlug  = craft.app.request.getSegment('2') %}
{% elseif craft.app.request.getSegment('2')|length %}
{% else %}
  {% set entrySlug  = craft.app.request.getSegment('1') %}
{% endif %}```


texts: Debugging Craft search query: differences between craft.log and dump()

texts:
I'm new to Craft, coming over from ExpressionEngine to start doing maintenance on an agency-built Craft site, and I have what may well be a very basic question... please be gentle.

We have a page that allows searches on a particular section of entries. There is a form that has a handful of input fields corresponding to ExpressionEngine fields that can be searched. One of the input fields (locationState) always gives zero results, even though the data being searched for is there per admin and database.

When I look at craft.log, I can see that several database queries go into the search. The query that's just pulling primary keys for matching rows works fine. The next query, which wants to pull all fields for output for rows with those primary keys, looks like it has a problem:

SELECT * FROM `craft_searchindex`
WHERE ((`keywords` LIKE '%title%') OR (`keywords` LIKE '%position%') OR (`keywords` LIKE '%jobtitle%') OR (`keywords` LIKE '%bioquick%') OR (`keywords` LIKE '%biofull%') OR (`keywords` LIKE '%institution%'))
AND `locale` = 'en_us'
AND `elementId` IN (5355,7874,8608)

Those title, position, jobtitle, bioquick, biofull, and institution values look like they're unparsed variable names to me, like someone writing this code forgot to evaluate them for values before handing them off to the search service.

However!

If I go into the template for this search page do a dump(params), where "params" is the name of a variable being constructed out of user input to the search form input fields, I get this:

array(6) {
    ["section"]=> string(8) "profiles"
    ["type"]=> string(11) "localExpert"
    ["order"]=> string(5) "score"
    ["limit"]=> int(25)
    ["locationState"]=> string(2) "DC"
    ["search"]=> array(3) {
        ["query"]=> string(73) "title: OR position: OR jobTitle: OR bioQuick: OR bioFull: OR institution:"
        ["subLeft"]=> bool(true)
        ["subRight"]=> bool(true)
    }
}

Here are title, position, jobtitle, bioquick, biofull, and institution again. The full code that dynamically creates the params variable is too long to paste, but the piece of it that addresses these 6 fields looks like this:

{% set fullquery = 'title:' ~ query ~ ' OR ' ~ 'position:' ~ query ~ ' OR ' ~ 'jobTitle:' ~ query ~ ' OR ' ~ 'bioQuick:' ~ query ~ ' OR ' ~ 'bioFull:' ~ query ~ ' OR ' ~ 'institution:' ~ query %}

where "query" is craft.request.getParam('q') and where "fullquery" eventually gets concatenated into params.

The meat of my question here is this: for my failing search, craft.request.getParam('q') is null. So I'd expect that the value of "fullquery" would be concatenating empty strings, which matches what I see when I do that dump(params), but does NOT match the SQL query I see in craft.log, with those seeming unparsed variables.

So I hope someone can help me out by at least confirming that what gets written to craft.log is the final and literal query, post all evaluation and parsing, right? Knowing that alone would help me know I'm not missing something super fundamental on my way to trying to figure out how my dumps don't match what's in craft.log, which seems pretty key to figuring out why my search is failing.

FWIW, I'm doing my dump(params) immediately before the line of the template that runs the search via {% set entries = craft.entries( params ) %}, so nothing should be changing between the dump and the logging of the db query.

Thank you, and I hope my question is clear.


texts:
I'm building a plugin and have a form in the plugin's CP page that allows admins to save access codes. The form is a simple textarea where each line is a separate access code.

I'm wondering what the best practice is in terms of inserting these records into the database?

Controller:

// This returns an array of codes to be inserted
$codes = explode("\r\n", craft()->request->getPost('codes'));

foreach($codes as $code) {
    $codeModel = new Portal_CodeModel();
    $codeModel->code = $code;
    $codeModels[] = $codeModel;
}

$success = craft()->portal_code->addCodes($codeModels);

Service:

public function addCodes($codes) {

    foreach($codes as $code) {

      Portal_CodeRecord::model()->insert(array(
          'code'        => $code,
          'code_used'   => 0
      ));

    }

}

Record:

class Portal_CodeRecord extends BaseRecord {

    public function getTableName() {
        return 'portal_codes';
    }

    protected function defineAttributes() {
        return array(
            'code'          => AttributeType::String,
            'code_used'     => AttributeType::Bool
        );
    }
}


texts:
I did find this post while looking to do something similar, but I'm beginning to wonder if there's a bug.

With code along the lines of:

craft.entries.section("pages").type("not landing")

I'm unexpectedly getting no results. Looking at the logs, it's generating queries that includes:

SELECT * FROM `craft_entrytypes` `t` WHERE `t`.`handle`='not landing'

I have to think this is at least partly responsible for getting no results. Could anyone point out if I've got the syntax wrong or something?


texts: What's the easiest way to migrate my local site data to my live site?

texts:
I've finished my site locally, and would like to migrate my data to my production database.

I've already uploaded the templates, assets, etc, but I'm unsure how to 'dump and load' (referenced from this question ) my database to production.

I realize this may be a little bit more phpMyAdmin related, but I thought this question could help others who are just beginning work with Craft CMS!


texts: Querying entries that have not been related to any other entry or contained matrix element

texts:
I have a large amount of content that we are attempting to collect before we migrate to our new site structures. Normally the staff are supposed to relate content back to main entries to make sure that content ownership is maintained as seen below.

However, they often would just add a page and then add a link to a relationship from a parent page as they discovered this was "easier":

What I’m wondering is if there is a way for me to query entries that have not been related in the second method. The first example is simple, for example, I can query my topics that are missing relationship fields filled out like so:
{% set total =
  craft.entries.section("topics")
    .departments(":empty:")
    .boardsCommissions(":empty:")
    .officials(":empty:")
    .processes(":empty:")
    .projects(":empty:")
    .topics(":empty:")
 %}

Topics missing all relationship fields: {{ total | length }}

{% for entry in total.all() %}
  {{ entry.title }} - {{ entry.author }} - {{ entry.id }}

{% endfor %}

Where I’m getting confused is how I would query the second example, as what I want to do is query if the entries have been related to any other content on the site, which also includes matrix fields that may also have those relationships, instead of predefined fields.


texts: Developing in Teams - What is the best Craft setup?

texts:
We are currently working on a Craft project with 3 developers.

Our setup:
3 Local machines running Laravel Homestead and a local DB + Craft.
1 remote server holding Craft + db.

Our workflow:

We are using Github for version control of our local files.
For the DB we are currently using a dumb workaround we are very unhappy with :) . We are saving the DB in the craft-cp and git pushing the export to whatever branch we are working in. Then the next person has to import it locally whenever he makes changes to it.

We just thought using the same remote db on our server would be a better idea. Any better ideas? Is there something as good as Github but for DBs?
Or is there a better way to collaborate on a craft project anyway?


texts: Can I use Regex in the Find and Replace tool?

texts:
Does the Find and Replace tool support regex? I need to remove a certain section of an image url for all images in the 'field_body' column.

So if I had an image referenced as such

http://craft.dev/uploads/image-600x400.png

I would be able to find all images that match that pattern and return the url to be

http://craft.dev/uploads/image.png

Now I have very little experience with Regex but would this be a safe pattern to use (if I can with Craft that is...)?

(-[0-9]+x[0-9]+)


texts:
I want to add a Comodo Trust Logo to a Craft CMS website page per the instructions below:

Install Code Snippets
Please insert the following two snippets of HTML
code into your webpage document. You will need to repeat the process
for each web page you wish to display the TrustLogo.
<script type="text/javascript">//<![CDATA[
var tlJsHost = ((window.location.protocol == "https:") ? "https://secure.comodo.com/" : "http://www.trustlogo.com/");
document.write(unescape("%3Cscript src='" + tlJsHost + "trustlogo/javascript/trustlogo.js' type='text/javascript'%3E%3C/script%3E"));
//]]>
</script>

How do I access the Craft CMS code in order to add the above JS?
Thank you!


texts:
Folks:

The client receives an email with order details that include the customer shipping address. On a couple of occasions, though, the shipping details do not show. Notes:

The email is delivered without an issue.
The customer shipping address is missing.
The customer email still makes it through. Not sure why just the
email comes through but could be a fluke.
The order form does not allow the user to complete the transaction
without a shipping address.
Neither the commerce nor the craft log files show anything amiss.
Viewing the confirmation email source reveals nothing.

The customer confirmed that they entered all their details. The customer also confirmed that they are using standard Chrome and that they checked all their details before placing the order. They also attempted the same transaction a second time at the request of the client and they could not get past the address screen without entering a shipping address.

Any assistance would be appreciated.


texts:
Im looking for where to get the Gateway Response as the site I am working on is carrying over a legacy subscription system. Using  verbb / commerce-payflow Plugin. Any pointers would be great we authorize the payment then use the PNREF to continue the subscription so all i'm looking to do is Authorize the first payment as I have a module I can do the rest of the transactions through.
Thanks in advanced.


texts:
I used this example to create an RSS feed in Craft, saved it as “feed.rss”, uploaded it into the “craft/templates” directory. When I go to www.my-website.com/rss, I get a 404.

What am I missing here? Any help is highly appretiated.

Thanks!


texts: How would I setup my plugin to use a unique fieldlayout that is unique to the top level of the plugin?

texts:
For example: Users. You can only have one fieldlayout per ElementType user which you customize in the settings section.

I've got as far as abstracting out the fieldlayout to it's own view, but when I go to set the field layout in the controller I'm borrowing the following code:

// Set the field layout
$fieldLayout = craft()->fields->assembleLayoutFromPost(false);
$fieldLayout->type = ElementType::MyElementType;

To which I get the following (pretty much expected) error:

 Fatal error: Undefined class constant 'MyElementType' in /controllers/MyElementTypeController.php on line 115

I've looked at how the plugin example "Events" is handling this and Brandon seems to be setting the fieldlayout->type to Assets:

$fieldLayout = craft()->fields->assembleLayoutFromPost();
$fieldLayout->type = ElementType::Asset;
$calendar->setFieldLayout($fieldLayout);

Is this how we're supposed to be setting these up? i.e., borrowing from other elementtypes?


texts: Plain text field - apostrophes are getting escaped

texts:
I have a plain text field in Craft and the content has an apostrophe. On the front end, the apostrophe gets turned into &#039;

Not ideal! Thanks in advance..


texts: Craft Commerce Arrange a delivery booking plugin?

texts:
Is there a booking plugin available for Craft Commerce that would let you arrange a delivery via a calendar interface with AM and PM timeslots? Or would it need to be custom developed for Craft.

The client's shop already has this functionality via it's current custom CMS, but we'd like to move it over to Craft Commerce if possible. And this looks like one of the sticking points as there doesn't seem to be anything like it currently.


texts: How to list all Matrix Blocks from anywhere, using a slug?

texts:
I came across a specific situation where I needed to list out all the values within a collection of Matrix fields on a single entry page.

More specifically, I had a single entry that needed multiple team groups, each with the name, role, and description of various people. I then wanted to list them all out anywhere on the site (single or entry pages).

Hope this solution helps people out. Feel free to critique.


texts: How to integrate Craft Commerce with Salesforce?

texts:
We're looking for a way to integrate Craft Commerce with Salesforce. What are the options there?

Is there a Craft API to talk to? (I can't seem to be able to find it...)

And the other option is to write a plugin in Craft that communicates outwards to Salesforce, I suppose?


texts: Re-using entry types across multiple sections

texts:
Is there way to a create an entry type that you can re-use on different sections?

Essentially what I would like to do is define one entry type, such as a "Product" entry type, and add fields for a product. Then I'd assign this "Product" entry type to each section, as required.

This would prevent me from having to create a "Product" entry type on every section and add the same fields to each one.


texts: Craft 3 – Render template as if it were a site request

texts:
I have a Craft 3 plugin that renders a portion of an entry after save in order to index the resulting information. The plugin needs full access to the Twig extensions on the site to render the template, however several plugins that add such extensions check:

if( Craft::$app->getRequest()->getIsSiteRequest() )

As a result not all Twig extensions load when renderTemplate is called from the control panel. I set the template mode using:

Craft::$app->getView()->setTemplateMode(View::TEMPLATE_MODE_SITE)

but that only updates the path to the template. Is it possible to render the template as if it were a site request?


texts: Mutliple logouts required on Multiple App Servers

texts:
We're using Craft CMS (pro) across multiple application servers and using reddis to manage the sessions.

We're needing to click on 'log-out' twice, sometimes several times before it actually logs us out of the control panel.

Any idea what could be causing this?


texts: SuperTable Returning Unexpected Results w/ Template

texts:
Perhaps I am not understanding how to properly use SuperTable, but I am having a strange issue where calling for the results of a SuperTable field twice in the same template overwrites the results of the second instance with those of the first.
I have a SuperTable used to assign contributors to things and capture a contribution and a few characteristics identified through flags (showBio and featured).
In my template I perform the following queries at two different points to show featured contributor and then show all contributors:
{% set featuredPeopleGrouped = entries.supertable
    .featured(1)
    .with(['contribution','contributor'])
    .all()|group('contribution[0]')
%}

and
{% for person in entry.supertable.showBio(1).all() %}

The first query works as expected. Strangely, the second is limited by the first -- an only includes people with the featured flag on. Removing that condition from the first removes the limit on the second.
In looking through the SuperTable documentation, it seems like the suggestion is to query the SuperTable field directly, capturing the row related to a given entry. Am I simply doing this wrong?
Thanks in advance!


texts: Possible to set Forgotten Password path in config?

texts:
Looking at the documentation here: https://docs.craftcms.com/v2/config-settings.html#users

I have set loginPath, invalidUserTokenPath and setPasswordPath. However, it appears that there isn't a config option for the forgotten password template.

It's also not mentioned as an option (unlike the other path options mentioned above) on this doc: https://docs.craftcms.com/v2/templating/forgot-password-form.html

EDIT: Forgot to add that I have got it working in the meantime by setting
{{ url('users/forgotten-password') }} in my login template.

Thanks.


texts:
It is easy to set in the text field, but I don't see such option in RTF. How can I do it?

Alternatively, I can use a text field, though it doesn't output new lines as paragraphs - it is possible?


texts: Has anyone been able to get auto-complete working with plugins + PHPStorm?

texts: It would make my day to be able to have PHPStorm recognize third-party services. Has anyone figured out how to get this working yet?


texts:
I have a basic contact form set up and working but I've now got to change it to make it support locales. So depending on what language version of the website you are looking at, the form submits to a different address.

So what I have so far is I've set up several forms one for each language with their form handles being contact_en, contact_de etc, which is working fine I get submissions to the different forms. What I haven't got working is the validation, in particular how reference the submitted field and get any errors. In the original working form my form handle was contact, so to reference the field I used contact.fullName, this worked fine.

So now to setup the form initially I'm using:

{% set form = craft.amForms.getForm('contact_' ~ craft.locale) %}

Is there a way to get a handle to the form so I can reference the fields?

I've tried:

{% set formHandle = form.handle %}

This just returns a string, so it fails if I tried to reference a field like this:

{{ formHandle.fullName }}

I'm sure there's a straightforward way of doing it that I'm not seeing! Any help gratefully received.


texts: Template error: Method "siteUrl" for object "Craft\ConfigVariable" does not exist

texts:
Method "siteUrl" for object "Craft\ConfigVariable" does not exist

{% for locale in otherLocales %}

    {# Is this an entry page? #}
       {% if entry is defined %}

         {# Find the current entry in the other locale #}
        {% set localeEntry = craft.entries.id(entry.id).locale(locale).first %}

        {# Make sure that it's actually localized to this locale #}
       {% if localeEntry.locale == locale %}

           {# Output a link to it #}
            <link rel="alternate" hreflang="{{ locale }}" href="{{ craft.config.siteUrl[locale] ~ (localeEntry.uri != '__home__' ? localeEntry.uri) }}">
         {% endif %}

    {% else %}

        {# Just output the same path with the locale's base URL #}
        <link rel="alternate" hreflang="{{ locale }}" href="{{ craft.config.siteUrl[locale] ~ craft.request.getPath() }}">
    {% endif %}
{% endfor %}


texts: How can I fix Image Exception error when uploading image via front-end form while Preparse plugin enabled?

texts:
I'm not sure if the issue is with Craft 3, the Preparse plugin, or me, so I'm posting here first.

I have a front-end form that includes an Assets field used to upload images. The entry type contains Preparse fields.

When the Preparse plugin is enabled and I submit the front-end form with an image, I get this error:

Image Exception – craft\errors\ImageException
The file "assets5bcf19ef8f6bc6.04658934.jpg" does not appear to be an image.

Screenshot with more details: https://cl.ly/edfbc0c07bde

The entry still gets created and the .jpg file is uploaded as expected.

I don't have any issues when creating entries via the CP.

If I disable the Preparse plugin and submit the front-end form, the error does not appear.

If I upload a .pdf file instead of a .jpg while the Preparse plugin is enabled, I don't get an error.

Therefore, it appears to be an issue with the Preparse plugin and image files in Craft 3 front-end forms (tested both .jpg & .png).

How can I fix this?


texts: Problem with switch statement in language picker - [Solved]

texts:
I made a language picker, it works in one language but not in other. I want to get the current page of other locale.

{% set locale = craft.i18n.getCurrentLocale() %}

 {% switch locale %}

  {% case 'en_us' %}
   Deutsch
  {% case 'de' %}
   English

 {% endswitch %}

Works in first case but not the second. What am i doing wrong?

Update: I forget to update the locale template in other language. Problem is solved, my mistake.


texts: Image Upload "Failed to load resource: the server responded with a status of 500 (Internal Server Error)"

texts:
I'm getting my nerves on this because I can't find what's stopping from uploading. I simply choose a file, the loading show and get itself complete, but it simply stops at the 100%. I ran into my browser's console and this shows up:

Safari:
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"

Chrome:
"Failed to load resource: http://craft.dev/index.php/admin/actions/assets/uploadFile the server responded with a status of 500 (Internal Server Error)"

Please help me to figure this out... A huge thanks in advance!

I'm running the website on localhost and using AMPPS and Navicat for the DB.


texts: Send email to website owner after user registration

texts:
I have a client that wants to get notified whenever someone registers on their website.

How can I do this, is there some kind of plugin? If not how would I go about doing this?


texts: Get selected values from all of an entry’s Multi-select fields

texts:
I am new in Craft, and will be happy if I can get help with this task. I have a tab that contains only multiselect fields. What I want to do, is to get all selected values for all multiselects field in this tab. I find this answer to get all field from a tab, but I can't get the selected values for the entry. Here is my code:

{% for tab in entry.getFieldLayout().getTabs() %}
  {% if tab.name == 'Spec' %}

{{ tab.name }}

          {% for field in tab.getFields() %}

{{ field.getField().name }}

          {% endfor %}

  {% endif %}
{% endfor %}


texts: Plugin-settings form field for chosing a user?

texts:
I'd like to be able to select a user for a settings field for my plugin.

Is there a settings AttributeType that matches users? And a corresponding forms template for picking a user?

(also interesting would be picking assets/elements from a certain section)


texts: What is the advantages/disadvantages of separating macro imports?

texts:
In my base template extended by all other templates, I import my macros, so I have global use of them throughout my templates.

Question 1:
Am I taking a performance hit for including these whether or not I'm using them in a given template?

Question 2:
Is there any advantage to splitting up macros into different imports, other than just organization?

In other words, is there any reason not to do:

{% import "_includes/macros" as macros %}

And have _includes/macros have all my macros?


texts:
I'm trying to check my craft locale to offer language switching but it seems that my french locale returns the "en" value???

When I run the following:
{% if craft.locale == 'fr' %}

I instead get the contents of:
{% if craft.locale == 'en' %}

Is anyone experiencing this? I don't see any code that could be messing with the code.

Note: the site url outputs just fine: mysite.dev/fr/ BUT if I print {{ craft.locale }} I get "en".


texts: Form Error Causes Page to Reload Without an Entry ID

texts:
I have a section (single) that uses a template that shows information from the entry and includes a form (uses entry form) that posts to a different section (event registration info). All is fine as long as the form data is valid.

If the form is submitted such that it throws an error (required field not filled in), the user is redirected back to the original page, but only the form is displayed and there is apparently no entry ID passed when reloading the template.

Any ideas would be appreciated!

Here is the template code for the form - note that the form handles a number of different event registrations, hence the variables for the redirect and the section Id for posting the form contents:

<form id="eventReg" method="post" action="" enctype="multipart/form-data" accept-charset="UTF-8">
                        {{ getCsrfInput() }}
                        <input type="hidden" name="action" value="entries/saveEntry">
                        <input id="theRedirect" type="hidden" name="redirect" value="{{ theRedirect }}">
                        <input type="hidden" name="sectionId" value="{{ section }}">


texts: Maximum execution time exceeded when adding or updating plugins from the Control Panel

texts:
When I try to install or update a plugin from the Control Panel, I see a message "Updating Composer Dependencies" and then the following error occurs. I'm running Craft on a local environment. Installing and updating from the command line works fine.

Status: Internal Server Error

Response:
PHP Fatal Error &#039;yii\base\ErrorException&#039; with message &#039;Maximum execution time of 30 seconds exceeded&#039;
in ...\vendor\composer\composer\src\Composer\Util\RemoteFilesystem.php:555

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


texts:
Our client would like to run a promotion which would require a user to spend at least £30 in order to get a certain product for free.

We have setup a ‘codeless’ discount that has:

the product that they get free in the Product field in conditions
The Purchase Total set to 30 (although I think this means the total value of the above products)
The Base Discount amount to be the same as the value of the product (3.99).

I had assumed, that provided the cart > 30 and that product was in their cart, the 3.99 would be automatically removed from the total. Now I’m guessing it’s not doing that because of the way the Purchase Total works.

If that is the case, does anyone know how I’d achieve the desired outcome?


texts:
We have an existing CMS and I'm just learning how to use CraftCMS so that I port the data from SQL Server to MySQL database. I went through a few videos on how to create a basic site so I kinda understand the system.

I have used a couple of plugins to import the data and one of them being this:
https://github.com/boboldehampsink/import

This plugin doesn't export existing data from MySQL data from Matrix field (using sample data). I wanted to see how the data is stored so I can create a similar format. But unfortunately the Matrix field comes back empty. I am not sure how to create and insert data in CraftCMS for this specific field. I will also at some point need to retrieve this data so I would like to know how the insert/select works on these fields.

Thanks in advance.


texts:
I have set up a Matrix field with three blocks, each contains a Table field.

Each table has one column - a single line text field.

When I call these tables into the template with this code, each row is echoed twice:

{% for block in entry.projectFacts.limit(3) %}

    {% switch block.type %}
        {% case 'code' %}
            {% if block.codePoints | length %}

                    {% for items in block.codePoints %}

                        /* Outputs "Array" */
                        {{ items }}

                        {% for wtf in items %}
                            /* Outputs identical content & wrapper twice */

{{ wtf }}

                        {% endfor %}

                    {% endfor %}

            {% endif %}

{% endfor %}

I'd be delighted if someone were able to point out what I need to do differently.


texts:
Ok, so I'm looping through a lot of entries. It's a large request, and I had to up php memory limit to 512M. But I'm sure there is a less memory consuming way to do this. Also, I want to cache the whole thing, apparently 512M isn't enough for that.

Any suggestions? Should I just go ahead and use the ElementAPI?

var geojson = [
          {
            "type": "StationCollection",
            "features": [
            {% for entry in craft.entries.section('map').limit(3000).find() %}
                {
                "type": "Feature",
                "geometry": {
                  "type": "Point",
                  "coordinates": [
                    {{entry.address.lng}},
                    {{entry.address.lat}}
                  ]
                },
                "properties": {
                  "title": "{{entry.title}}",
                  "slug": "{{entry.slug}}",
                  "alwaysOpen": "{{entry.alwaysOpen}}",
                  "phone": "{{entry.phone}}",
                  "saturdays": "{{entry.saturdays}}",
                  "stationType": "{{entry.stationType}}",
                  "sundays": "{{entry.sundays}}",
                  "workingDays": "{{entry.workingDays}}",

                }
              },
            {% endfor %}
        ]
      }
    ];


texts: FastCGI error when accessing a local development site using MAMP Pro

texts:
I'm running across a problem developing a site locally using OS X 10.10 and MAMP Pro 3.0.5 with PHP 5.5.10. Accessing both the site front-end and the back-end admin interface is  throwing an error 500 Internal Server Error.

The MAMP Apache log is showing multiple instances of the following error:

[Mon Nov 10 14:03:04 2014] [error] [client 127.0.0.1] FastCGI: comm with server "/Applications/MAMP/fcgi-bin/php5.5.10.fcgi" aborted: idle timeout (30 sec), referer: http://jtp.dev:8888/admin/entries/project
[Mon Nov 10 14:03:04 2014] [error] [client 127.0.0.1] FastCGI: incomplete headers (0 bytes) received from server "/Applications/MAMP/fcgi-bin/php5.5.10.fcgi", referer: http://jtp.dev:8888/admin/entries/project

Once this happens, I can't continue working until I restart my machine. Restarting my Mac and restarting MAMP fixes the error temporarily, but it eventually reappears and prevents me from being able to view the site locally.

Has anyone got any ideas about what may be causing this?


texts: Delete matrix blocks based on their content

texts: Is it possible to pragmatically delete a matrix block based on its content? I have a channel called "Artist", which has a matrix field with concerts. It'll be about 5-600 concerts in total every year, so it's a bit of a hassle to manually remove old concerts. Every block has a field with the concert date. Is it possible to remove matrix blocks based on that date?


texts:
I'm extremely new to Craft CMS - I'm trying to install it on to a Cpanel as a test, upon downloading the CMS is gives you all the folders for craft, and then a separate /web folder.

If you move the contents of the /web folder outside of this, it causes an error. I've also tried moving the craft installation up one level, and then taking the contents of the /web folder out, but this also errors. am I missing something extremely obvious?

It's currently set up as a sub domain:

http://ea.cranberrywp.co.uk/web/

I'm looking to make it like this:

http://ea.cranberrywp.co.uk/

But as you can see that takes me to just the directory.

Sorry for the silly question!


texts:
I'm making a portfolio website, where the url's look like "projects/project-name".
There is also an overview page with all the projects that is under "projects" on itself.

I'm using a Structure for this, but I go to the 404 page when I'm just trying to go to "projects" without the slugs.

Is there a way of using a structure without a slug?


texts: How to get related entry data using ElementCriteriaModel in a plugin

texts:
I am working on a custom plugin which gets some entry data using

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->order('postDate asc');
$criteria->dateUpdated = array('and', '>=' . $this->dateFrom->format(DateTime::MYSQL_DATETIME), '<=' . $this->dateTo->format(DateTime::MYSQL_DATETIME));
$criteria->limit('null');

$responses = $criteria->find();

The returned entries contain a relationship to entries in another channel. In this case, the relationship field is named 'video'. So when looping through $responses I can see that $response->video is an array containing the sourceElement id and field id.

Is it possible to get the complete entry data for the related entry returned in the same query rather than needing to perform an additional query?


texts:
All, I'm very close, but missing something and any help is appreciated. I have a teamMember matrix block allowing me to add employees with some basic info. One of the fields is a category field called 'department'. I"m trying to list the departments, and within them, the employee information.

Currently my output is this:

Marketing
  marketing member one
  marketing member two
  creative member one
  creative member two

Creative
  marketing member one
  marketing member two
  creative member one
  creative member two

However, I'm looking to achieve this:

Marketing
  marketing member one
  marketing member two

Creative
 creative member one
 creative member two

It seems that I'm doing something wrong with relatedTo.

My code:

        {# Fetch entries with a Matrix block to get non empty categories #}
        {% for block in entry.teamMember.all() %}
        {% set category = block.department.one() %}

        {# Fetch entries with a Matrix block related to the category #}
        {% set entries = craft.entries.relatedTo(category).all() %}

{{ category.title }}

            {% for block in entry.teamMember.all() %}

                {% set image = block.photograph.one() %}
                {% if image %}

&nbsp;

                {% endif %}

{{ block.fullName }} {{ block.jobTitle|markdown }}

                {{ block.biography }}

            {% endfor %}

        {% endfor %}

What am I missing? Thank you in advance!


texts: Where to upload a User photo in the admin?

texts:
Not sure if I'm just overlooking, but I can't seem to find where in the admin to update my user photo (Craft versions 3.5 and 3.6).
The User Photo Location field in User Settings is set to a valid Volume, but when I view My Account (or edit the settings of any other Users) none of the Account/Permissions/Preferences tabs have a field to add/update this image.
I am logged in under an Admin account. Am I missing something?


texts:
I've got a multi-environment setup similar to the following, and thinking about adding database details to the index.php. In this way, I can pretty much just edit the index.php when creating new websites - staying out of app/config.

switch ($_SERVER['SERVER_NAME']) {
    case 'local.craft.dev':
        define('CRAFT_ENVIRONMENT', 'local');
        define('CRAFT_DB_USER', 'root');
        define('CRAFT_DB_PASSWORD', 'craftycraft');
        define('CRAFT_DB_DATABASE', 'local');
        break;
    case 'staging.com':
        define('CRAFT_ENVIRONMENT', 'staging');
        break;
    default:
        define('CRAFT_ENVIRONMENT', 'production');
        break;
}

Would there any potential security issues with this? I imagine being in the web root might be risky - but would having this information in db.php a level up really made a difference to a hacker?

Would like to hear your thoughts!


texts: How do I add commas to an output that returns a list of names?

texts:
I have a simple for loop to get the names of countries from a category.

{% for name in country %} {{ name.title }} {% endfor %}

The output is typically returns the name of 1 country.  But, some entries are associated with more than one country.

For example:

  Belgium Czech Republic Denmark Greece Netherlands Norway Portugal

How do I template for an entry that returns 2-N country names by adding "," between each country and "and" before the last country?

This is what I want to output:

  Belgium, Czech Republic, Denmark, Greece, Netherlands, Norway and Portugal


texts: Craft model and populateModels() performance issue?

texts:
I'm getting a big performance hit on front end requests (+15 seconds) when using a model to store / use data from one of my custom fieldtypes, cp requests for the same data appear unaffected.

The prepValue function:

public function prepValue($value)
{
    if( is_array($value) )
    {
        return FruitGrid_BlockModel::populateModels($value);
    }

    return $value;
}

And the model which is getting populated:

class FruitGrid_BlockModel extends BaseModel
{
    protected function defineAttributes()
    {
        return array(
            'row' => array(AttributeType::Number),
            'col' => array(AttributeType::Number),
            'sizex' => array(AttributeType::Number),
            'sizey' => array(AttributeType::Number),
            'entryid' => array(AttributeType::Number),
            'rules' => array(AttributeType::Mixed),
        );
    }

    public function getRuleClasses()
    {
        $string = '';
        if(is_array($this->rules))
        {
            foreach ($this->rules as $rule => $value)
            {
                switch ($rule)
                {
                    case 'fixedHeight':
                        $string .= ' height-'.$value;
                        break;
                    case 'desktopRuleOne':
                        $string .= ' desktop-'.$value;
                        break;
                    case 'tabletRuleOne':
                        $string .= ' tablet-'.$value;
                        break;
                    case 'mobileRuleOne':
                        $string .= ' mobile-'.$value;
                        break;
                }
            }
        }
        return trim($string);
    }

    public function getEntry()
    {
        $criteria = craft()->elements->getCriteria(ElementType::Entry);
        $criteria->id = $this->entryid;
        return $criteria->first();
    }
}

And pretty standard usage on the front end:

{% if entry.customFieldHandle|length %}

    {% for block in entry.customFieldHandle %}

{{ block.entry.title }}

{{ block.entry.text }}

        ...

    {% endfor %}

{% endif %}


texts: Eager-loading of matrix field with getPage

texts:
Can anyone provide a working example to extend the following code (add support for matrix block named "copy") and allow getPage usage:

{% set entries = craft.entries({
   section: ['news'],
   order: 'postDate desc',
   limit: 5,
   with: [
     ['assets', { kind: 'image' }]
   ]
}) %}

{% for content in entry.contentBuilder.type('copy').limit(1) %}
   {{ content.copy.getPage(1) }}
{% endfor %}


texts: What is the handle of a section’s default entry type?

texts: For a section without additional entry types, what would be the handle value of the default entry type output by {{ entry.type }}?


texts: Reverse related entry with Solspace Calendar

texts:
I'm using Solspace Calendar,
When I create an event with it I use a related entry field called 'project'
to choose an entry from a section called projects
I can display the project title etc in the Calendar template,
however I want to display the projects event date when on the project page (reverse related)
I can't fathom how to construct a reverse related entry – being 'events' is neither an entry, user, asset etc as per this question: Related Entries
I would like to understand if its even possible as for example - the plugin not being a section, this clearly won't work:
{% set relatedDates = craft.entries.section('events').relatedTo(entry) %}

how would one grab the calendar event to begin with?
Thanks


texts:
Is there a way to do this? Emails are pretty ugly when selecting people.

I'm guessing it would be a quick plugin to write, if I wrote plugins. Anyone done this before?


texts: Can I get the value of an environment variable in routes.php (or other config files)?

texts: I am trying to get the value of an environment variable (defined in the general.php config file) in the routes.php config file. Is it possible or not? I tried $environmentVariables = craft()->config->get('environmentVariables')['myVariable'] but that throws an error: Call to undefined function craft().


texts: Category archive page isn't filtering by current category

texts:
Ok all - this is bound to be ridiculously simple, as it's one of the most basic things you can do (https://craftcms.com/support/entries-related-to-category) - but I am ill and I can not figure out what I've done wrong.

I have a category group 'Things To Do'. That group is set to allow categories in it to have their own URLs. The URL format is: things-to-do/{slug} and it uses the template 'things-to-do/category'.

I also have a channel Things To Do, the URL format being 'things-to-do/{slug}' and using a different template 'things-to-do'.

If I go to the url for a category that exists, it loads the correct template and I can output the correct fields attached to the category itself; e.g., {{ category.title }} or {{ category.myCustomField }}

However, trying to output entries related to the category I'm viewing is instead just listing all entries regardless of their lack of association with the category...

{% set thingsToDo = craft.entries.relatedTo(category) %}
{% for thingToDo in thingsToDo %}
    ...
{% endfor %}

This should only be listing one entry for a given category, but it's listing all entries.

What have a screwed up?


texts:
I want to create an ICS file that people can download to add events to their calendar. I have done this with ExpressionEngine by creating an xml template and just calling it. Below is the code I have so far but I think the problem is that twig doesn't allow php in a template. I'm guessing that means I need to put this in a plugin, but that's beyond my skills. Any help/advice appreciated.

<?php
$ical = "BEGIN:VCALENDAR
X-WR-TIMEZONE:Europe/London
PRODID:-//Orienteering Club//NONSGML v1.0//EN
CALSCALE:GREGORIAN
X-WR-CALNAME:Orienteering Club
VERSION:2.0
{% set events = craft.entries.find({section:'events,activities', eventDate : ">= " ~ now.w3cDate() , order:'eventDate'}) %}
{% if events %}
{% for entry in events %}
BEGIN:VEVENT
UID:{entry_id}
URL;VALUE=URI:{{ entry.url }}
DTSTAMP:{{ entry.eventDate.format('Ymd') }}
DTSTART:{{ entry.eventDate.format('Ymd') }}
DTEND;VALUE=DATE:{{ entry.eventDate.format('Ymd') }}
LOCATION:{{ entry.eventName }}
SUMMARY:Orienteering,nr.{{ entry.map.parts.postal_town }}
END:VEVENT
{% endfor %}
{% endif %}
END:VCALENDAR";

//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
echo $ical;
exit;
?>


texts: Control panel switches to HTTPS protocol on its own

texts:
On one Craft CMS site I have, all control panel URLs I call over HTTP are rewritten to HTTPS. E.g. the login page, as well as all its assets, are being served via https://www.mywebsite.com/admin/….

The rest of the site is available via https://www.mywebsite.com/

I've already tried to enforce HTTP via mod.rewrite in .htaccess, as well as explicitly setting baseCpUrl and an new cpTrigger in config/general – with no success at all.

Is this a feature that I can deactivate? A bug in Craft CMS 2.4.2670?
Or is this a server-side issue?


texts: Exclude certain entries and its children from navigation

texts:
I need to split up a navigaton tree. So I try to exclude certain pages from a structure based navigation tree PLUS their children automatically, but don’t seem to get it.

{% nav page in craft.entries.section('pages').id('and,not 3,not 4,not 5') %}

Excluding certain entries like this works.

But:

{% nav page in craft.entries.section('pages').descendantOf('and,not 3,not 4,not 5') %}

… doesn’t return anything of course, because descendantOf needs one exact ID. But how could I manage to exclude entries 3, 4 and 5 AND all their children from the navigation without calling the exact IDs of all the children?

Thanks!


texts:
I have a custom date field - "renewalDate" - which I want to use to limit an entry query. Here is the code:

When I run that it throws this error:

"Calling unknown method: craft\behaviors\ElementQueryBehavior::renewalDate()"

{% set dateStart = now|date('Y-m-d H:i')  %}
{% set dateEnd = date('next month') | date('Y-m-d H:i')  %}

{% set list = craft.users()
.group('members')
.status(null)
.orderBy('lastName asc')
.renewalDate('and', '>= #{dateStart}', '< #{dateEnd}')

%}

However, this works fine:

{% set list = craft.users()
.group('members')
.status(null)
.orderBy('lastName asc')
.renewalDate('>= #{dateStart}')
%}

So, the problem seems to be related to using "and".

I have done this before using Craft 2, but it is not working with Craft 3. I am missing something here?

Thanks!


texts: Change Freeform redirect URL according to checkbox field

texts:
Is it at all possible to set a different Redirect URL on a FreeForm form if a checkbox is checked? To summarise, I have a FreeForm form which contains a checkbox. I would like the submission redirect URL to differ depending on whether or not the checkbox is checked.

Can anyone shed any light on this and offer some advice?

Thanks


texts:
Is there a way to repeat fields in the Craft Formbuilder (FreeForm)?
I’m working on a form on which I want to be able to have multiple names/addresses.
Rather than add a new field every time (name 1, name 2, etc.), is there a way to simply copy fields?


texts: Can visitors 'force download' images stored on Amazon S3?

texts: I have a large set of images, stored on Amazon S3. I would like my users to be able to download the original version of an image, rather then watching it in the browser. I know I can do this with PHP by setting headers and such, and I already have a plugin + controller waiting to do this, but is there an easy way to access the image data stored in S3, or should I do this directly through the S3 Class?


texts: Live Preview error when entry is disabled

texts:
When the entry is disabled, the Live Preview only shows things which are outer of the main loop. This is a part of my code:

{% include "header.html" %}
{% for entry in craft.entries.section('flashback') %}

Flashback

...
{% endfor %}
{% include 'footer.html' %}

The header and the footer are visible but the section and headline not.


texts: How do you query entries by field value for multi-select field type?

texts:
I am looking to query entries by a field value. The value will be a dynamic variable but i cannot get any results showing with hardcoded state. This is the code i have so far:

   $entries = Entry::find()
  ->section('locations')
  //->locationStates('missouri')
  ->orderBy('title asc')
  ->where(['field_locationStates' => 'missuori'])
  ->all();

I have looked at the other relevant answers and at the element query docs but i am getting nothing returning when i search with the field-type. I have also tried looping through the entries and accessing the fields like so $locationEntry->locationStates. Is it because the field-type is a multi-select that its causing some issues?
Thanks in advance!


texts: Can't duplicate a product in Craft Commerce?

texts:
I can't seem to find a way to duplicate a product in Craft Commerce.

I've duplicated articles before, with the "save as new" feature... But can't find anything similar for products.

Does such a thing exist?


texts: Sprout Forms -- Assign email selects LABEL to hidden field (jquery?)

texts:
I have a form that uses an email select form, where the label of each option is a department, and the value is the email or emails associated with that department.

It's working fine, but the notification email just lists the selected email address, and not the department selected. Because some emails are associated with multiple departments, I need to be able to show what department was selected.

There doesn't seem to be a way to customize the notification, so I'd like to add a hidden field, and assign the label of the selected email option as its value.

I tried doing it with javascript, using the code below, but it's not working:

<input type="hidden" id="fields-selectedInterest" class="selectedInterest" name="fields[selectedInterest]">

<select name="fields[imInterestedIn]" id="fields[imInterestedIn]" required>
    <option value="">I'm Interested In:</option>
    <option value="0" >Service 1</option>
    <option value="1" >Service 2</option>
</select>

<script type="text/javascript">
    jQuery(document).ready(function($){
        $(document).on('change', 'select[name="fields[imInterestedIn]"]', function(){
            var val1 = $("select[name='fields[imInterestedIn]']").children("option").filter(":selected").text();

            $("#fields-selectedInterest").val(val1);
            $("#fields-selectedInterest").change();
        });
    });
</script>


texts: How to re-populate form with old values when submitted from a controller?

texts:
I have a form in a template which makes a request to the specified action (a controller).

The controller decides that there is an issue with the inputs and needs to provide error output for the user. To do this I am using the flash error feature of Craft.

However, I'm unsure how to re-populate the form with the old values when it is next shown.

At the moment I am redirecting to the form page again using $this->redirect but the user inputs get erased each time.


texts: Setting body ID from includes does not work

texts:
This is my _layouts/main.twig:

<body {% if bodyId is defined %}id="{{ bodyId }}"{% endif %}>

  {% include '_layouts/header.twig' %}

  {% block main %}

  {% endblock %}

</body>

Then i have blog/_entry.twig with:

{% extends '_layouts/main' %}

{% block main %}

{% switch entry.entryType.entryIs.value %}
    {% case 'listing' %}
        {% include 'blog/_listing.twig' %}
    {% case 'listingSimple' %}
        {% include 'blog/_listing-simple.twig' %}
    {% case 'article' %}
        {% include 'blog/_single-entry.twig' %}
{% endswitch %}

{% endblock %}

If I do:

{% set bodyId = 'article' %}

in my blog/_single-entry.twig that does not work.

But it works if i set bodyId in my index.twig in the root that is not a include.


texts:
I am coming to Craft from Perch Runway so am trying to work out how to replicate some functionality from one to the other.

With Runway any form submissions, as well as being emailed to specified addresses, are stored on the database and viewable through the admin area.

I have installed the Contact Forms plugin for Craft (https://github.com/craftcms/contact-form) and was wondering if there is a way to do the same thing with this? Or do I need to look at another plugin / some custom functionality for this?

It is a helpful feature as emails are sometimes missed / fail to deliver etc.

Thanks!

Mike


texts:
Im trying to render a site macro from my plugin, i’m getting the following error:

Argument 1 passed to Twig_Template::display() must be of the type array, object given, called in /path/to/file.php on line 51 and defined in "_macros/elements" at line 3

My service contains the following method:

public function renderSiteMacro($template, $macro, array $args)
{
    // Get the current template path
    $originalPath = craft()->path->getTemplatesPath();

    // Point Twig at the site templates
    craft()->path->setTemplatesPath(craft()->path->getSiteTemplatesPath());

    // Render the macro.
    $html = craft()->templates->renderMacro($template, $macro, $args);

    // Restore the original template path
    craft()->path->setTemplatesPath($originalPath);

    return TemplateHelper::getRaw($html);
}

And i'm calling it as follows:

$args = array(
    'entry' => $user,
    'layout' => 'friend'
);

$userHtml = craft()->logic->renderSiteMacro('_macros/elements', 'listing', $args);

The issue appears to be with the include line in my macro template file:

{% macro listing(config) %}
{% include "_macros/elements/listing" with config only %}
{% endmacro %}

Does anyone know what i'm missing?