texts:
I created a matrix with 1 type, 3 fields for user profile. I use front-end to upload file to documentUpload field. But I got PHP warning: array_merge(): Argument #1 is not an array message. I Google it and see this issue. I did try adding

if (empty($value)) {
    $value = array();
}

But I still got the same issue. Not sure how I could resolve the issue. I see my file is uploaded to AWS S3. Looks it has issue to save it in Craft. Does anyone know how to solve it? Thanks

Here is my code to upload file:

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
 {{ getCsrfInput() }}
<input type="hidden" name="action" value="users/saveUser">
<input type="hidden" name="fields[petRecords][new{{ next }}][type]" value="records">
<input type="hidden" name="fields[petRecords][new{{ next }}][enabled]" value="1">
<input type="file" name="fields[petRecords][new{{ next }}][fields][documentUpload]" />
<input type="text" name="fields[petRecords][new{{ next }}][fields][description]" />
<input type="text" name="fields[petRecords][new{{ next }}][fields][petIdNumber]" />
<input class="btn btn-primary btn-block btn-social" type="submit" value="continue">
</form>

My Craft CMS version is 2.6.2980


texts: What is the correct syntax for using merge to create an array of field values from an element query?

texts:
I grab some values via an element query:

{% set events = craft.entries.section('events').status('live,pending').order('postDate asc') %}

But I need to put them into an array for use in a Craft-styled form field.

Twig documentation shows how to put text values in an array and merge them:

{% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %}

But how do I do this with the results of my element query?


texts:
Has anyone successfully minified Craft's HTML templates?

Had setup a Grunt task but it had parse issues with the twig template tags. I since found that the Grunt task "HTMLmin" is only for the purposes of minifying "vanilla" HTML.

Is this even possible?

Any help or direction is greatly appreciated.


texts: Flushing logs halfway through a request?

texts:
Sometimes I have long running requests that do imports or similar.

Currently logging using MyPlugin::log is only actually written to file once the request is done.

Is there a way to trigger log-flushing mid-request?


texts:
I added some date fields on my entry. I select a date and save the entry.
But the date field saved the day before.

Every editing the entry continue saving the day before. When the date comes to the 27 October it stops.

İf I select before 27 Oct it's not a problem.

This video for the problem:
https://www.loom.com/share/82cb26be003540a9ae95e1f567ca0b18


texts: Use of tag.slug instead of tag.title in a custom route

texts:
I've followed this guide for creating a routes to list entries with specific tags. It is working fine except that I have muli-word tags so using the tag token from Settings -> Routes gives me urls like

mysite.com/tags/my%20tag%20name

I'd like to us the tag.slug instead which should allow me to have urls end in .../my-tag-name instead, but I can't figure out how to do it.

Is there a way to refer to tag.slug in craft/config/routes.php?

If so what should the custom route look like:

'tags/what goes here?' => 'tags/_tag.html',

Updated

The template code is:

{% extends "_layout" %}

{% block content %}

{% set tag = craft.tags.title(tag).first() %}

{% if not tag %}
    {% exit 404 %}
{% endif %}

Entries tagged with “{{ tag.title }}”

{% set entries = craft.entries.relatedTo(tag).order('title') %}

{% if entries | length %}

        {% for entry in entries %}
            {{ include('./partials/entryListItem.html', {'entry': entry}) }}
        {% endfor %}
{% else %}

No entries could be found with that tag.

{% endif %}

{% endblock %}

and the include points to:

{{ entry.title }}

             continue reading

        {% if entry.tags | length %}

          {% for tag in entry.tags %}
            {{ tag.title }},
          {% endfor %}

        {% endif %}

The route is set in the dashboard tags/(tag token) points to tags/_tag.html

If I change the route to tags/(slug token) I get template error: variable tag does not exist.


texts: Adding a cite tag within the blockquote tag using redactor's WYSIWYG?

texts:
I have a rich text field that needs to have the cite tag within. See here:

It is currently ouputting as:

    This is the quote.

Whereas I need to work in an option for the client to create this:

    This is the quote.

        John Doe, Founder

What options are there for formatting some copy to be within the blockquote tag, but then formatting some of it to be wrapped in cite tags?

Thanks,
Jay


texts:
The issue I am experiencing is very similar to the one described here: link.  The fix described there does not work.

Here is what happens when I request a resource from that page directly using curl:

$ curl -v 'http://localhost/admin/resources/js/craft.js?d=1474612391'
*   Trying ::1...
* Connected to localhost (::1) port 80 (#0)
> GET /admin/resources/js/craft.js?d=1474612391 HTTP/1.1
> Host: localhost
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx
< Date: Fri, 23 Sep 2016 07:07:59 GMT
< Content-Type: application/javascript; charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Vary: Accept-Encoding
< X-Powered-By: PHP/7.0.8-0ubuntu0.16.04.2
< Content-Disposition: attachment; filename="craft.js"
< X-Sendfile: [CENSORED]/craft/app/resources/js/compressed/craft.js
<
* Connection #0 to host localhost left intact

Here is some version info:

Linux: 16.04 LTS (Xenial Xerus)
PHP: 7.0.8-0ubuntu0.16.04.2
nginx: 1.10.0

Here is a link to my nginx config (approximately).

Here is a screenshot of what the page looks like:


texts: New user validates without confirming email

texts:
I've built a plugin that does some work before saving the user from the standard Registration Form. My only issue is it does not fire the activation email which I added in. But it lets the user login without verification, so I'd like to know what I'm missing as I thought if I use craft()->users->saveUser() it automatically deals with this for new users. My code is as follows I think I may be missing something from the model?

$newUser = new UserModel();
$newUser->username = $username;
$newUser->email = $email;
$newUser->newPassword = $password;

$success = craft()->users->saveUser($newUser);

if ($success)
    {
        // Code added to send email
        craft()->users->sendActivationEmail($newUser);

        $this->redirectToPostedUrl($newUser);
    }


texts: Stalled / Stuck Task (GeneratePendingTransforms)

texts:
I’ve got a task running called “GeneratePendingTransforms”, but it seems to stop/get stuck just over 65% of the way through and never completes. Is there anything that could cause this

I’ve got Task Manager plugin (https://github.com/boboldehampsink/taskmanager - Which is amazing) installed to see whats happening and tried restarting the task multiple times but it gets stuck at the same point every time.

It gets stuck on Step 121 of 205.

Any ideas how I could debug this?


texts: How can I specify what happens when someone calls my fieldtype without any further dot chains?

texts:
So, I'm in the process of building a fieldtype, and I'd like to output an HTML element and some javascript when a developer calls my plugin like this:

{{ entry.fieldtypeHandle }}

The field returns an object with other methods/properties on it, but I'd like to specifically provide something different when a developer calls my fieldtype without any other chaining.

I've tried pass a class with a __toString() method, but it just returns a string. (I don't know what I expected, honestly.) I also know that coupling the HTML output with the class seems a bit dirty, even if that did work.

Is this possible?


texts:
I'm using Matrix and Neo to build out quite large, complex entries.
On larger pages (70+ blocks each with one-multiple sub-blocks) the performance is taking a bit of a hit taking upwards of 40 seconds to load (locally running PHP7).

Any thoughts on speeding this up at all, eg selectively loading/collapsing blocks as required rather than load in everything onto the page?

Thoughts/suggestions appreciated,

Cole


texts: Change base URL for email activation link?

texts:
I am using Craft as a headless CMS and have set base Url/siteUrl to the url of my React/Gatsby site.

I needed to do this as my navigation plugin, Navie, appends it by default.

But now when users registers, they are sent an activation email with the Gatsby url.

How can I change this?

Thanks


texts: Conditional for user registration fields

texts:
What’s the best way to validate a user registration form to make sure that at least one of two fields is not empty?

I’ve tried a very simple controller but can’t get this to work past the point of trying to save the user. Any pointers with this method or for a different method entirely?

public function actionIndex() {

    $this->requirePostRequest();

    $fields = craft()->request->getPost('fields');

    $customField1 = $fields['customField1'];
    $customField2 = $fields['customField2'];

    $user = new UserModel();
    $user->email = craft()->request->getPost('email');
    $user->password = craft()->request->getPost('password');
    $user->setContentFromPost('fields');

    if ($customField1 != '' || $customField2 != '') {

        // RETURN CUSTOM ERROR

    }

    // OTHERWISE SUBMIT USER REGISTRATION REQUEST
    // AND RETURN ANY ERRORS

    craft()->users->saveUser($user);
    $this->redirectToPostedUrl();

}


texts:
One of my sites does not send mail. When testing the email settings (using the test button at the bottom of the email settings page), I get an error. My log file shows this error thrown in Mailer.php.
[-][1][-][error][Swift_TransportException] Swift_TransportException:
Expected response code 354 but got code "554", with message "554 5.5.1 Error: no valid recipients
in /var/www/vhosts/xxx.be/public_html/yyy.be/craft/vendor/craftcms/cms/src/mail/Mailer.php:182

My mail settings:

System email address: info@yyy.be
Transport type: SMTP
Host: yyy.be
Port: 25
No verification
No encryption method

Is this due to my email settings? I always use similar settings who usually work (different hosting provider though).


texts: Asset uploads failing on new installation of Craft CMS

texts:
New (local) installation of Craft on Mac OSX Yosemite, working well except uploading an asset doesn't complete. The progress bar hangs and the spinner never stops spinning.

Craft index.php is located in /Users/Penguin2/Sites/craft.dev/
Craft application files are in /Users/Penguin2/Sites/craft/
PHP open_basedir is /Users/Penguin2/Sites/

The PHP log indicates the following:

[21-Jan-2015 18:04:02 UTC] PHP Warning:  Unknown: open_basedir restriction in effect. File(/var/tmp/) is not within the allowed path(s): (/Users/Penguin2/Sites) in Unknown on line 0

I assume I need to change the location where Craft stores temp files to a directory under the PHP open_basedir but I can't find the setting anywhere.

Thanks!


texts: Conditionally apply a tax zone in commerce

texts: Many of the customers we'll be selling to are tax-exempt entities. We're located in OH, so for OH customers we're applying sales tax through the Tax Zone setup in Commerce. Is there a way to not apply the tax based on some conditional, even though their billing address is in OH?


texts: Looking to export product listings from Salesforce and importing into Craft Commerce?

texts:
I've been trying to find an approach where one could import product listings from Salesforce directly into one of my product types in Craft Commerce. It seems like my only option at this point is to write a plugin that can accomplish this. I recently found a post that mentioned that I would need to use the Salesforce PHP Toolkit to effectively make REST API calls from my platform.

The only issue is I don't know exactly where to start.  Can anyone provide some suggestions or advice on how to handle this problem?


texts: “Request missing required body param” error when creating entry on front end

texts:
I get an Request missing required body param error when trying to create a new entry on the front end. All required fields are being filled. Nothing changed except the craft version. Craft version is 3.2.0-RC2.

Has that something to do with the way drafts are handled in 3.2?

Edit:
Looks like Craft wants a entry id:

/…/controllers/EntriesController.php(848): craft\web\Request->getRequiredBodyParam('entryId')

Which, of course, is not available when creating a new entry. What is to be done?


texts:
I am using Michael Rog's Calendar plug-in and am trying to pass the calendar ID to an include.

Parent template:

{% include '_includes/_calendar' with {'calendarId': '1'} %}

_includes/_calendar:

{% set params = {
    calendarId: '{{ id }}',
    dateRangeStart: 'today',
    dateRangeEnd: '+36 months'
} %}

{% for entry in craft.calendars.eventData(params).events %}

        <time>{{ entry.startDate  | date("D d M") }}</time>

{{ entry.element.title }}

        {{ entry.element.eventDescription }}

{% endfor %}

I am not getting any results for that.

If I change the params to

{% set params = {
    calendarId: '1',
    dateRangeStart: 'today',
    dateRangeEnd: '+36 months'
} %}

I get the results for the correct calendar.

I haven't used includes with variables like this before. Where am I going wrong?


texts:
We have a very strange issue here. On my computer I'm trying to save an entry. The process indicator keeps spinning for about five minutes before this exception comes up:

CDbException
CDbCommand faalde tijdens het uitvoeren van volgend SQL statement: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away. The SQL statement executed was: SELECT `locale`
FROM `craft_locales`
ORDER BY `sortOrder`

It's triggered by this function:
$this->userSession->checkPermission('accessCpWhenSystemIsOff')

On first look this definitely looks like a server issue. But... when I test this on a windows computer, it never happens. It's just not saving from an osx computer (browsers tested on osx: chrome, safari, firefox). Also tested on different osx computers and different windows computers. All with the same result. Windows works, osx doesn't.
Does anyone have a clue what might be going on here? Thanks!


texts: How can I get field data for the current locale in a plugin?

texts:
So I have a plugin with a service. Part of the service function is to grab a field (body) from an entry object that has been passed into the function.

<?php
namespace Craft;

class MyPlugin_ExampleService extends BaseApplicationComponent {

    public function example($entry) {
        return $entry->body;
    }

}

The function will be called via Twig.

{{ craft.myPlugin.example(entry) }}

How do I go about getting the field data for the users current locale?


texts: Can the HTTP status be set with the redirect tag

texts:
Although undocumented, according to this answer How do I force a 301 http status code using the redirect tag? adding a 301 parameter to the redirect tag should change the status. I am using this but am still getting a 302 status.

{% redirect entry.getChildren().first().url 301 %}

Should this work to create a 301?


texts: How to get submitted data in Sprout Forms custom email

texts:
I've setup a custom email notification that is sent out after submitting a form. I want to have a set message but with a personalised greeting "Hi Bob". I have the email.html file and that works but I can't figure out how to display the persons name. In my example the field handle it yourName and the form handle is contactForm.

Is this possible?


texts:
I have a redactor field whose HTML contents contain links to other parts of the website.

How do I render variables located in the HTML content of a Redactor field in Twig?

Sample redactor content:

About

Contact

In output of this results in the braces being encoded:

About

Contact

But I want it the output to be whatever siteUrl is. Eg on localhost:

About

Contact


texts:
I am posting this in case anyone will encounter this problem. I also reported a potential bug about that. (see here: https://github.com/craftcms/cms/issues)

When you start to suddenly get redirection loops with HTTP-302 redirects to our own page, you might want to check your loginPath value in general.php.

After we spent hours investigating into the usual .htaccess and other places for redirection loops, we eventually figured out, that loginPath set to '/' will cause that behaviour.

We wanted to redirect users to the homepage if they were not logged in and tried to access a page that required a login.

Our setting was:

'loginPath' => '/'

which proved to cause the redirection loop.

The correct setting instead was:

'loginPath' => ''

I hope this saves somebody else from future pain :)


texts: "Forbidden" response when saving entry with HTML code in matrix field

texts:
I have a matrix field which the user can paste YouTube etc. embed code into, which is working fine with YouTube, but SoundCloud embed code causes it to return a page which simply says "Forbidden".

I've tried every combination of plain text, rich text, purify & clean HTML etc.

Trial and error has shown the problematic part of the embed to be this:

width="100%" height="166"

However I can't seem to pin down which part of this is actually the problem.

I tried a few variations to try to see what's going on...

The following fragments are saved fine:

%" h
w="100%" h
w="100%" h=
w="100%" h="
"100%" h
100% 166
width="100%"
width="100" height="166"
width=100% height=166

The following are not saved and return Forbidden:

width="100%" height="166"
w="100%" h="166"
w="100%" h="1
100%" h="1
"100%" "166"
width="1%" height="1"

I've tried pasting the same SoundCloud embed into various other fields across the site, it's fine everywhere else.

Curious!


texts: How do I toggle list/grid view on section index page without affect category filtering

texts:
I have a section "projects" with entry type (projectPage) with and an index page set up displaying a grid view of entries.  I have also set up category filtering via links to the {{category.url}} which point to the projects/index template.

I want to add another entry type (projectList)  that will have entries that
1. have only title and category relationships defined
2. do not have their own url.

I want to add a toggle button to the page that will change the display from a grid view to a list view combining the (projectPage) entries and (projectList) entries, but I want it to remain in effect as you cycle through the categories, until it is deselected.

I had some success setting  up a route to projects/list  that filtered the entry types based on the url with   {% if craft.request.getSegment(2) == link %}

but the relationship brakes when I click on a category link.  I'd prefer to have everything in the same template file and not add the "list" to the url if possible.

Currently I'm think that to hide the (projectList) entry URL's I'd have to set up another section "projectListings"  and set up routes  for project/list to point to the new index template and add routes for each category for project/list/{{cat}}  but I'm hitting a roadblock as to if this is the best way to go about it, and how exactly to implement it.

Hopefully this is not too broad a question, as I could use a little direction.  Thanks.


texts:
Based on this interesting article: DRY templating with Twig and Craft CMS. I found myself trying to update the approach with include instead of macro following reading I had about twig 2 and craftcms 3.

So basically there is my component

_hero-banner.twig

{# Defaults #}

{% set defaults = {
    heroTitle : title is defined ? title : 'Title not set',
    titleColor : color is defined ? color : null,
    heroImage : image is defined ? image : null,
    heroButton : button is defined ? button : null,
    heroClasses : classes is defined ? classes : null
  }
%}

{# Options #}

{% set options = options is defined ? defaults|merge(options) : defaults %}

{# Variables #}

{% set imageMobile = {
    mode: 'crop',
    width: 640,
    height: 500,
    quality: 75,
    position: 'focus-point'
} %}

{# Output #}

      {# Display the entries #}

{{ options.heroTitle }}

            {% if options.heroButton %}
              <button type="button" class="o-button o-button--primary"> {{ options.heroButton }} </button>
            {% endif %}

And there is my include

index.twig

{% set heroBannerOptions = {
    title : homepage.mainTitle,
    image : homepage.heroBanner,
    color: true
  }
%}

{% include 'components/_hero-banner.twig' with { options : heroBannerOptions } %}

Somehow I cannot pass the variables into the component and I cannot figure out why...


texts: Use default field type(s) within my plugin

texts:
I am just experimenting with plugin development and would like to use the existing dateTime field type. For no other reason than to maintain consistency throughout my application.

Is there a way to call that field as a macro (for lack of better words) in my template or do I just view the generated source from one spot and copy/paste it into my templates?

Thank you!


texts:
I've setup a Craft 3 site for a client and we are seeing the strangest thing where pages are just disappearing. Best we can tell no-one has deleted the entry, but we get a 404 on the front-end and it is not showing up on the back-end, even under "Trashed". What is weird is that when I re-create the page I can't use the same slug so it seems like it is still in the database. I've tried querying the database and I can see rows in the elements_sites table with that uri, but I don't know enough about the data scheme to tell where the disconnect is or tables to look at to determine which is the "live" version. One other note that may be related is several pages disappeared that were all sub-pages to a parent page (but the parent page is still there on the site)
Here is a query I ran for one of the pages that is missing:

Any suggestions for how to figure out what is happening or a query to run to determine which pages are live and where the disconnect may be for those pages?


texts: Only fetch categories that are related to a minimum of entries

texts:
Is there a way to only fetch categories that have been assigned to a minimum of entries, i.e. 4?

Currently I fetch categories like this:

{% set productIds = craft.entries.section('products').ids() %}
{% set categories = craft.categories.relatedTo({ sourceElement: productIds }) %}

I know I can now do the following to only display content for categories which have been assigned to at least  four entries:

{% set entries = craft.entries.section('products').relatedTo(category) %}
{% if entries|length > 4 %}
  ...
{% endif %}

But is there a way to apply this logic to the craft.categories query?


texts: Can't get correct template for ajax call

texts:
Background: I've inherited a site built in craft that has a page called "updates" with a button to load additional entries through ajax. The updates page is an entry in the "page" structure and when it's template is called it loads entries stored in a channel also called "updates". The template the "pages" structure points to is pages/_entry.html, and this holds the logic for gathering entries stored in the "updates" channel. However, the ajax script calls /updates/q?param=1 which is somehow calling the template updates/index.html. All while the channel is set to call template entries/_entry.html for the individual entries in the channel.

So I tried to create a blog page that would work the same way. I created an entry in the "pages" structure called blog, then created the template blog/index.html which is the same as updates/index.html. The ajax script calls /blog/q?param=1 but it returns a 404. I even created a channel in the cms called blog wondering if that was the case but it hasn't helped. What does the url need to be to return blog/index.html?

pages/_entry.html

{% extends "_layout" %}
{% block content %}
{% set myJs %}
window.entryType = '{{ entry.type }}';
{% endset %}

{% includeJs myJs %}
{% cache unless craft.config.devMode %}

  {% if entry.type != 'contact' %}
    {% include ['_partials/_page-header-' ~ entry.type, '_partials/_page-header'] %}
  {% endif %}

  {% include ['_partials/_page-content-' ~ entry.type, '_partials/_page-content' ] %}

{% endcache %}
{% endblock %}

updates/index.html

{% if craft.request.isAjax %}
  {% set layout = "_ajax" %}
{% else %}
  {% set layout = "_layout" %}
{% endif %}

{% extends layout %}
{% set title = 'Updates' %}
{% block content %}

{% cache for 3 hours unless craft.config.devMode %}
  {% if craft.request.isAjax %}
    {% include '_partials/_get-updates' %}
  {% else %}
    {% set entry = craft.entries.slug('updates').featuredUpdate %}

        {% include '_partials/_updates-filter' %}
        {% include '_partials/_grid-cards' %}

          Load More

  {% endif %}

{% endcache %}
{% endblock %}


texts:
It seems that after x amount of time (somewhere between 30-60 mins?) of inactivity on a page the session is being destroyed/cleared/etc.

I will sit on a page with an active session for an hour and make 0 calls to the PHP. The next time I make a call to my PHP the session is completely gone. I have 0 variables in my session. I'm logging in the beforeAction and the session is just an empty array.

I thought it was my custom code that was clearing the session accidentally but before my code even executes the session is gone which leads me to believe it has something to do with Craft bootstrapping up to receive the PHP request.


texts:
I'm making a staff page. The entries are in the section 'people'.
There are four types of staff - leadership, wardens, staff, safeguarding - so there is a category field for each 'staffCategory'. That category field can have more than one category selected e.g. someone can be categorised as both warden and safeguarding.
I'm outputting each staff via an if statement:
e.g.
{% for entry in entries %}
{% if entry.staffCategory.one() == 'Leadership' %}
All is outputting fine except when I come to the last staff type: safeguarding.
One of the people in safeguarding is also a warden.
They are output on the page as a warden but not in the Safeguarding section. All the other people in safeguarding as output without a problem - but they aren't in multiple categories.
If I remove warden from their safeCategory field in their entry, they appear in Safeguarding. But if I have both safeguarding and warden selected they appear ONLY in the warden part of the page.


texts:
Is there a way to get all available image transforms in a template?
I would like to generate the srcset for responsive images programmatically.

I thought of creating a macro for that but haven't found any information about how to loop over all the registered image transforms.


texts: How can I change the rich-text editor to remove the "Heading 1" option

texts:
I want to remove the option to add a H1 from the dropdown in the Redactor rich-text component. I have edited the Standard.json file in craft>config>redactor to the below but it still hasn't done the job:

{
    "buttons": ["format","bold","italic","lists","link","horizontalrule"],
    "plugins": ["source","fullscreen"],
    "formattingTags": ["h2","h3","p","blockquote"]
}

I followed instructions from this page, but it looks like "formattingTags" doesn't work. Anyone know how to fix this?


texts: How to display an entry id multiple times?

texts:
I've set up a print template for furniture labels.
I let my client print the labels with a special Link like

/label?ids="x|y|z"

It all works good. Now he sometimes wants to print the same label multiple times, so he and I tried the following:

/label?ids="x|x|x|y|z|z|z"

The underlying code is the following:

{% set ids = craft.request.param('ids')| split('|')|join(',') %}
{% set params =
    {
        section: 'furniture',
        limit : null,
        id: ids

    }
%}
{% paginate craft.entries(params) as entries %}
{% for entry in entries %}
     ...
{% endfor %}

This will only display x and z one time.

Is there a way around this?

Any help appreciated.


texts: Filtering multiple categories with URL queries

texts:
I am trying to filter using categories. I have to filters type and size, in the url.

/products.html?size=medium,large&type=polo-shirt,jeans

In my template, I am doing the following

{% set sizes = craft.app.request.getQueryParam('size') %}
{% set types = craft.app.request.getQueryParam('type') %}

{% set relationParam = ['and'] %}

{# type #}
{% if types %}
  {% for i in types|split(",") %}
    {% set type = craft.categories.group('types').slug(i) %}
    {% set relationParam = relationParam|merge([{ targetElement: type }]) %}
  {% endfor %}
{% endif %}

{# sizes #}
{% if sizes %}
  {% for i in sizes|split(",") %}
    {% set size = craft.categories.group('sizes').slug(i) %}
    {% set relationParam = relationParam|merge([{ targetElement: size }]) %}
  {% endfor %}
{% endif %}

{# Avoid passing an array with `['and']` only #}
{% if relationParam|length < 2 %}
  {% set relationParam = '' %}
{% endif %}

{% set entries = craft.entries({
    section: 'products',
    relatedTo:  relationParam
}) %}

<div class="listings-container">
  {% if entries|length %}
    {% for entry in entries %}
        {% include "partials/_listing.html" %}
    {% endfor %}
  {% endif %}
</div>

The problem I'm having is as follows:

I click on “medium” in sizes, it shows all products that have the category “medium”
I then, click on “large” in sizes, it shows one result because it’s searching for products that have all 2 categories (“medium”, “large”)
I then click on "polo-shirt" in types, this now shows all products that have all 3 categories (“medium”, “large", "polo-shirt")
I then click on “jeans” in sizes, this now shows no results as its trying to find products that have all 4 categories (“medium”, “large", "polo-shirt", "jeans")

What I am trying to achieve is find all the products that are “medium” or “large" sizes and of "polo-shirt" or “jeans” types


texts:
If I have a lineItem that needs some validation, for example on an option or note filed, how do I show potential errors in a template and repopulate the form with the posted values?

In addition, I’m working with a template that has multiple products on a page and uses MulitAdd to add items to the cart.

I’m validating lineItem data using onBeforeSaveLineItem and adding the error with something similar to $lineItem->addError('text','This is required');.


texts: craft()->locale->getTimeFormat() throws Fatal error

texts:
When requesting the control panel I get the following error:

Fatal error: Call to a member function getTimeFormat() on a non-object in
/craft/app/etc/requirements/RequirementsChecker.php on line 103

Apparently  craft()->locale is null, but I have no idea why this is the case. I'm running craft locally, on http://[PROJECT].craft.dev/ and installed the Pro version.

Any ideas?

Edit: this turned out to be a too restrictive gitignore file, ignoring the craft/app/framework/i18n/data folder


texts: How do I access AJAX data within a controller method?

texts:
I have a JavaScript file which sends an array of data to a controller:

Craft.postActionRequest('wineNotes/wineSpreadSheet/saveWines', data, ...)

The structure of the data variable is as follows:

var data = {
    Data: sData
}

... where sData is an array of temp variables sData(temp1,temp2,...) and the structure of each temp object is like this:

temp = {
    "wine":        ht.getDataAtCell(i,0),
    "country":     ht.getDataAtCell(i,1),
    "region":      ht.getDataAtCell(i,2),
    "note":        ht.getDataAtCell(i,3),
    "tastingdate": ht.getDataAtCell(i,4),
    "rating":      ht.getDataAtCell(i,5),
    "maturity":    ht.getDataAtCell(i,6),
    "conclusion":  ht.getDataAtCell(i,7)
};

How can I access the parameter temp.wine for each temp in the sData array within the following method of my controller?

public function actionSaveWines()
{
    // ???
}

I know the data structure is kinda wierd its actually an array of arrays. Read the below code and you might understand.

for(i=0;i<NumRows;i++)
        {
            temp = {
                "wine":ht.getDataAtCell(i,0),
                "country":ht.getDataAtCell(i,1),
                "region":ht.getDataAtCell(i,2),
                "tastingdate":ht.getDataAtCell(i,3),
                "rating":ht.getDataAtCell(i,4),
                "maturity":ht.getDataAtCell(i,5),
                "conclusion":ht.getDataAtCell(i,6),
            };
            sData.push(temp);
        }

        var data = {
            Data: sData,
        }
        Craft.postActionRequest('wineNotes/wineSpreadSheet/saveWines', data, function(response) {

        });


texts: How can I retrieve number of times an entry has been updated since postDate

texts: For a news site I would like to retrieve the number of times an entry has been updated since postDate. Is that possible without using a plugin? Im using craft pro and have versioning enabled for that section.


texts: Image Optimize Field - adding ImOp field to a volume causes images in that volume to not be found

texts:
Steps I've taken to configure Image Optimize

Installed plugin, configured binaries (green checkmarks all around)
from the CLI, ran ./craft resave/assets - all assets resaved and successful example: - Resaving Female (474749) ... done
created new OptimizedImages field "Optimized Images Field (Square)"
assigned this field to the Asset Volume Field Layout for our site content
from the CLI, ran ./craft resave/assets- all assets from that volume now are unable to be found
- Resaving Female (474749) ... error: The file "female.jpg" does not exist.

similarly, the CLI command for the plugin to run variants breaks the same way:

running ./craft image-optimize/optimize/create results in:

196/213 - processing asset: Female from field: Optimized Images Field (square)
[error]: The file "female.jpg" does not exist. while processing 196/213 - processing asset: Female from field: Optimized Images Field (square)

We've cleared caches, tried on fresh volumes, etc... same results whenever we add the Optimize Image Field to the volume.

We are still able to create front-end variants in twig, but none using the ImOp field.

  Craft CMS 3.4.15
  Image Optimize 1.6.12

Any recommendations on where to go from here?  Thanks in advance for any help.


texts: Multi Country website - Using locales is the best approach?

texts:
I will work in a website that have presence in 3 countries: Nicaragua, Panama, Costa Rica. They will upload products and want that each country have they own product or product information.

So i think about locales to organize the website, to give 3 different contexts to load information, and the ability to change a existing product for each country.

My question is: this 3 countries speaks Spanish, and i want to clearly show the client which country he is editing- Can i duplicate the Spanish locale and put the country name on each one ( to show PANAMA-COSTARICA-NICARAGUA ) ? I see the list of locales but i don´t know if this 3 countries are available...
Thanks!

Sebastian.


texts: Output Matrix Block with Element API Plugin

texts:
Below is my code to output the news entires under the "news" section of my site using the Element API. My question is how do I output the matrix block with a block type of "text" with a field called "blockText"?

https://craftcms.stackexchange.com/qcuestions/13118/how-do-you-use-the-element-api-plugin-to-output-matrix-blocks-for-an-entry

<?php
namespace Craft;

return [
    'endpoints' => [
        'api/entries' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function(EntryModel $entry) {
              // Check to see if there are any images
              $featuredImage = $entry->featuredImage->first();
              $bodyBlocks = [];
               foreach ($entry->bodyEnhanced as $block) {

                   switch ($block->type->handle) {
                       case 'text':
                           $bodyBlocks[] = [
                            //'text' => $block->type->attributeConfigs,
                            'content' => $block->type->bodyText
                           ];
                       break;
                   }
               }

                return [
                    'id' => $entry->id,
                    'url' => $entry->url,
                    'postDate' => $entry->postDate,
                    'title' => $entry->title,
                    'excerpt' => !empty($entry->excerpt) ? $entry->excerpt : false,
                    'image' =>   !empty($featuredImage) ? $featuredImage->url : false,
                    'body' => $bodyBlocks,
                ];
            }
        ],
    ],
];

This is the only line that is breaking my JSON. Any help would be greatly appreciated.

'content' => $block->type->bodyText


texts: Recommendations on integrating Craft 3 and FormAssembly

texts:
I was wondering if anyone could give me some advice.

We have a client that we are in the process of moving away from a Drupal build to a new Craft build, however, they have a large number of forms created in FormAssembly that sync nicely with Salesforce. Does anyone have experience with Craft/FormAssembly integration specifically rolling their own plugin or using the HTTPS Connector?

The client doesn't want to have to recreate all the forms, so using a plugin like Freeform isn't really an option.

Any other insights greatly appreciated.


texts: How can I add fields in the Sprout design your form?

texts:
I am using Craft CMS 2.7.3 and sprout forms 2.6.0 version.

I have created a dropdown field in the craft cms -> fields. How can I fetch this field or render this field in the Sprout form design?

Even if I create a tab and save it. It doesn't get saved.


texts: Search result based on a specific field in a related entry in a matrix

texts:
On this product list page: https://www.alfa.no/shop/skisko/ I need to add a size filter, to only show products that are size 45 for example AND that are in stock.

The structure is built with products and productVariants in separate channels, and productVariants (individual shoe sizes) are added to the product inside a matrix field (colorVariants), with sizes as related productVariants entries to each color. All those words look a little something like this:
https://www.dropbox.com/s/2kyvfxq7xv843v6/Screenshot_2014-10-23_09_53_00.png?dl=0

So what I need in the template is to search for products that have a related productVariant in the colorVariants matrix, matching 45 in the variantSize field AND > 0 in the variantStock field.

I have only come as far as being able to list products that match the size in the matrix, with a way too simple search. It searches for the size in the colorVariants matrix field, but the approach is not targeting specific fields, like stock, in the related productVariants entries in the colorVariants matrix:

{% set filteredProductList = productList.search('colorVariants:45') %}


texts: Setting the page title for a category page

texts:
I am trying to get the page title of the categories page. Currently it shows as: category-name, but I would like to have it set to Category Name to match the category.title.
My categories/index.html looks like this:

{% set title = category %}

{% block content %}

    {% set entries = craft.entries.relatedTo(category) %}

    {% for entry in entries %}

        -- Code Here --

    {% endfor %}

{% endblock %}

Thanks in advance.


texts: Craft 3 Plugin - Only default action works

texts:
I'm working on a Cloudflare integration plugin for Craft 3. I set up the plugin with settings, which works fine so far. Now I intended to verify the Cloudflare credentials using an AJAX call.

I set up a controller at controllers/DefaultController with a method named actionFetchZones:

class DefaultController extends Controller {
    protected $allowAnonymous = [ 'fetch-zones' ];

    public function init() {
        parent::init();
        $this->defaultAction = 'fetch-zones';
    }

    public function actionFetchZones() {
        return $this->asJson( Plugin::getInstance()->cloudflare->getZones() );
    }
}

I registered the action in the plugin class:

// register the actions
Event::on(
    UrlManager::class,
    UrlManager::EVENT_REGISTER_CP_URL_RULES,
    function( RegisterUrlRulesEvent $event ) {
        $event->rules['POST cloudflare/zones'] = 'cloudflare/fetch-zones';
    }
);

But the response is

POST https://host.tld/admin/actions/cloudflare/zones 404 (Not Found)

When I request /admin/actions/cloudflare instead, I receive a 200 response.

The plugin handle is set to cloudflare, the app works fine otherwise. What am I doing wrong?

Edit: As requested, below is the AJAX call:

Craft.postActionRequest(
  'cloudflare/zones',
  { apiKey, email },
  (response, textStatus, request) => { /* ... */ }
);


texts: How do I add an HTML block from template extension to main layout template? (i.e. meta data)

texts:
I have a main layout file and extending it with another template. I have my markup and content in the {% block content %}{% endblock %} however, I'd like to add content to another "block" on the individual entry page for meta data - that would require adding another {% block content %} to my template as it would need to be output in a different area of the layout template.

Essentially, is there a way to add a second block (perhaps name it differently) or is my best bet to set all that meta data as a variable and pass it that way?


texts: Charge plugin redirecting to page with "1" on it

texts:
I've been trying to figure this out for a couple days now and haven't been able to. I'm using the Squarebit Charge plugin to accept donations on a website.

I have everything working fine on my local Vagrant machine. However, when I push it to my staging server, the redirect to the "thank you" page never works. Instead of redirecting to the thank you page, the Donate page is reloaded and displays a single "1".

Does anyone have any ideas? I do get a TypeError in console because the card expiry date field had to be changed. Stripe would complain that the card exp_month field wasn't present so I had to create that field. I get the error on my Vagrant box too so I don't think it's causing the process to fail.

My staging link is here: kb.topsdev.net/donate

Any help is really appreciated.


texts:
Is there a simple way to opt out of the translation that occurs when you format a date like this:

{{ expiry | date('D, d M Y H:i:s', 'GMT') }}

The problem is that I need this in english to create a valid date for my HTTP headers. But the site is in norwegian so days and months are translated, resulting in an invalid date.


texts:
As this tip (Twitter) suggested we can use type hints for Twig in PHPStorm after installing Symfony Support plugin by utilizing its PHPTypes feature, for example putting:

{# @var craft \craft\web\twig\variables\CraftVariable #}

at the top of a template would auto-complete all properties and methods in craft.abc for us.

Type hints for plugins?

How could we get auto-completion for plugin variables?

Let's have a look at the Imager plugin. It is accessible via craft.imager. If I put

{# @var imager \aelvan\imager\variables\ImagerVariable #}

at the top of the template the IDE actually auto-completes for me when I type imager.abc, however this obviously throws an error because Craft expects craft.imager.abc. But the IDE doesn't autocomplete craft.imager.abc.
I also tried

{# @var craft.imager \aelvan\imager\variables\ImagerVariable #}

which is not working.

Ugly workaround

If I put craft.imager into a local variable the auto-completion is working:

{# @var imager \aelvan\imager\variables\ImagerVariable #}
{% set imager = craft.imager %}
{% imager.transformedImage(...) %}

Any hints? hahaha


texts: Why is htaccess file not named ".htaccess" on fresh install?

texts:
I run into the same error on each project setup with CraftCMS. So did I this time… again…

First of all: Yes, I seem to be a slow learner. And therefore I can't memorize to rename the htaccess file before calling the Craft installer page. ;)

When downloading CraftCMS the .htaccess file is called htaccess (without leading dot).
So, whenever I setup my Craft projects I have to rename the file that is located in /public.

But I always forget about that. I always run into the problem that I get a "503 Service Unavailable" on requesting my new website using Craft. On requesting the admin panel (to start the installer) I get a "404 Not Found". Then I only wonder and ask myself if I have made something terribly wrong…

Only after some hard thinking about what's going on there I come accross the solution:
Rename htaccess to .htaccess. Apache is not recognizing the one without dot.

This is happening always (and by "always" I mean each and every single time I start working on a new Craft project) to me and it's totally bothering me.

Why can't Craft jsut come with a correctly named .htaccess file?

Is the public htaccess file maybe named without the leading dot to not be hidden on operating systems like MacOSX? So you can copy files from folder to folder without missing hidden ones?
I mean, Craft is made for developers. Come on, guys. Developers should know to have in mind hidden files when copying them to a new project's destination.

So, why just not delivering Craft with .htaccess in /public folder instead of htaccess?

I guarantee you guys that I will forget about the renaming again before calling the URL of my next Craft project.


texts:
I am using Sprout Forms for my contact forms and I want to integrate the MailChimp subscribe plugin but it looks like the MC Subscribe plugin needs to have name="mcvars[FIRSTNAME]" on the input fields and Sprout Forms needs name="fields[LASTNAME]".

Also, they have different hidden fields for the action:

MailChimp Subscribe

<input type="hidden" name="action" value="mailchimpSubscribe/list/Subscribe">

Sprout Forms

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

Has anyone managed to integrate the two so people can choose to subscribe to a list while also using the power of Sprout Forms?


texts:
I'm getting a 500 error when trying to visit my page. Was able to track it down to this error in the logs, but can't seem to get it fixed. Updated the craft/app folder with the latest Craft version, but still no luck.

From my phperrors.log

[14-Mar-2017 17:56:34 UTC] PHP Fatal error:  Uncaught Error: Class 'Craft\DbConnection' not found in /var/www/site/craft/app/etc/behaviors/AppBehavior.php:849


texts: Edit select dropdown field in a Matrix on the front-end

texts:
Having a front-end user form where users can maintain there profile. I managed to get the single text and date field in the Matrix to be edited from the front-end but having issues with the select dropdown fields in the form.

The select dropdown is build up correctly but selected values won't save, in fact the existing value is cleared after submitting the form.

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="mijnduikteam/gegevens/{{ currentUser.username }}">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    <input type="hidden" name="fields[userDivingCertification]" value=""

                        Type
                        Certificaat #
                        Datum</th

                    {% for block in currentUser.userDivingCertification.order('certificateDate desc') %}
                    <input type="hidden" name="fields[userDivingCertification][ {{ block.id }}][type]" value="certifications">
                    <input type="hidden" name="fields[userDivingCertification][ {{ block.id }}][enabled]" value="1">

                                <select class="form-control" type="text" name="fields[userDivingCertification][ {{ block.id }}][fields][certificateType][]">
                                {% for option in block.certificateType.options %}
                                <option {% if option.selected %}selected="selected"{% endif %} value="{{ option.value }}">{{ option.label }}</option>
                                {% endfor %}
                                </select>

                                    <input class="form-control" type="text" name="fields[userDivingCertification][ {{ block.id }}][fields][certificateNumber]" value="{{ block.certificateNumber }}" >

                                    <input class="form-control" type="text" id="datetimepickerCertificate" name="fields[userDivingCertification][ {{ block.id }}][fields][certificateDate][date]" value="{{ block.certificateDate| date('d-m-Y') }}" aria-describedby="basic-addon4" >

                     {% endfor %}

                <input role="button" class="btn btn-primary" type="submit" value="Wijziging bewaren">

    </form>


texts: Displaying Craft User Profile based on First and Last Name

texts:
I don't want to ustilise the username or the ID of a user to get their profile info so I am using their first and last name. So far I can fetch the user based on first name:

{% set slug = 'first-last' %}
{% set firstNameSlug = slug|split('-')[0] %}
{% set lastNameSlug = slug|split('-')[1] %}

{% set user = craft.users.firstName(slug).first %}

How do I build on this code to fetch using the first name AND last name?


texts: Batch assigning a certain category to existing entries

texts:
I have a few 1000 existing entries and just introduced a new Category type. And I would need to assign all existing entries, to a certain category.

I've been looking in the MySQL databases what exactly is going on, so I could reproduce it with a query directly in there, but can't seem to pinpoint exactly what I would need to update.

Any ideas?


texts: 404 error on entry template in dev tools, but layout template loads

texts:
I created a Shop page here: https://www.intermountaincleaning.net/shop/products/diamond-magic. The rest of the site is just static HTML (not Craft), and the Shop page is in a Shop folder within the public_html for the site.

Craft is pulling in the correct _layout file, and it's including the _nav and _footer, but if you open dev tools there's a 404 error on the products/_product template.

I'm staging the site here, and it's working just fine with the same templates: http://diamondmagic.jonathanweedin.com/shop/products/diamond-magic.

I can't figure out why Craft isn't pulling in the products/_product template. Attaching screenshots of my CP area, Craft folder, and public_html folder.

Any guidance would be much appreciated. Thank you!

config/general.php

<?php
    return array(
        'siteUrl' => 'intermountaincleaning.net',
        'environmentVariables' => array(
            'baseUrl' => 'intermountaincleaning.net'
        ),
        'defaultWeekStartDay' => 0,
        'enableCsrfProtection' => true,
        'omitScriptNameInUrls' => 'auto',
        'cpTrigger' => '***********', // I'm ommitting this from StackExchange
        'devMode' => true,
        'tokenParam' => 'paypalexpress',
    );


texts: Loop over table field in Element API plugin

texts:
How can I output the rows and values of a table field using the element api plugin?

Where I have entries I do

...
$industries = [];
foreach ($entry->industries->all() as $industry) {
  $industries[] = $industry->title;
}
...
return [
    'industries' => $industries
];

but ->all() doesn't work in the scenario of a table.


texts: Get entries which have a certain category assigned to them

texts:
So, i have a channel called images and a couple of category groups one of which is called "images" which has categories called family, animals, individuals in it.

So, i just want to grab the entries that have one of those categories assigned / related to them.

Figured something like this would do it

    {% for entry in craft.entries.section('images').relatedTo('photography').find('family') %}
        <h3>{{ entry.title }}</h3>
    {% endfor %}

But i figured wrong! Any ideas would be gratefully received!


texts: Getting a mixed content warning when trying to login, '/actions/users/login' is being requested over http

texts:
We are getting a mixed content error when trying to login to our dashboard.  Site settings all reference https – have tried nearly everything I can think of relative to making sure that all references to the site are via https.
Mixed Content: The page at 'https://xyz.com/z43sgRn/login' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://xyz.com/index.php?p=z43sgRn/actions/users/login'. This request has been blocked; the content must be served over HTTPS.

DNS is via Cloudflare.


texts:
Assuming that I’ve a total number of 10 entries in my section('exhibitions') where 8 of them have their entry.endingDate < now, I limit the display to 8 entries but the paginate shows a next button whereas the next page is empty:

{% paginate craft.entries.section('exhibitions').limit(8) as pastExhibitions %}
    {% for entry in pastExhibitions %}
        {% if entry.endingDate < now %}
            …
        {% endif %}
    {% endfor %}

    {% if paginate.prevUrl %}
        &larr; Précédent
    {% endif %}
    {% if paginate.nextUrl %}
        Suivant &rarr;
    {% endif %}

{% endpaginate %}

How can I add a date filter, in this case < now, to the paginate configuration in order to only paginate on entries that are < now?


texts: Category query very slow on multilingual site

texts:
I have a directory of sea ports with a google map that loads about 450 records. The map and listings and pagination work fine. On their own, I get a 2.5 sec page load average.

However as soon as I add a search form that populates a chained select for countries and ports the load time goes up to 8 secs.

The search form code looks like this

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

Country
<select id="countries" class="countries" name="country">
    <option value="">Select...</option>

    {% cache %}
        {% for country in categories %}
            {% if country.level == 1 %}
                <option value="{{ country.slug }}">{{ country.title }}</option>
            {% endif %}
        {% endfor %}
    {% endcache %}
</select>

Ports
<select id="ports" name="port" class="ports" disabled="disabled">
    <option value="">Select a country first</option>

    {% cache %}
        {% for port in categories %}
            <option value="{{ port.slug }}" class="{{ port.parent | lower }}">{{ port.title }}</option>
       {% endfor %}
    {% endcache %}

</select>

It seems that this code cost about 5 seconds of load time.

I have checked the profile output and seen the query for the categories. It's huge.  I can't see how to get the page to load faster as I can't see eager loading applying to a category group, and caching doesn't really help here.

Any ideas on how to optimise this portion?


texts: How to setup custom site routes created by user in plugin settings

texts: In my plugin settings I am allowing the user to specify url formats for each locale along with desired template path, much like sections.  How do I then register those custom url formats as site routes?


texts: Still no way to filter by category in Control Panel?

texts:
I'm wondering if, with the release of Craft 3.5, there is a way to filter by category in the control panel. I see this request goes back several years. The only workaround I can find is to use a Preparse field type to output the category name, and then I can at least sort on it. But I still can't filter on it.
This seems like a very fundamental thing that is missing from the control panel. Are there any plug-ins that handle it? And no, sorry, I am not writing my own.


texts: How would you handle subscriptions and recurring payments using Craft Commerce?

texts:
I am building a VOD site using Craft and Craft Commerce. This is the first time I'm working with their Commerce plugin.

I would like to:

Create subscription products and assign them to plan types.
Subscription period of any duration and frequency.
Trial period to lower a price barrier for subscribers.
Payments processed via external gateways.

What is the best way of implementing such functionality?


texts: CloudFlare Shared SSL certificate forbids CraftCMS control panel sign in

texts:
I am running a site using CraftCMS and have a shared CloudFlare SSL certificate in place. Based on my understanding, the content source (i.e. my website) is not safe, while the content delivered to the user by CloudFlare is secure. While accessing the website works perfectly fine, logging in to the Control Panel is a major issue.

Now I am assuming that I will need an SSL certificate available on my server to secure the content source and thereby be able to log into the control panel using the https domain as opposed to the IP address or the http alternative.

Am I getting this correct or is there some way to log into the control panel using a shared CloudFlare SSL certificate?

Here is the console message I am referring to:

Mixed Content: The page at 'https://www.mysite.com/admin/login' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www.mysite.com/index.php/admin/actions/users/login'. This request has been blocked; the content must be served over HTTPS.


texts: how to access to event object propereties

texts:
I want to access for particular information which is contained in event object.

public function init()
{
    parent::init();

    craft()->on('entries.saveEntry', function(Event $event)
    {

        var_dump($event->params['entry']);
    });
}

it dumps info (brining a needed part)

     ......
["_preppedContent":"Craft\BaseElementModel":private]=>
  array(1) {
    ["tweet"]=>
    array(23) {
      ["created_at"]=>
      string(30) "Thu Nov 13 09:15:40 +0000 2014"
      ["id"]=>
      float(5.3282410346476E+17)
      ["id_str"]=>
      string(18) "532824103464763392"
      ["text"]=>
      string(115) "'The innovation insight you didn't get from Forbes' great blog by @LydiaRagoonanan @nesta_uk http://t.co/PImPVvWeAv"
      ["source"]=>
      string(63) "Hootsuite"
      ["truncated"]=>
      bool(false)

How can I extract text, id_str information?
Thanks


texts:
I'm trying to install the Craft demo site on my local dev environment but I'm getting stuck trying to install Composer.

This command from the instructions didn't work.

cd happylager.test
composer install

The I tried this command from the Composer website:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

I tried both as-is and putting it after the path to my directory first like so:

cd /path to directory

Then the above command.

It did seem to install a file named composer.phar but I'm not sure this is it, and moreover I don't have a vendor subfolder.

Am I missing anything? Thanks.


texts: How to setup a multi-lingual site on IIS

texts:
I've been trying to setup my site on IIS, which runs fine on Apache, without success.

My setup is this (with rewrites)
/ (loads craft for the admin panel)
/en (loads the english homepage)
/fr (loads the french homepage)

The root works without any issues so the web.config does its job.
The same web.config lives in the fr and en folder, but as soon as I try to get in there, I hit a 500.

If I remove the web.config from those 2 folders, I get the homepage of each language, but nothing for the entries.

Anywone knows how to get it to work ?

I'm also trying to get everything working with a single php file that checks for the lang in the p parameter and sets it, but Craft doesn't receive the good slug, even if I modify the p parameter to remove the language.

Thanks


texts:
I moved a site from staging to live. Prior to moving, I logged in to the Craft admin and cleared the caches. I copied the db to the new one and moved the folders like so…

from…
home/subdomains/craft
home/subdomains/staging

to…
home/craft
home/public_html

I’m getting this in the server log…
[28-May-2017 20:01:30 UTC] PHP Fatal error:  Class 'Craft\DbCommand' not found in /home/wenzelspine/craft/app/etc/db/DbConnection.php on line 28

And this in storage/runtime/logs…
2017/05/28 21:33:05 [error] [php] Declaration of Craft\DbCommand::addForeignKey() should be compatible with CDbCommand::addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = NULL, $update = NULL) (/home/wenzelspine/craft/app/etc/db/DbCommand.php:15)

2017/05/28 21:33:05 [trace] [system.CModule] Loading "errorHandler" application component


texts: CSRF Token not verified with actual gateway in Craft Commerce

texts:
My payment page form works just fine with the dummy gateway, but once I change it to use my authorize.net gateway it says that the CSRF token isn't verified. The code below isn't complete, but I figured maybe there is something in this part that is causing it? Any ideas would be great, thanks!

<form class="flex-container flex-center flex-col nav-buttons flex-lg" method="POST">
  {{ getCsrfInput() }}
    <input type="hidden" name="action" value="commerce/payments/pay"/>
    <input type="hidden" name="redirect" value="/store/customer/order?number={number}"/>
    <input type="hidden" name="cancelUrl" value="/store/checkout/payment"/>
    <input type="hidden" name="paymentMethodId" value="1"/>

{% set formValues = {
    firstName: paymentForm is defined ? paymentForm.firstName : (cart.billingAddress ? cart.billingAddress.firstName : ''),
    lastName: paymentForm is defined ? paymentForm.lastName : (cart.billingAddress ? cart.billingAddress.lastName : ''),
    number: paymentForm is defined ? paymentForm.number : '',
    cvv: paymentForm is defined ? paymentForm.cvv : '',
    month: paymentForm is defined ? paymentForm.month : 1,
    year: paymentForm is defined ? paymentForm.year : (currentYear +1),
} %}


texts: What's the recommended way to include vendor library dependencies in your plugins?

texts:
My plugin requires vendor library dependencies and api keys set. What is the recommended way to register an external library? I would also like to configure the public api keys separately for stage and production environments — is there a way to set these in craft/config with the rest of the multi-environment configuration? Or is it better to create a plugin config file of some kind?

Currently I am having to include these in each of my service methods (and something similar again in my javascript files):

private function _saveStripeCustomer($account, $token = NULL)
{
    require_once(CRAFT_PLUGINS_PATH . 'businesslogic/vendor/stripe/lib/Stripe.php');
    \Stripe::setApiKey("sk_test_xxxxxxxxxxxxxxxxxx");

    // ...
}

I'm not familiar with composer. I don't know if that can perhaps help here.


texts: Macro _self no longer possible in Craft 3

texts:
This used to work in Craft 2:

{% macro richText(macroParam) %}
  {{ macroParam |striptags('

')|raw }}
{% endmacro %}

{# include the richtext macro on multiple occasion into another macro #}
{% macro memberMolecule( entryParam ) %}
  {{ _self.richText(entryParam.body) }}
{% endmacro %}

Now in Craft 3 this causes the error:

  Impossible to invoke a method ("richText") on a string variable
  ("path/to/file/with/the/macro").

How do I have to rewrite this for Craft 3?


texts: Error on functions in queue: "Session does not exist in a console request."

texts:
I get the following error on multiple order mails from Craft Commerce. The error points out to the lines where a macro is called:
Email template parse error for email “New order”. Order: “e35f244”. Template error: “An exception has been thrown during the rendering of a template ("Session does not exist in a console request.")

I've also seen this same error on other custom functions in the queue, but this got solved by performing a DB command instead of setting the field values directly on the element followed by the saveElement function, so the error does not only happen in this specific situation.
The mail template:
{% import "_macros/commerce" as macroCommerce %}

{% block content %}

    {% set language = "nl" %}

    {% set lineItemsList = {} %}
    {% for lineItem in order.lineItems %}
        {% set lineItemsListItem = {} %}
        {% set lineItemsListItem = lineItemsListItem|merge(["#{lineItem.qty} x #{lineItem.description}"]) %}
        {% if lineItem.purchasable.product.type.hasVariants %}
            {% set variantLabel = macroCommerce.getVariantLabel(lineItem.purchasable, true)|trim|striptags %}
            {% if variantLabel %}
                {% set lineItemsListItem = lineItemsListItem|merge([variantLabel]) %}
            {% endif %}
        {% endif %}

        {% set lineItemsList = lineItemsList|merge([lineItemsListItem|join(" - ")]) %}
    {% endfor %}

    {% set body = "#{"orders_new_products"|t("app", null, language = language)}
        #{lineItemsList}"
    %}

    {% include "_emails/template" %}

{% endblock %}

The getVariantLabel macro function in _macros/commerce.twig:
{% macro getVariantLabel(variant, showPrice = false) %}
    {% set variantLabel = {} %}
    {% set variantFields = variant.variantFields.one() %}

    {% if variantFields %}
        {% if variantFields.potSize %}
            {% set variantLabel = variantLabel|merge([variantFields.potSize]) %}
        {% endif %}

        {% if variantFields.color %}
            {% set variantLabel = variantLabel|merge([variantFields.color]) %}
        {% endif %}
    {% endif %}

    {% if showPrice %}
        {% set variantLabel = variantLabel|merge([variant.salePrice|commerceCurrency(craft.commerce.carts.cart.currency)]) %}
    {% endif %}

    {{ variantLabel|join(" - ") }}
{% endmacro %}

When the mails are sent manually from the order detailpage it does succeed. There is a cronjob set on the server that keeps the queue running automatically to keep all the functions running in the queue, so I guess that it has something to do with this.
Any solution or tips that could point me in the right direction are much appreciated!


texts: Are there any poll plugins for Craft CMS?

texts:
Since many of us are coming from EE, I will reference these EE addons as examples:
- channel polls
- vwm polls

I found this question but it didn't help much:
How to deal with client input your site?

Also there is UPVOTE plugin but it's not really polls.
https://www.doublesecretagency.com/plugins/upvote

It is important that it works like field type and that you can add as many options as you need.

Thank you


texts: How to suppress display of expired entries in Solspace month calendar?

texts:
I'm trying to suppress display of expired events (events that occurred in the past) on the Solspace month calendar. I'm using the out-of-the-box templates included with Solspace Calendar for Craft. Initially, I thought that there would be a start and end range for the calendar.month function:

{% set month = craft.calendar.month({
    date: targetDate,
    calendar: calendarHandle,
}) %}

But looking at the documentation, there are no parameters to pass. (https://solspace.com/craft/calendar/docs/calendar.month/)

So, I looked at what is happening, and it seems that the start and end should be set on the event object (https://solspace.com/craft/calendar/docs/event/)

In the month template, the event object is called here:

{% for event in day.events %}
    {% include "cal/layouts/_event.html" %}
{% endfor %}

And this is what is returned:

{% set classes = "" %}
{% set classes = classes ~ (event.allDay ? " all_day") %}

{% if event.multiDay %}
    {% set classes = classes ~ " multi_day" %}
    {% set classes = classes ~ (day.containsDate(event.startDate) ? " first_day") %}
    {% set classes = classes ~ (day.containsDate(event.endDate) ? " last_day") %}
{% endif %}

{% set style = "" %}
    {% if event.multiDay or event.allDay %}
        {% set style %}
    style="background-color: {{ event.calendar.lighterColor }} !important;
        border-color: {{ event.calendar.color }} !important;"
    {% endset %}
{% endif %}

{% if event.startDate.format('U') > now|date('U') %}

        {% if event.multiDay %}

                {% autoescape false %}
                    {{ day.containsDate(event.startDate) or day.containsDate(event.endDate) ? event.title : "&nbsp;"|raw }}
                {% endautoescape %}

        {% else %}
            {% if not event.allDay %}

            {% endif %}

                    {{ event.title }}

        {% endif %}

    {% include "cal/layouts/_event_popover.html" %}

{% endif %}

I assume this is where I would set a date range, but I'm not really clear where I would set it?

UPDATE: I managed to get this working by wrapping the event output in a conditional:

{% if event.startDate.format('U') > now|date('U') %}

I added this to the code above.


texts:
With v2 of the Element API plugin, I'm having issues with working out how to return entries that are in a particular category.

I've got the slug in the API route but can't work out what the query should be in the transformer.

Should I be doing this query in a total different way?  I keep thinking I've just gone down the wrong way to do it completely.

'api/v1/category/<slug:{slug}>.json' => function($slug) {

        return [
            'elementType' => Entry::class,
            'elementsPerPage' => 30,
            'criteria' => [
              'section' => 'posts',
              'relatedTo' => ['targetElement' => ***category slug($slug)***],
            ],
            'transformer' => function(Entry $entry) {
                return [
                    'title' => $entry->title,
                    'id' => (int) $entry->id,
                    'slug' => $entry->slug,
                    'postDate' => $entry->postDate
                ];
            },
            'pretty' => true
        ];
    }


texts:
I am currently using an import plugin to import csv data into a channel section and it works just fine. Now I want to import the entries in a second language. Does anyone have any experiences with this?
Since the import works great, I could set up a new channel for the second language, but I wonder if there's a chance to import translations for existing entries.


texts: Unable to edit any entry after update to 2.5

texts:
I can't edit any entry after updating to Craft CMS 2.5.2754 - what I see is attached.

PHP does not report any errors and other parts of the control panel and frontend seem to be working.

Before I dive deep - is there anybody who has had the same behaviour and was able to fix it?

The update has been done twice already, once automatically, once manually. Same results in both cases.


texts: Craft Commerce: Hard code different product prices based on currency?

texts:
We are considering using Commerce for a site where the company sets hard coded prices for the various regions and countries they sell in. I know Commerce has multi-currency support but pricing is in a primary currency and then you set conversion rates. However our client just sets prices - there's not a consistent conversion rate. So, for example, a US product would be $700, it would be $950 in Canada and 14000 pesos in Mexico.

Is there a way to achieve this with Commerce in a fashion where the client can update these prices in the admin? It's an important requirement for them and we're considering other platforms but thought someone might have some insight specific to Commerce because we do like Craft for other reasons. Thanks!

--- UPDATE ---

Trying this as per the accepted answer and the lineItem price on the Cart page doesn't seem to reflect what gets set in the plugin. My code...

class NewPricingPlugin extends BasePlugin
{
    function init(){
        craft()->on('commerce_cart.onBeforeAddToCart', function($event){
           $line = $event->params['lineItem'];

           NewPricingPlugin::log($line['price']); # = $9.00

           // this sets the lineitem price, but when the cart page
           // loads the price hasn't changed.
           $line['price'] = 1000;

           NewPricingPlugin::log($line['price']); # = $1000.00
        });
    }

    // other plugin methods...
}

Is there a lineItem or cart update method that needs to be called?


texts: How to set simple yes/no checkbox using Freeform

texts:
Using Freeform, I am wanting to have a checkbox on a front end form that is not checked by default that posts 'Yes' if checked and 'No' if not checked. I am creating a manual HTML form that works fine for all the other fields, but I can't figure out what to write for the checkbox logic.

From the docs I know I can set the value in the back end to a default of either 'Yes' or 'No', I have done this and using the following template code but it always sends through the same value of either Yes or No depending on what you set in the back end.

<input type="checkbox"
        name="{{ receiveContactFromTFA.handle }}"
        value="{{ receiveContactFromTFA.value == 'Yes' ? 'Yes' : 'No' }}"
        {% if receiveContactFromTFA.value == 'Yes' %} checked{% endif %}>

I have also just tried not having a value attribute at all but again the value defaults to yes because it is set in the back end. I have also tried removing the value entirely and having the following template code:

<input type="checkbox"
        name="{{ receiveContactFromTFA.handle }}">

If I do that then then nothing posts. I know a checkbox will normally post a '1' if checked but how do you handle this logic using Freeform to be either 'Yes' or 'No'?


texts: Auto-populate login form when accessed via client intranet

texts:
My client has a private Craft site only accessible to their employees. To access the site they all use the same username and password on a front-end login form. They are now wanting to link to this site from their intranet and have the username and password form values auto-populated (only when accessed from the intranet). I have come up with a way using a Craft route (example.com/login/user/username/password/actualpassword) and craft.request.segment to auto-populate the form input values. This works but I was wondering if anyone else has a solution that doesn't require the password being in the URL.

Thanks!


texts: How to receive email notification when an error or bad request happens?

texts:
Is it possible to receive email notifications when there is an error or Bad Request issue in Craft CMS?
We had an issue where our contact forms were not working due to craft.app.config.general.[csrfTokenName] changing to craft.app.config.general.csrfTokenName. No warnings in the deprecated code section. Instead, potential customers would see a Bad Request message, but we had no idea for days.
I would like to be alerted if such an error occurs so I can fix the issue much quicker.
Similarly, if there is an error on the site anywhere, I would like to be alerted.
Is it possible?
Thanks


texts: Redactor I source button no longer working?

texts:
Running Craft CMS 2.6.2903 and Redactor I 1.1.0

This is my config:

{
    "buttons": ["format", "bold", "italic", "lists", "image"],
    "plugins":["fullscreen", "source"],
    "toolbarFixed": true
}

fullscreen and source no longer work, not sure but possibly a recent Craft update? I have all my rich text fields set to Rich Text (Redactor I) and Standard as Standard.json is the config I edited for above settings. No html or source button shows up, fullscreen shows up but doesn't work.

Anyone know what could possibly be wrong, this config worked a while back.


texts:
Unable to create the cache directory
  (/path/craft/storage/runtime/compiled_templates//36).

I receive this on one live installation of Craft CMS.
This is 99% a server issue with permissions. I can't even login to the CP anymore.

My question tough: I don't cache anything on the site.
Does Craft still cache things even with 'cache' => false, or are these two different cache levels?


texts: Filtering by entries which have unpublished draft versions in the admin

texts:
I have a client who wants to use an author (draft) -> editor (publish) workflow.

It appears that authors can update existing entries which will create a new draft of the entry. As an editor, I can then visit the edit page for that entry and select the new draft from the "revisions" drop-down.

This is great if I know that a new draft is waiting to be reviewed, but I couldn't find a way to discover which entries have new drafts.

Is there a way to view which posts have new drafts from the entries index? Otherwise what is the normal practice for editor-type users to know which entries have pending changes?

Thanks in advance!


texts:
I recently inherited a project in Craft from another developer, but he's moved on and no one knows what his admin password was.

I've tried generating a password on an account with a fresh install and copying that over the hashed password in MySQL without success.  Are there any other options?

Thanks.


texts:
I'm trying to create an object of objects, can anyone suggest why object would only contain the last iteration of "itemObject"?

{% set object = {} %}

{% for entry in craft.entries.section("mainSectionsStructure") %}
    {% set itemObject = {
            "title": entry.title,
            "link": entry.url
        } %}

    {% set object = object|merge(itemObject) %}

{% endfor %}

{{ object|json_encode() }}


texts: When redirecting to HTTPS from www, index.php appears in URL

texts:
I have a redirect setup for www, it successfully redirects to https:// but it includes /index.php?p= in the URL. I'm not convinced by htaccess file is configured correctly.

Here's my htaccess file:

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]

RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Help much appreciated.


texts: Possible to paginate product variants in Craft Commerce 2?

texts:
I am currently in the process of building a commerce 2 site with a very detailed level of nesting in the product options so we're looking to list all variants for a product. (Sounds silly, but it works in this case!)

However, while trying to use paginate, I'm getting the following error:

Impossible to invoke a method ("limit") on an array.

Here is my markup:

{% paginate variants.limit(12) as pageInfo, pageEntries %}

Is it even possible to paginate variants?

Thanks

EDIT

We are getting all the product variants as follows:

{% set variants = product.variants %}

But if we use the limit here outside of the pagination, won't that mean we will always get the same first 12 items. Whereas we need to limit it within the paginator so we get the first 12, the next 12 etc etc.

Cheers


texts: Is it possible to submit to an AM Forms form via Ajax? I cannot find anything in the docs? Is there a tutorial somewhere?


texts: Generating pending image transforms stuck in process

texts: In the CMS the progress indicator for tasks is stuck and not completing its jobs. What can I do to resolve this?


texts: Management of large number of downloadable PDFs

texts:
I'm rebuilding the main website for a small rural local council, and at this stage I am planning on using Craft. The main issue I have is around the management of several hundred PDF documents which fall into different categories (agendas, minutes, policies and a lot a paper-based forms). The current system uses Docman in Joomla, so I need to come up with something equal of better.

At this stage my thinking is to create channel entries for each document with a number of metadata fields which would include categories and possibly tags. Each document would be named with a date included to facilitate some level of revision history (requirement by law). I need to present the documents in various ways. Sometimes there will just be links on a webpage, and in other cases I would need to auto-generate an index (e.g. meeting minutes) for a category.

So, am I going in the right direction, or can someone point me down another road, or try and divert me away from Craft altogether if it is not yet suitable to do the job?  I realise I may not be asking the right sort of StackExchange question, so happy to take advice to make it specific enough to meet any criteria.

(An alternative might be to see if I can extract some sort of feed from Sharepoint which the council uses as a basis for it's intranet. That would have to be a separate question though.)


texts: unserialize(): Error at offset 0 after attempting to download and install plugin within control panel

texts:
Steps to reproduce:

Log into control panel,
Go to Plugin Store tab and install a plugin (in my case hillholliday/craft-user-manual or dolphiq/sitemap),
Plugin installation error screen,
Navigate to /admin and entire site errors out with this message (control panel and frontend)

unserialize(): Error at offset 0 in ProjectConfig.php

Unsuccessful attempts to correct the issue include:

Restoring latest database backup
Restoring backed up composer.json and composer.lock files from storage/composer-backups and running composer install
Clearing storage/runtime/cache

Any suggestions on how to resolve this issue, and insights to why it's happening in the first place?


texts: Allow a User Group to access plugin pages (without hasCpSection)

texts:
I'm facing a problem which, on the surface, seems similar to this thread...

Like that other thread, I've found that a specific user group is unable to access my plugin's pages because the plugin is lacking a hasCpSection method. My plugin doesn't need a hasCpSection method, because there really isn't a "section" for people to access. Specifically, I don't need a link in the side nav, because my plugin doesn't have a main index page.

However, my plugin does have other pages. These other pages are only accessible via special links. Those special links appear on Entry edit pages, as a custom Fieldtype. These random pages are what I want my client to have access to.

And that's where I'm unable to use the solution provided in the related thread. Because when I link directly to a template, those pages are restricted by default. There's no way for me to "allow anonymous". I would have to give the user group full admin access (which is crazy), and then circle back and restrict permissions on the page.

Any suggestions? This kinda feels like a bug to me, or perhaps a feature request.


texts:
Setting up a plugin using Pocket API and I'm currently in a authorization loop.

Index template calls the init function. Init function gets requestToken (successfully) and then redirects to Pocket for app authorization (authorizeToken function). After authorization, redirected to callback.

From here, I need to convert the token to a 'Pocket access token', but when the controlller fires it seems to call the init function before the accessToken function and I end up in an endless loop.

Can anyone explain why this is happening? Am I going about this the right way?

Index template:

{% extends "_layouts/cp" %}
{% set title = "Pocket Articles"|t %}

{% set offset = craft.request.getParam('offset') %}
{% set start = craft.pocket.init() %}

{% set content %}
    {{ start }}
{% endset %}

Service:

public function init(){
    $token  = $this->requestToken();
    $auth   = $this->authorizeToken($token);
    return;
}

public function accessToken($code){
    $url                    = $this->getSetting('access_path'); //https://getpocket.com/v3/oauth/authorize
    $requirements['code']   = $code;
    $requirements['key']    = $this->getSetting('consumer_key');

    $curl = $this->initCurl($url, $requirements);
    $results = curl_exec($curl);

    echo "<pre>";
    print_r($results);
    echo "</pre>";

    curl_close($curl);

    return $results;
}

private function authorizeToken($token){
    $auth_path      =$this->getSetting('auth_path'); //https://getpocket.com/auth/authorize?
    $redirect_path  =$this->getSetting('callback_path');
    $actionUrl = UrlHelper::getActionUrl('pocket/callback');

    $url = $auth_path.'request_token='.$token.'&redirect_uri='.$actionUrl;

    header("Location:".$url);

    return $url;
}

Controller:

public function actionCallback(){

    //call pocket server for acccess token
    if(craft()->httpSession->get('code')){
        $code   = craft()->httpSession->get('code');
    }else{
        $code   = "no code";
    }

    $access_connection = craft()->pocket->accessToken($code);
    $variables['access_token'] = $access_connection;

    $this->renderTemplate('pocket/control_panel', $variables);

}

Callback template:

{% extends "_layouts/cp" %}
{% set title = "Pocket Articles"|t %}

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

{% set content %}
    {{ dump(access_token) }}
{% endset %}


texts: Asset integration with Microsoft Azure Storage in Craft 3

texts:
I'm developing a site using the Craft 3 and I can't figure out how to connect assets with Microsoft Azure Storage.

I found plugin for Amazon S3 but not available similar plugin for azure.

Any help will be appreciated.


texts:
I've created a 'controllers' folder within the 'plugins' folder and a php file within that following the documentation

I've also created the following form:

    <form method="POST" accept-charset="UTF-8">
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="pluginName/controllerName/actionName">

        <input type="submit" value="Start poll">
    </form>

I keep getting the 'Unable to resolve the request' error.

Do you have any idea why this could be happening? Am I missing a step that's not in the documentation, like needing to register the url?

For reference, the action only contains $this->redirect('');


texts: Contact Form Extensions - Checkbox Templating

texts:
Cannot for the life of me get checkbox values to display in a HTML email template using the Contact Form extensions plugin.

Form snippet:

<input type="hidden" name="message[type]" value="">

<input type="checkbox" class="styled-checkbox" name="message[type][]" id="New" value="New">
New

<input type="checkbox" class="styled-checkbox" name="message[type][]" id="Used" value="Used">
Used

And the email template snippet:

{% if submission.message['type'] %}

Type of Quote: {{ submission.message['type'] }}

{% endif %}

Does anyone have a clue about this? I have tried many variations, the above is just one of them. Pulling my hair out ;)

TIA!


texts: How to set the commerceCurrency filter in an European style

texts:
Using commerceCurrency filter from the Craft commerce plugin, how can I add the currency name after the price instead of before the price, and drop the zeros when not necessary ?

For example :

{{ product.variants[0].salePrice | commerceCurrency(cart.currency) }}

  €68.00

How can I output this :

  68€

Thank you!


texts: I love routes, but they appear limited to loading a specific template. What about loading a plugin/controller based on the route instead? Anyway to do this in craft or am I limited to .htaccess?


texts: How to get the unverifiedEmail value of a user after a change email request?

texts:
The currentUser.unverifiedEmail variable, which is public, is always empty on front end even after email change.

I thought it was a bug. I contacted Craft support about this, and here is Brad's answer:

  That's expected behavior... the default UserQuery (which is what {{
  currentUser }} is) only grabs a small subset of columns in it's select
  to avoid exposing potentially sensitive user account information
  throughout the system.
  https://github.com/craftcms/cms/blob/develop/src/elements/db/UserQuery.php#L310-L325

  If you want anything outside of that, you'll have to query for the
  data directly.

I tried this custom query:
{{ craft.users.id(currentUser.id).one().unverifiedEmail }}.
But even after requesting an email change, the value remain empty.

Any idea how to make this query from Twig?


texts: How do I send a POST request using the Dukt REST plugin?

texts:
The plugin documentation is somewhat lacking, but based on the documentation that exists and looking at the plugin files, I believe a post request should take the following form:

{% set response = craft.rest.request
.url('http://my.api.endpoint')
.method('post')
.headers({
    key: XXXXXXXXX,
    secret: XXXXXXXXX
})
.query({
    name: craft.request.getPost('name'),
    email: craft.request.getPost('email'),
    telephone: craft.request.getPost('telephone'),
    message: craft.request.getPost('message')
})
.send() %}

Unfortunately, I'm getting a 403 / Access denied response from the API.

I'm posting to the template containing this code from a form, hence the use of the craft.request.getPost() method.

If I send the same request using Postman, it works perfectly. So I know the problem is with the request and not the API.

Any advice much appreciated.

Update: It seems that the headers are not arriving at the API end. If I remove the .method('post') parameter, the request works, albeit as a GET request with the data appended to the URL as a query string. So it seems that adding the method parameter is somehow interfering with the sending of the headers.


texts: Craft Request Filter Query Matching Drop Down Fields and Checkbox Fields

texts:
I have a front end form that allows users check checkboxes to find entries that have matching field values. I've pieced together a query reading other posts here and my limited knowledge of Craft and Twig.

My entries have multiple dropdown fields that are getting matched (1 match per field) and one checkbox field (1 or more matches per field). My query works when I only have dropdown fields but I'm struggling getting it to work to match the checkbox fields.

Here's my paired down query:

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

    {% set relatedParams = ['and'] %}

 {# dropdown field match #}
    {% set brand = craft.request.getParam('brand') %}
       {% if getBrand %}
           {% set params = params|merge({'brand':getBrand}) %}
       {% endif %}

 {# checkbox field match #}
    {% set getLocation = craft.request.getParam('location') %}
    {% if getLocation %}
          {% for eachLocation in getLocation %}
              {% set params = params|merge({'eachLocation'}):getLocation}) %}
          {% endfor %}
    {% endif %}

 {# merge related params and params #}
    {% if relatedParams|length > 1 %}
         {% set params = params|merge({'relatedTo':relatedParams}) %}
    {% endif %}

 {# search #}
    {% set entries = craft.entries(params).search(searchParams|trim) %}

Here's my paired down front-end form:

 <form>

<!-- brand matches dropdown fields-->

    <label>
       <input type="checkbox" name="brand[]" value ="brandX" />
    Brand X
    </label>
    <label>
       <input type="checkbox" name="brand[]" value ="brandY" />
    Brand Y
    </label>

 <!-- location matches checkbox fields -->

    <label>
       <input type="checkbox" name="location[]" value ="locationA" />
    Location A
    </label>

    <label>
       <input type="checkbox" name="location[]" value ="locationB" />
    Location B
    </label>
 </form>


texts: Using target element criteria to filter results

texts:
I'm using the Element API plugin to try and search for addresses using minimum and maximum lat & lng values and then using target element within the criteria parameters to filter the results however it doesn't seem to be working based on the code below.

$locationCriteria = craft()->elements->getCriteria('Entry');
$locationCriteria->lat = array('and', '>='.$max_min_values['min_latitude'], '<='.$max_min_values['max_latitude']);
$locationCriteria->long =  array('and', '>='.$max_min_values['min_longitude'], '<='.$max_min_values['max_longitude']);
$locations = $locationCriteria->find();

return [
            'criteria' => [
                'section' => 'xxx',
                'relatedTo' => [
                    'and',
                    ['targetElement' => $locations],
                ]
            ],
            'elementType' => ElementType::Entry,
            'transformer' => new Search(),
        ];

Does anyone have any ideas?


texts: HTML/View Source button not working/showing in WYSIWYG Craft 2.5 / Redactor II 1.1.0

texts:
The "HTML" button no longer seems to show in the WYSIWYG. The button is set in the Redactor config file like so:

{
    "buttons": ["html","formatting","bold","italic","unorderedlist","orderedlist","link","image","video"],"plugins":["fullscreen","video"],
    "toolbarFixed": true
}


texts: Cannot get file upload/attachment with Sprout Forms working

texts:
I'm trying to add an file upload/attachment to my Sprout Form submission, but even though all the other fields are saved & the Sprout Email notification is sent - the file field remains empty - no file is uploaded & so no attachment is sent.

I've checked that my form contains enctype="multipart/form-data"
I've checked that the file type I'm trying to upload is an allowed file
type for the Asset folder ie: PDF
I've checked that the file is a reasonable size - in this case 3KB
I've checked the craft log, sprout forms log & sprout email log & there are no errors.

Anyone have any ideas ? Below is my form code - what am I missing ?

<form id="careerApplication" method="post" action="" accept-charset="UTF-8"
enctype="multipart/form-data">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="sproutForms/entries/saveEntry">
<input type="hidden" name="handle" value="careerApplication">
<fieldset>
    {{ craft.sproutForms.displayField('careerApplication.fullName') }}
</fieldset>
<fieldset>
    Reference #
    <input type="text" name="fields[refNo]" id="fields-refNo" readonly value="{{ craft.request.getParam('ref') }}" />
</fieldset>
<fieldset>
    {{ craft.sproutForms.displayField('careerApplication.email') }}
</fieldset>
<fieldset>
    {{ craft.sproutForms.displayField('careerApplication.telephone') }}
</fieldset>
<fieldset>
    Motivation
    <textarea name="fields[motivation]" id="fields-motivation" placeholder="Motivation"></textarea>
</fieldset>
<fieldset>
    Submit your CV:
    <input type="file" name="fields[cvUpload]" id="fields-cvUpload" />
</fieldset>
{{ craft.sproutInvisibleCaptcha.protect() }}
<input id="submit_application" name="submit_application" type="button" value="Submit Application" class="red-btn" />
</form>


texts: Accessing entries in a matrix field in plugin

texts:
I am writing a plugin function that takes an entry id, the entry has a matrix field (called block) and the matrix has a blocktype which contains a number field (blockStep), an entries field (blockContent) and another entries field (blockDependency).

I am getting the entry, which i am calling a module, like this:

$module = craft()->entries->getEntryById($moduleid);

This works fine. Then I get the matrix field, called block, like this:

$matrixBlocks = $module->block;

This also works fine. However, when I try to loop through the matrix field, like this:

    foreach ($matrixBlocks as $block){
      var_dump( $block->getContent()->blockStep);
      var_dump( $block->getContent()->blockContent);
      var_dump( $block->getContent()->blockDependency);
    }

Only the blockStep, which is a number, is set - the two entries fields are just returning NULL.

Can someone help? How should I be accessing these entries fields?

Thank you.