texts:
I'm trying to install craft on my local machine (OSX Mavericks). It gets stuck on a screen with "Oops." and a spinning icon.

The requirements checker says all is good. I have InnoDB and MySQL 5.7.3 installed. I get a list of errors in craft.log:

2014/09/22 15:40:54 [warning] [application] Skipping record /Library/WebServer/Documents/lays2/craft/app/records/BaseRecord.php because it’s abstract or an interface.

2014/09/22 15:40:55 [error] [system.db.CDbCommand] CDbCommand::execute() failed: SQLSTATE[42000]: Syntax error or access violation: 1171 All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead. The SQL statement executed was: CREATE TABLE `craft_assetfolders` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY NULL,
`parentId` INT(11) NULL,
`sourceId` INT(11) NULL,
`name` VARCHAR(255) NOT NULL,
`path` VARCHAR(255) NULL,
`dateCreated` datetime NOT NULL,
`dateUpdated` datetime NOT NULL,
`uid` CHAR(36) NOT NULL DEFAULT 0
) ENGINE=InnoDb DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci.

2014/09/22 15:40:55 [error] [exception.CDbException] exception 'CDbException' with message 'CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1171 All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead' in /Library/WebServer/Documents/lays2/craft/app/framework/db/CDbCommand.php:358

There's also a Stack Trace.

Any ideas? Thanks in advance.


texts: How can I loop through the values of a drop down within a SuperTable?

texts:
I a musing a front-end form to create an entry in the CP. In my form I am using a SuperTable that contains two fields/blocks.

Size - [text input]
Measurement - [dropdown]

Here is what my template looks like:

    <input type="hidden" name="fields[lotSize]">
    <input type="hidden" name="fields[lotSize][new1][type]" value="1">

            Lot Size
            <input type="text" class="form-control" name="fields[lotSize][new1][fields][size]">

        Measurement
        <select name="fields[lotSize][new1][fields][measurement]">
            {# Loop through the values instead of hard-coding #}
            <option value="">Select</option>
            <option value="squareFeet">Square Feet</option>
            <option value="acres">Acres</option>
        </select>

I've been reading through Updating a Super Table field from a front end form and have tried this:

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

...But I'm not sure where to go next to get to the measurement field.

I have attached a screenshot of my CP page to help show what I am trying to accomplish. Thank you for any suggestions!


texts: Evenly dividing up table items in columns

texts:
I'm building out my first Craft site and learning a whole lot so far. Coming from ExpressionEngine, this really seems like what EE should have been.

Anyway, I'm trying to find a way divide up content from a table field into three even columns. For example, if I have content in 9 rows in a table, I would like to have 3 items per column. Is this possible with Twig?  Here is the HTML.  Thank you!

item

item

item

item

item

item

item

item

item


texts: With using the CraftCMS builtin database export feature, is it possible to specify the export config to have the file in .gzip instead of just .zip? If, yes, then how can I do it?


texts:
I have a client with very stringent concerns over acurate color in thier images.

They have noticed that image resized from Craft have some dramatic color discrepancies, which I have verified. It's nothing you'd probably notice in a regular photo, but these are actual fabric swatch images, so the color is crucial.

Anyway - first thing I verified was that Imagick was being used, which it is.

However, when I look at the file info, it still says something about gd-jpeg which concerning...not sure if that is just a red herring though.

❯ file resized-720.jpeg
resized-720.jpeg: JPEG image data, JFIF standard 1.01, comment: "CREATOR: gd-jpeg v1.0 (using IJ"

Is this more appropriately posted as an issue for https://github.com/avalanche123/Imagine?


texts:
I want to create a Excel file with all used slugs in my Craft website.
I've searched for a plugin but without succes. I also tried to find a useful table in the Craft database, also without succes.

Is there a simple way to achieve this?


texts: How to use categories with Sprig's "Load More" recipe

texts:
I am trying out Sprig's "Load More" Recipe and I am trying to call up entries that are related to the current category page. But when I add .relatedTo(category) to the entry model, it doesn't work–it still just shows all the entries in the channel. I've used this .relatedTo(category) method elsewhere on the page (not using Sprig) and it works just fine. How can I call up only the entries that match the current category page in this Sprig recipe?
_category.twig
{{ sprig('_layouts/_categories/_loadMore', {limit: 6}) }}
{{ sprig.script }}

_loadMore.twig
{% set offset = offset ?? 6 %}
{% set limit = limit ?? 10 %}

{% set entries = craft.entries.section('aBetterPost').offset(offset).limit(limit).relatedTo(category).all() %}

{% for entry in entries %}

            {% set featuredImage = entry.featuredImage.one() %}

{{ entry.title }}

{% endfor %}

{% if entries %}

    <input type="hidden" name="offset" value="{{ offset + limit }}">
    <button class="load-button" sprig>Load More</button>

{% endif %}


texts:
I'm currently using SEO by EtherCreative on Craft 2, one of my pages needs a custom title and description injected into it like this on the docs:

  In some cases, you will not have access to an SEO field, but will want
  to set the page title & description. You can do this by creating a
  custom SEO object using the function below:

craft.seo.custom('The Page Title', 'The page description', $includeDefaultTitleSuffix)

Mine seems to be throwing errors or not doing anything like so:

  {% set seo = craft.seo.custom('Discount codes and vouchers for {{ query }}', 'You searched for {{ query }}. Check out the latest live {{ query }} discount codes & voucher codes for {{ "now"|date("m") }} {{ "now"|date("Y") }} only at Vouchertoday.uk') %}


texts:
I have updated my craft/config/general.php file to allow some new file types to be uploaded to my site.

'extraAllowedFileExtensions' => 'bim, dwg, rvt'

When I output these file assets in the template, I would like to be able to use the {{ asset.kind }} property to output "PDF" or whatever name for my additional types.

Currently I see unknown for each of my new types.

I've had a look in the documentation for the IOHelper Class but could not see a way to add additional definitions.


texts: Why is /blog not displaying /blog/index.html?

texts:
So basically, my url is mysite.com/blog which should apparently lead to /blog/index.html which is stored under templates/blog/index.html. As far as I can see I don't need to set up any routes to make it work and it should be happening as standard. I'm working in a multisite environment, and may have done some damage there? I basically need to know where the error will be coming from, .htaccess/index.php etc...

Thanks!


texts: I am creating a resources page, on which a resource can be downloaded after filling or submitting a form. This form is having user info fields like first name, last name, email etc. Could anyone please suggest me how can I implement it in Craft.


texts: Get entries by category value from within plugin

texts:
I need help.

I want to get entries based on multiple field search. It works for basic field types like selectbox or plain text but I can't get it to work with Categories Fields.

The field size is a selectbox field and works good.
The color is a Categories field and doesn't work.

The code:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = "houses";
$criteria->size = "big";
$criteria->color = "white"; // <== HOW???
$entries = craft()->elements->buildElementsQuery($criteria)->queryAll();

How do I get entries with a specific Categories Field value?

Thanks for any help.


texts:
I updated a very old Craft installation (v2.6.2794 to v2.6.2971) and now I'm locked out off the admin area. I can get to the login panel and log in but once in I just get 500 errors.

After turning on devMode, I found this:

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 72 bytes) in /mysite.com/craft/app/helpers/ModelHelper.php on line 102

I already have my phpMaxMemoryLimit at 512M (checked). Could my installation really be using that much memory?


texts: How to use getTemplateName() from within a plugin?

texts:
I wondered if we could embellish from this answer?

I'm developing a plugin where at some point it needs to detect if the user is currently on one of the error pages (400, 403, 404, 500, or 503).

I'm not sure of any built in methods within craft, so I figured an easier solution would be to just check the file name being used. Php's __FILE__ method refers to the .php file it was called from. I can't seem to grasp how to use getTemplateName() within a plugin.

Is there a better way to detect the error page, or a clean way of detecting the template file being used?


texts:
I'm trying to load a JSON feed and parse/display the data.  My code below generates an error - "impossible to access id on a string variable".  Below is some sample JSON data I get back along with code I tried to use to display.  Any help accessing my JSON data would be hugely appreciated.

Code to load / display feed (does not work):

{% set params = {
    url: 'https://jsonURL',
    type: 'json',
    element: '',
    cache: 60,
} %}

{% set feed = craft.feedme.feed(params) %}

{% for node in feed %}
    node: {{ node.id }}
{% endfor %}

JSON feed data:

{
    "id":"546852386",
    "timestamp":"2019-10-17 15:35:47",
    "user_agent":"Mozilla",
    "remote_addr":"1234",
    "payment_status":"",
    "form":"12345",
    "latitude":"123",
    "longitude":"123",
    "data":[
        {
            "field":"83628997","value":"first = aa\nlast = a"
        },
        {
            "field":"83691483",
            "value":"1"
        }
    ],
    "pretty_field_id":"83628997"
}


texts: Front End Entry Form Select Dropdown Error

texts:
My front-end new entry form works, but when I add the complexity of a dropdown to the mix - it error's and doesn't save the entry. (I found this out with trial and error, removing fields until I found the culprit - the dropdowns)

I'm unsure what errors it's returning, but I'm sure something may be off with the code.

  {% macro errorList(errors) %}
            {% if errors %}

                    {% for error in errors %}

{{ error }}

                    {% endfor %}

            {% endif %}
        {% endmacro %}

        {% from _self import errorList %}

        <form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
            {{ csrfInput() }}
            <input type="hidden" name="action" value="entries/save-entry">
            {{ redirectInput('/listings/') }}
            <input type="hidden" name="sectionId" value="1">
            <input type="hidden" name="enabled" value="1">

              Demographic
              <select class="form-control" id="listingType" name="fields[demographic]">
                {% set demographicField = craft.fields.getFieldbyHandle('demographic') %}
                {% for option in demographicField.settings.options %}
                  <option>{{ option.label }}</option>
                {% endfor %}
              </select>

            <button class="btn btn-primary btn-md semi-bold" type="submit">Create Listing</button>

        </form>


texts:
I'm building a site and getting some odd search results.

For example, searching against the term 'Gibraltar' returns an entry with four mentions of the term in it's content first, whilst an entry with 'Gibraltar' in the title and 10 instances in the body is returned second.

I am returning the results paginated, ie:

{% paginate craft.entries.search( '*' ~ query ~ '*' ).limit(10).order('score') as entries %}

Any thoughts why this might be happening? I came across this issue reported last year at Search order "Score" criteria - seems to be the same issue.

Cole


texts: Filtering by categories AND tags with full match

texts:
We're trying to filter by categories AND tags in the one form. However can't seem to get things working as we would like.

Essentially, we have a form that pulls in the tags and allows multiple filtering dropdowns. The below is out results page code, which outputs odd results. We need all params to match the entries categories/tags but it just doesn't work as expected. Where are we going wrong?

    {# Get params #}
    {% set mainCategory = craft.app.request.getParam(‘category’) %}
    {% set season = craft.app.request.getParam(‘season’) %}
    {% set age = craft.app.request.getParam(‘ages’) %}

    {# Set arrays #}
    {% set mainCat = mainCategory ? craft.categories.group(‘courseCategories’).slug(mainCategory).all() %}
    {% set seasonCat = season ? craft.tags.group(‘season’).slug(season).all() %}
    {% set ageCat = age ? craft.tags.group(‘ageRange’).slug(age).all() %}

    {# Set relatedTo #}
    {% set categoryParam = mainCat ? {targetElement: [‘and’]|merge(mainCat)} %}
    {% set seasonParam = seasonCat ? {targetElement: [‘and’]|merge(seasonCat)} %}
    {% set ageParam = ageCat ? {targetElement: [‘and’]|merge(ageCat)} %}

    {# Get entries #}
    {% set relationParams = [categoryParam, seasonParam, ageParam]|filter %}
    {% set entries = craft.entries({
        section: ‘courses’,
        relatedTo: relationParams ? [‘and’]|merge(relationParams) : null
    }) %}


texts: How delete a user session with the element api?

texts:
I need a function to logout a craft user and delete the session of that user. This must take place in the element API plugin as an endpoint. Something like this:

function userLogout(){
    if (craft()->userSession->isLoggedIn()){
        // if user loggedin
        // how to logout?
    }
}

'api/logout' => array(
    'elementType' => 'User',
    'criteria' => ['id' => craft()->userSession->user->id, 'limit' => 1 ],
    'paginate' => false,
    'transformer' => function(\Craft\UserModel $user) {
        userLogout();
    }
),


texts: Sprout Reports plugin - How to output a Matrix field into a row

texts:
I'm not clear on how I would iterate over a Matrix field to be able to include the content in the row.

Wish there was an example in the docs: https://sprout.barrelstrengthdesign.com/docs/reports/custom-twig-template-report.html#template-settings

{% for entry in entries %}

    {% do craft.sproutReports.addRow([
      entry.title,
      entry.myMatrixField
    ]) %}

{% endfor %}


texts: Cannot access assets - unable to open image

texts:
I'm on Craft 2.7.8 and cannot access some of my assets - getting
Unable to open image ../html/assets/xxx.jpg error all the time.

I've checked the owner, group and permissions dozen of times, currently everything set to root and 777.

I can access the images when I go directly to that URL in a browser, but for some reasons I cannot access them in a template.

In the Craft Admin Panel I changed the Source type to Amazon S3 bucket but that didn't work too. I can see the access/secret keys are correct (can display available buckets) but getting the same error "403 - unable to open".

Double checked with Postman and confirmed the images are there - looks like it's a Craft's or the Imager plugin issue.

Any ideas, please?
I'm using html as the root of my website (instead of public) and running on Apache.

Thanks


texts: In a large set of entries across multiple sections, how can I loop through each section type in the set?

texts:
I have a set of entries from multiple channels and I want to loop through each section type that is in the set.

Something like

{% set entries = craft.entries.search(query).order('score') %}

{% for entrySection in entries.sections %}
    {{ entrySection.name }}
{% endfor %}

So basically if I have 100 results from across 8 sections, is there a way I can list out those 8 sections separately?


texts:
I'm trying to edit the Contact Form plugin to copy the email to another address.

Looking in apps/models/EmailModel.php I see this for CC:

'cc' => array(AttributeType::Mixed);

Looking in apps/services/EmailService.php I see this:

// Add any CC's
if (!empty($emailModel->cc))
{
    foreach ($emailModel->cc as $cc)
    {
        if (!empty($cc['email']))
        {
            $ccEmail = $cc['email'];

            $ccName = !empty($cc['name']) ? $cc['name'] : '';
            $email->addCC($ccEmail, $ccName);
        }
    }
}

So, it looks like 'cc' needs to be array? I tried it without it being an array and I get an invalid foreach error. At the moment, I've added this line to ContactFormService.php (after line 45):

$email->cc = array('email' => 'name@domain.com');

I've also tried this:

$email->cc = array('email' => 'name@domain.com', 'name' => 'My Name');

The problem: The email is not being CC'd and I'm not getting any errors. Anyone?


texts:
What's the correct way to create a conditional so that a field won't display if it's empty? Is it:

{% if entry.myentry | length %}
    ...
{% endif %}

or

{% if entry.myentry %}
    ...
{% endif %}

I tried both and both seem to work, but I want to make sure they're both correct.


texts:
I am trying to create a category template that shows all entries to show relating to the categories.

At the minute the cats are

Industry
Chemical
Medical


texts: How do I omit similar content in a for loop based on the first letter in title?

texts:
I've got a for loop that is returning the first letter of the entry title. I have a number of entries so I almost get a complete alphabet except that there are too many of many letters. I only want one 'a', one 'b', one 'c' and so
forth. And no letter if there is no entry to correspond to it.

{% for alpha in craft.entries.section('advertisers').order('title asc') %}
    {{ alpha.title|first }}
{% endfor %}

This code returns:
A A A B B B B B C C E E E E G G H H K M M M M P P R R S S S T T U U U W W
but I want it to return A B C E G H K M P R S T U W

Are there any solutions to this?


texts: Order by dynamic field in custom Element Type

texts:
In my module, I have a custom Element Type with three fields (firstName, lastName, email) that are dispalyed on an element index page in the CP.
I have the first column as a full name by concating the first and last which works fine but I'd like to be able to sort this when selecting the heading but firstName and then lastName e.g. "...ORDER BY firstName ASC, lastName ASC"
I have an element query class however I'm not sure how to affect the ordering for the element in there (or even if that's where I'm supposed to do it).
The Element Type:
class Subscriber extends Element
{

    public $firstName;
    public $lastName;
    public $email;

    ...

    public function __toString()
    {
        $firstName = trim($this->firstName);
        $lastName = trim($this->lastName);
        return $firstName . ($firstName && $lastName ? ' ' : '') . $lastName;
    }

    public static function find(): ElementQueryInterface
    {
        return new SubscriberQuery(static::class);
    }

    protected static function defineTableAttributes(): array
    {
        return [
            'fullName' => \Craft::t('app', 'Full Name'),
            'firstName' => \Craft::t('app', 'First Name'),
            'lastName' => \Craft::t('app', 'Last Name'),
            'email' => \Craft::t('app', 'Email'),
        ];
    }

}

The Element Query:
class SubscriberQuery extends ElementQuery
{

    public $firstName;
    public $lastName;
    public $email;

    public function firstName(string $firstName) {
        $this->firstName = $firstName;
        return $this;
    }

    public function lastName(string $lastName) {
        $this->lastName = $lastName;
        return $this;
    }

    public function email(string $email) {
        $this->email = $email;
        return $this;
    }

    protected function beforePrepare(): bool
    {
        $this->joinElementTable('na_subscriber');

        $this->query->select([
            'na_subscriber.firstName',
            'na_subscriber.lastName',
            'na_subscriber.email',
        ]);

        if ($this->firstName) {
            $this->subQuery->andWhere(Db::parseParam('na_subscriber.firstName', $this->firstName));
        }

        if ($this->lastName) {
            $this->subQuery->andWhere(Db::parseParam('na_subscriber.lastName', $this->lastName));
        }

        if ($this->email) {
            $this->subQuery->andWhere(Db::parseParam('na_subscriber.email', $this->email));
        }

        return parent::beforePrepare();
    }
}


texts:
Wondering if it's possible to change the output that I'm getting from ElementAPI. I'm using the API to preload assets, and this is the output I'm getting.

{
    "data": [
        {
            "title": "Hero",
            "url": "assets/hero.jpg"
        },
        {
            "title": "Profile",
            "url": "assets/profile.jpg"
        }
    ]
}

This is great, and pretty much exactly what I need, but I'm wondering if there is a way to change the output so that, rather than using "data": I can use "manifest": which is what my preloader needs. Ideally, my code should look like this:

{
    manifest: [
        {
            "title": "Hero",
            "url": "assets/hero.jpg"
        },
        {
            "title": "Profile",
            "url": "assets/profile.jpg"
        }
    ]
}

Here also is my elementapi.php file:

namespace Craft;

return [
    'endpoints' => [
        'assets/data/assets.json' => [
            'paginate' => false,
            'elementType' => ElementType::Asset,
            'criteria' => [
                'limit' => null,
            ],
            'transformer' => function(AssetFileModel $asset) {
                return [
                    'id' => $asset->title,
                    'url' => $asset->url,
                ];
            },
       ],
    ]
];

If there isn't a way to do this in the plugin, is there a way to get the endpoint file and change it some other way?

Thanks!


texts:
Heyo - I have an entry form in which you select/upload assets (photos). The asset has a caption/copyright (custom)field attached to it, so ideally I'd tell them…

Click "Add Asset" and upload/select your photos
When the pills show up in the entry form, double-click them to add captions/copyright

But, I find that if you do the above, you won't see the caption/copyright field (just title and file name) unless you save the entry between steps one and two.

I can see why this could be … the images are probably in a holding position until you save the entry(?). But just wondering if someone can confirm I'm not mucking something up, or maybe has a workaround?

It seems weird to have a note on the entry form that says "Reminder: 'Save and Continue Editing' to add captions to the images.

Same issue also comes up when you need to upload assets in a field, then in a subsequent field choose one of the assets (say, an entry form where you upload a group of images, then want to select one of the images to be the group's thumbnail).

Any ideas? Tks in advance.


texts: Craft 2 - Returning Value in Variable from Plugin to Template

texts:
I am working with a plugin and wish to return a value from it to the template that calls it.  In my plugin, there is an XML feed call, and I would like to pass a value(variable) from the plugin to the template that indicates whether there is any value for a particular XML query.

I currently am working with a Plugin Variable, which returns the XML output.
How would I be able to return a second value to the template for a conditional 'display/don't display' value?  Would I need to set up a second class, apart from my main XML feed variable?

Thanks.

Here is the basic layout of the plugin:

XmlFeedVariable.php

<?php
namespace Craft;

class AiPaginationTestVariable
{
        public function AiPaginationTestVariable($optional = null)
        //the '$optional' in the function call passes to the xml call for the query
            {
            //performs XML call and string assembly here, then echo's to output
            //if there is no xml returned, I would like to do this:
            //$xml_return='no';
            //then have the template pick it up.
            }
}


texts: Craft Commerce: Sage Pay - Redirect Required after payment?

texts:
When I test with my payment gateway (Sage Pay) I get a server error stating Craft Commerce isn't providing a redirect after payment is received:

Server error 5006: Unable to redirect to Vendor's web site. The Vendor failed to provide a RedirectionURL.

This is what is shown in my error logs:

195.170.169.29 - - [20/Jul/2016:09:05:17 +0100] "POST /index.php/actions/commerce/payments/completePayment?commerceTransactionId=9&commerceTransactionHash=b965d6bb8ca17ffc475849ab878721d5 HTTP/1.1" 404 50171 "-" "SagePay-Notifier/1.0"

Does anyone know what might be causing the redirect issue?


texts: Force Download a file using an Ajax request or Task

texts:
The following code doesn't seem to work when called using an Ajax or Task but it does work otherwise:

craft()->request->sendFile($file, IOHelper::getFileContents($file), array('forceDownload' => true));

I was wondering, Is it not possible to force download a file using an Ajax or Task?

Any help much appreciated!

Many thanks


texts: How to omit certain tag from (% cache %)

texts:
How can I omit a certain tag from being cached?

I have a large page with a fair few queries but halfway down I am loading in a Freeform Form field which cannot be cached. But I'd like all of the content below it to be..


texts: 'Could Not Find Your Craft/ Folder' After Updating

texts:
I updated to the latest version of Craft, and I am getting this error:

  Could not find your craft/ folder. Please ensure that $craftPath is set correctly in /storage/xxxxxxx/www/public_html/index.php

I have updated the same way each time. This is the first time I am seeing this error.

The files are setup like this:

Server

www/

craft/
public_html/

index.php

This is what the index.php file has always been:

https://cl.ly/281K2H3a3r1y

Permissions are the same as the previous app folder: 775

Any ideas about what may be causing this? As I said, I have updated Craft several times before without any problems. I've also read other threads on this and didn't find a solution that works for me. I am wondering why this would be a problem now, when it hasn't been an issue during previous Craft updates?

Thank you for any help you can give!


texts: Dynamic upload location for Super Table within a Matrix field?

texts:
I'm trying to set dynamic upload locations for my asset fields that are in a Super Table field within a Matrix field. So it's Matrix > Super Table > Asset field. I'm getting the following error when I save an entry, though. Could not resolve the subpath “{owner.section.handle}/{owner.slug}”.
Omitting the owner part doesn't work either.

Any ideas? Thanks!


texts:
I'm trying to build what's basically a blog page, but spread throughout the posts we want some of our tweets as well. Obviously we have the entries from Craft, and I've found this plugin which I can use to pull in our tweets.

My question is how can I merge our entries and tweets and order them by date?

I was thinking of creating an array with the entries, then pulling in the tweets and merging them into the array and then ordering them by date.

Is this possible?


texts: Is it possible to get the md5 hash of Craft's latest version from the download server?

texts:
It is possible to programmatically download the latest version of craft. But is it also possible to get this file's md5 sum directly from the server?

I'm thinking about something like this:

http://buildwithcraft.com/latest.hash

I am asking this because I'm currently writing a Salt formula to install Craft. I intend to use salt.states.files.managed, which is capable of downloading a file only if it has a different md5 sum than an already downloaded version of the file.


texts: Steps to publish a craft website from local to server

texts:
is there any resource that list all the steps to publish a local finished website to the final server?

Thanks!


texts: My tasks don't seem to be running as a background process

texts:
I have my plugin working now so that I can email users who's accounts will expire in 7 days time. The users are being selected correctly and the emails are being sent as expected. However, the tasks don't seem to be running in the background. I was expecting that when I hit the controller the task will be triggered and the page would immediately return saying "emails sent". Instead it seems it waits until the emails are sent before returning "emails sent". I'm worried that if the number of emails is large the page will timeout before it completes. It was my understanding that tasks run as a background process but may I have miss understood. Can anyone explain them to me in more detail?

For reference here is the controller and the service of my plugin:

class AcmeNotifications_NotificationsController extends BaseController
{

// let anyone run the controller actions
protected $allowAnonymous = array('actionSendEmail');

public function actionSendEmail()
{
    craft()->acmeNotifications_notifications->sendReminderEmail();

    //Make sure we kick the task off

    if (!craft()->tasks->isTaskRunning())
    {
        $task = craft()->tasks->getNextPendingTask();

        if ($task)
        {
            craft()->tasks->runPendingTasks();
        }
    }

    craft()->end();
}
}

and:

class AcmeNotifications_NotificationsService extends BaseApplicationComponent
{
public function sendReminderEmail()
{
    //Get all users whos account will expire in 7 days
    $user_criteria = craft()->elements->getCriteria(ElementType::User);

    $user_criteria->userExpiryDate = date('Y-m-d',strtotime("+7 days"));

    $users = $user_criteria->find();

    if($users){
        //Create array of user email addresses
        $user_emails = array();
        foreach ($users as $user) {
            $user_emails[] = array("to" => $user->email);
        }

        //Create an EmailModel
        $email = new EmailModel;

        //Set the global attributes
        $email->fromName = 'Joe Blogs';
        $email->fromEmail = 'joe.blogs@example.com';
        $email->subject     = 'Your account will expire in 7 days';
        $email->htmlBody    = 'The message';

        //Create the RecipientsModel and add the user emails
        $recipients = new Mailer_RecipientsModel();
        $recipients->recipients = $user_emails;

        if( $recipients->validate()){
            //Create mailer task
            craft()->mailer_main->newMailer($recipients, $email);
        }

        echo "emails sent";
    }
    else{
        echo "no emails to send";
    }
}

}


texts: Does Redactor have a button that adds a horizontal rule ( tag)?

texts: Does Redactor have a setting for a button that adds a <hr> tag?


texts: Yii Toolbar triggering mixed content warning in CP

texts:
I've enabled Show the debug toolbar on the Control Panel in my Craft Admin account in a local development environment that uses SSL. As soon as I enable it, I get the following error each time I load any page in the CP:

VM1685:1 Mixed Content: The page at 'https://domain.dev/admin/myaccount' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://craft3.dev/actions/debug/default/toolbar?tag=5a495cbcf3e15'. This request has been blocked; the content must be served over HTTPS.

SSL seems to be set up and working fine. I have the siteUrl variable in my general.php set up with an https url as well:

'siteUrl' => 'https://domain.dev',

What could be triggering this warning?


texts: Conditional to see if an Entries field in a user profile contains a certain entry ID

texts:
I've got a user profile field named Books. This is an Entries field that contains entries from the Books channel. The idea is that users will save books to their their profile to show they have read them.

I've also got a listing page which outputs all the books that are available.

I'd like to add a conditional that checks to see if the entry ID for a book is contained within the Books entries field in the current user's profile.

I've tried the following but it doesn't work. It outputs as true for every entry, even those that aren't saved to the user's profile. Any help would be appreciated, thanks.

{{ entry.title }}

{% if currentUser.booksField.contains("entry.id") %}
  I have read this book
{% else %}
  I haven't read this book
{% endif %}


texts:
I have a site which is online now.

This site has a set password, log in, etc. features for my users. My users are able to sign in or set password (all user operations) on any browser but when they try to set the password or login (all user operations) on mobile, the process is never ended and finally crashed.


texts:
Please help me build my sandwich locator maker :)

I have 3 categories, breads, meats, condiments
I have a Section called subShops with a matrix field.
My matrix field is called sandwichBuilder, fields: breads, meats, condiments
This matrix field is my entry I use for building the sandwiches that the suShops offer.

I want to keep my Categories to make it easy for structure and searching.

How can I build my query so that I can find all entries using a category of bread (over 200 sub categories for bread)?  I want the ability to only show those subShops that carry a certain breads based on URL segments (http://example.com/breads/spelt).

Basically, this above url example would list all the subShops that carry spelt bread, so it would display each group including - subShop, bread and typical meats that go best with spelt.

I have tried various ways and many hours trying to figure it out but with unusual results.  My code below is my baseline, but need some help from anyone willing to offer examples.  This is a pet project and I do plan on sharing the code when complete.

{% set entries = craft.entries.relatedTo(sanwiches).all() %}

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

{% for row in entry.matrixA %}
 {% for option in row.matrixB %}
    {{ option }}
    {% endfor %}
 {% endfor %}
{% endfor %}


texts:
Is it obvious why the task validation errors are not getting output in my log:

public function runStep($step)
{
    try
    {
        $entry = craft()->entries->getEntryById($this->_entryIds[$step], $this->_localeId);

        if (!$entry)
        {
            return true;
        }

        $newExpiryDate = new DateTime($entry->date);
        $newExpiryDate->add(new DateInterval('P1D'));

        // Update Expiry Date
        if($entry->expiryDate != $newExpiryDate)
        {
            $entry->expiryDate = $newExpiryDate->format('Y-m-d');
        }

        // Update Status
        $entry->enabled = true;

        // Save Entry
        if(craft()->entries->saveEntry($entry))
        {
            return true;
        }
        else
        {
            $error = 'Encountered the following validation errors when trying to save entry with the ID "'.$entry->id.'":';

            foreach ($entry->getAllErrors() as $attributeError)
            {
                $error .= "\n - {$attributeError}";
            }

            return $error;
        }

        return true;
    }
    catch (\Exception $e)
    {
        return 'An exception was thrown while trying to save the entry with the ID “'.$this->_entryIds[$step].'”: '.$e->getMessage();
    }
}

This task step is based on one of the Craft default steps but the error gets output without the specific validation issues:

  Encountered an error running task 1191 (Logic_UpdateEvents), step 1 of 1440: Encountered the following validation errors when trying to save entry with the ID "10295":


texts: How to list different product types separately in order summary?

texts:
I have two product types, 1) Materials and 2) Services.

Is there a way on the order summary page to list out the "materials" line items first, followed by the "services" line items below? I can't seem to figure out how to access the product type from cart.lineItems.

Here is what I'm currently using but it seems a little clunky:

Products

{% for item in cart.lineItems %}
    {% set variant = item.purchasable %}
    {% set product = variant.product %}
    {% if product.type == 'materials' %}

{{ product.title }} - {{ variant.sku }} ({{ item.qty }})

    {% endif %}
{% endfor %}

Services

{% for item in cart.lineItems %}
    {% set variant = item.purchasable %}
    {% set product = variant.product %}
    {% if product.type == 'services' %}

{{ product.title }} - {{ variant.sku }} ({{ item.qty }})

    {% endif %}
{% endfor %}


texts: How can I show only the sale discount applied to a completed order

texts:
I have two orders for the same product. One placed with a sale on the product enabled and the other with the same sale on the product disabled.

On the order details template for customers I have the following code

  {% for item in order.lineItems %}

    {% if item.purchasable.salesApplied|length or item.adjustments|length %}

        Original Price
        {{ item.price|commerceCurrency(cart.currency) }}

    {% endif %}

    {% if item.purchasable.salesApplied|length %}

        {% for sale in item.purchasable.salesApplied %}{{ sale.name }}{% if not loop.last %} + {% endif %}{% endfor %}
        {{ item.saleAmount|commerceCurrency(cart.currency) }}

    {% endif %}

    {% if item.adjustments|length %}
      {% for adjustment in item.adjustments %}

          {{ adjustment.name }}
          {{ adjustment.amount|commerceCurrency(cart.currency) }}

      {% endfor %}
    {% endif %}

        {% if item.purchasable.salesApplied|length or item.adjustments|length %}
          Total
        {% endif %}

      {{ item.total|commerceCurrency(cart.currency) }}

  {% endfor %}

I get the following results:

When placed: sale disabled
Currently: sale enabled

  Original Price £150.00
  25% off sale £0.00
  Total £150.00

When placed: sale enabled
Currently: sale enabled

  Original Price £150.00
  25% off sale  £47.50
  Total £102.50

When placed: sale disabled
Currently: sale disabled

  £150.00

When placed: sale enabled
Currently: sale disabled

  £102.50

item.purchasable.salesApplied is reflecting the current sale status of the item rather than the status when the order was placed. Is there a way I can get the name and value of the actual sales that were applied at the time of purchase?


texts: Enironment Variable being rendered literal

texts:
OK,
So created 2 variables in my local .env file
ASSET_BASE_URL="https://mysite.local/resources"
ASSET_BASE_PATH="/Volumes/yada/yada/yada/resources"
Then in the CP, created a new Asset volume and punched in
Base URL = $ASSET_BASE_URL/gallery
File System Path = $ASSET_BASE_PATH/gallery
Then front end renders an entries asset as:
<img src="$ASSET_BASE_URL/_480x480_crop_center-center_80_none/doddle-01.jpg" alt="Doddle 01" width="480" height="480">
THEN it creates a new folder named '$ASSET_BASE_PATH' at public site root.
I'm familiar with V2 it appears V3 has stepped up a bit. Could it be a Mamp issue with paths or somesuch trickery? Works if I hard code the paths as listed initially. All help greatly appreciated.


texts:
I originally had this setting in twig for gallery thumbnails:

{% set square150 = {
    mode: 'crop',
    width: 150,
    height: 150,
    quality: 75
    position: 'center-center'
} %}

<img width="{{asset.getWidth(square150)}}" height="{{asset.getHeight(square150)}}">

I noticed focal point doesn't apply, so I removed the position property as described on https://docs.craftcms.com/v3/image-transforms.html

So now it's

{% set square150 = {
    mode: 'crop',
    width: 150,
    height: 150,
    quality: 75
} %}

and the focal point works (I'm writing this out here because it took me some time to find out).

But it seems to me that the cropping is kind of generous, the area of the thumbnail is quite large. It does contain the focal point, true. But the focal point isn't always in the center of the image, as I'd have expected.

I'm sure the current behaviour is fine for many use cases.

In mine, what I'd expect is that for the focal cropping, the extract of the image is zoomed in so far that the focal point is in the center.

So something like...

{% set square150 = {
    mode: 'crop',
    width: 150,
    height: 150,
    quality: 75
    position: 'focal-point-center-center'
} %}

Is that possible and did I interpret the behaviour correctly?


texts: When creating new assets what should we put in base Url and document root file?

texts: I am not able to figure out what to put in base url and document root url while making new assets in craft cms


texts:
I've been building frontend pages for non-admin users with layouts matching the rest of the enduser site. For the "Set Password" page, I was able to build the form and set it up via the setPasswordPath config, no problem.

However, in addition to all my necessary frontend styles, this page also brings in a number of admin-side styles and scripts that greatly interfere with the layouts. Since any users seeing this custom page won't have admin access, these included files are certainly unneeded.

Outside of hacking the core, is there a more friendly way to exclude admin-level content on this non-admin page?


texts:
Is there a 2-factor authentication plugin for Craft? Or is there a way to secure the login for Craft CMS beyond the common installation instructions? I want to build a system that someone on a dynamic IP could access, so static IP's are a bit harder.

I was also thinking if there was a way to add another field to the login page, which was a decryption key, then use one the twig decryption method. If you don't have it, you'd see the data, but it would be all garbled up.


texts: Easy way to copy sections to a new install

texts:
Is there an way way to copy sections I have in an existing site to a new website I am doing with a fresh install?
E.g. To Copy the News Channel Section and all the field types
Also copy the structure section and all it's entry types etc?

I suppose I could copy the full database to the new install but then all the entries would need to be deleted, e.g. all the news articles etc.


texts:
I've been reading a lot of documentation (getSiblings, getDescendants etc) but can't get this to work:

I have a structure, named 'areas'. When showing an entry that is a child of an area in 'areas', I would like to list its siblings (that is in the same place in the hierarchy).

So for example on the url http://localhost/areas/some-area/very-nice-area-number-1, I would like to list very-nice-area-number-2, very-nice-area-number-3, very-nice-area-number-4 and so on (but not the current one (very-nice-area-number-1), of course).

To explain further, using the getNext function is the closest I've come, except that it only gives me one entry, and I want all other entries that holds the same place in the hierarchy under 'some-area'.


texts: Use only the sub categories from a category input

texts:
I have a category input. The category group has two levels.

When accessing the category input via Twig I am trying to only grab sub categories the user selected.  However when I use

{% set firstCat = entry.categoryInput.first %}
{% set cats = firstCat.getDescendants() %}

or children it grabs all the descendants from Categories > Group not just from the structure that was selected from the input.


texts: How do I know if a plugin supports Craft 3.1's project config?

texts:
Craft version 3.1 introduced the project config file.

The documentation mentions "plugins may not support it yet:"

  Any plugins that are storing configuration settings outside of their main plugin settings will need to be updated to support the project config. So there may still be some cases where changes need to be manually made on each environment.

Is there any way to know if a plugin for Craft 3 supports project config files?


texts:
How do I go about using a dynamic value to access a user field value? I have created a form builder for users and dynamically populate the user field based on the question's associated field.

<input name="fields[{{ question.fieldName }}]">

This works nicely but I am looking to pre-populate this input with a value if the user has previously provided and saved this info but I'm having trouble figuring out how to combine the field name with currentUser.

My first try was:

{% set fieldName = question.fieldName %}
{{ currentUser.fieldName }}

But that returns the following error:

Craft\UserModel and its behaviors do not have a method or closure named "fieldName".

Any help would be greatly appreciated


texts: How can I get custom user registration field parameters

texts:
I am allowing users to register on my site. I want to have the field "full name" on the registration page which, from there I will eventually split that value to populate the first name & last name fields for each user within the CP.

I have the actual in put in place:

twig

Full Name

<input id="fullName" type="text" id="fullName" name="fields[fullName]"
{%- if account is defined %} value="{{ account.fullName }}"{% endif -%}>

{% if account is defined %}
    {{ errorList(account.getErrors('fullName')) }}
{% endif %}

I have created a plugin to grab the value of the fullName input. I am using the init() method to listen for the saveUser event which is working perfectly.

MyPlugin.php

public function init()
{
    craft()->on('users.saveUser', function (Event $event) {
        error_log('-- saveUser event called --');
        error_log(print_r($event, true));

        if ($event->params['isNewUser']) {
            error_log('-- creating a new user --');

            error_log($event->params['fullName']);

            // split the fullname into firstname & lastname

            // populate first name

            // populate last name

            // save the new user
        } else {
            error_log('-- updating an existing user --');
        }
    });
}

I can see the data come through in the logs, but I'm not sure how to get to it.

error_log

...
[_attributes:Craft\BaseModel:private] => Array
                            (
                                [locale] => en_us
                                [elementId] => 123
                                [fullName] => aaa bbb
                                [id] => 123
                            )
...

The "fullName" parameter is getting populated, but when I log the out put:

MyPlugin.php

error_log($event->params['fullName']);

I am getting the error Undefined index: fullName. The user is getting created.

I can get to the data using this:

craft()->request->getPost('fields.fullName');

But then I'm not sure how to get that back into the user model so it gets saved.

EDIT

Sigh, well if it isn't obvious I don't give up too easily. I am able to capture the data like this. Is this the correct way? I will have a large number of registrations, so I'm trying to do things the correct way as much as possible.

MyPlugin.php

$event->params['fullName'] = craft()->request->getPost('fields.fullName');
error_log($event->params['fullName']);  // aaa bbb

Here is is in the CP:

The trick I'm seeing now is how to inject (for lack of better words) the values from fullName into firstName and lastName.

Here is what I am using to try to do that (without much success)

$name = explode(' ', craft()->request->getPost('fields.fullName'));
$lastName = array_pop($name);
$firstName = implode(' ', $name);

$event->params['fullName'] = craft()->request->getPost('fields.fullName');
$event->params['firstName'] = $firstName;
$event->params['lastName'] = $lastName;

"Full Name" (as you can see in the attachment) is getting populated, but "First Name" and "Last Name" are not. In the logs I can see it:

 [isNewUser] => 1
 [fullName] => aaa bbb
 [firstName] => aaa
 [lastName] => bbb

But the First Name & Last Name fields in the user account tab are not getting populated.


texts: I have just completed a fresh install of Craft CMS Pro and the Commerce plugin on my local host.  To view the website I go to localhost:8888 and I see the generic home page that says "Welcome to Localhost. Recent News - We just installed Craft" etc...   My question is, how do I view the page that my sample Commerce template is on that I dropped into the templates folder?  In my templates folder it is /templates/shop.  I also still have /templates/news/ in there that came with the Craft Pro in the templates folder as well. Maybe I'm confused but I thought my homepage would be overwritten with some sort of shopping website template, or do I need to go to localhost:8888/xxxxx?


texts:
Im trying to setup a front end user form with a category as a select box.  The box looks right but when i submit the form i get a new entry and other fields are filled out but the catgory fields are blank?

This is for a fieldgroup named borough and the field on the section is also called bourough

<form method="post" action="" accept-charset="UTF-8">
  <input type="hidden" name="action" value="entries/saveEntry">
  <input type="hidden" name="redirect" value="account/jobs?added={id}">
  <input type="hidden" name="sectionId" value="9">
  <input type="hidden" name="enabled" value="0">

<!-- other form fields -->

  {% set boroughs = craft.categories.group('borough') %}

  <select name="fields[borough]" class="form-control">
       {% for category in boroughs %}
           <option value="{{category.id}}">
             {{category}}
           </option>
       {% endfor %}
  </select>
</form>


texts:
I created a new single in Entries but the "preview" action isn't showing, which typically alerts me that I have not set it up correctly. In the singles list, if I click on the "blue globe" I get "couldn't find the page..."

to create the new single entry i did this:
Settings
Sections
New Section
Screen show of info in the section detail.

I know I am missing a very simply step because whenever I have to create this I always have this problem. But I can never recall how to fix it.


texts: How to add dynamic watermarks to images in Craft/Twig

texts:
I'm wondering if something is possible in Twig/Craft CMS that I used to do in ExpressionEngine and CE Image.

I want to output company logo images, but as they're all different shapes and sizes, I want to merge them with a white rectangle background image so that the page looks neat and tidy, e.g. like this.

This is how I did this in EE (using CE Image's watermark feature, so the logo is essentially a watermark on the white background):

{exp:ce_img:pair src="{my_logo_image}" width="250" height="150" allow_scale_larger="yes" parse="inward"}
  {exp:ce_img:single src="{my_white_rectangle_background_image}" width="300" height="200" crop="yes" allow_scale_larger="yes" watermark="{made}"}
{/exp:ce_img:pair}

Any ideas on how I'd do this in Craft at all? I'm not even sure where to start. I'm currently using the following, but this just outputs the logos/images, without even trying to merge them with the white rectangle background image, so any help on this would be appreciated, thanks.

{% set thumbnailImage = {
  mode: 'fit',
  width: 300,
  height: 200,
  quality: 80
} %}

{% for asset in entry.mainImage %}
  <img src="{{ asset.getUrl(thumbnailImage) }}" alt="{{ entry.title }}" />
{% endfor %}


texts: Is there a way to delete all entries within a section?

texts:
I am currently using FeedMe to import json data every night but I need to delete all entries before doing so to make sure that any orphaned entries are removed.

What is the best way to remove all entries within a section?


texts: Find Dropdown Option Labels That Are Assigned in a Section

texts:
I can get a list of option labels available in a dropdown field using the code below.  Is there a way to get a list of option labels that have been assigned to entries in a specific section?

{% for cocktailTypes in craft.fields.getFieldByHandle('cocktails').getFieldType.options %}
    <p>{{ cocktailTypes.label }}</p>
{% endfor %}


texts: Getting PHP error when trying to bind to onEditionChange event

texts:
I'm trying to bind to the onEditionChange event with something like this:

craft()->on('onEditionChange', function (Event $event) {
    craft()->womb->sendEvent($event);
});

However, i'm getting this error:

Undefined offset: 1

Seems it expects an dot in there. Is there another way to bind to this event?


texts: How can I loop through a collection in the index file?

texts:
I am basically wondering where does this section('services') is set up and how. https://github.com/craftcms/demo/blob/3f224f1f2e260c3e18190b16420c2e661cbb35ee/templates/services/_entry.html#L22

I need to loop through the collection entries on the _index.html to display a small card for each one, but I don't know how to reach them from the index.


texts:
This used to work in commerce 1: {{ order.billingAddress.firstName }} within a for loop of craft.orders.all().

No longer in Commerce 2. If I use this syntax I get

  Impossible to access an attribute ("firstName") on a null variable.

But when I do: {{ dump(order.billingAddress) }} then I see the firstName and it is clearly not null:

object(craft\commerce\models\Address)#2512 (35) {
  …
  ["firstName"]=> string(6) "Sophie"
  …
}

Why can't I access this? Also | first doesn't help. I also tried several versions with customer or primaryBillingAddress as mentioned in the changes doc But no luck so far.


texts: Display categories not related to an entry

texts:
I'm trying to output a list of categories that are not related to a particular entry (in order to show a list of services other than the service related to the current entry).

I have this code which lists the category that is related to the current entry:

  {% set categories = craft.categories.group('services').relatedTo(entry).all() %}
  {% nav category in categories %}

{{ category.title }}

  {% endnav %}

Is there a way of turning this on its head, so that the other, non-related categories are displayed? Something like a notRelatedTo(entry) parameter?


texts:
Is there a catch all error page template?

I'd like to use http://http.cat for my statuses.

(originally asked by Bryan Redeagle in Craft Slack)


texts: Add billing address to user on registration

texts:
I  am working on a craftcms + commerce project and I need to add a billing address to new user during its registration process. The idea is to have a billing address added to any newly registered user (no shipping address needed, as the shop will deliver no physical product).
I have been struggling with this and managed to get the user registered and the address record created in the DB with a 2-step form flow (first register user, then add address), but the address does not get linked to the user.
Is this possible or perhaps I am trying something completely against the way craftcms/commerce works?


texts: Craft 3 Plugin: Unable to add a new method to EntryQuery

texts:
I am developing a Craft 3 plugin and would need to add a new method like

{% for item in craft.entries.section('sectionName').birthday('XYZ123').all() %}

According to doc https://docs.craftcms.com/v3/element-types.html#element-query-class, I am using following code:

File: /by/prefix/element/Birthdate.php

    <?php
    namespace by\prefix\elements;
    use craft\base\Element;
    use craft\elements\db\ElementQueryInterface;
    use by\prefix\elements\db\BirthdateQuery;
    class Birthdate extends Element
    {
        public $birthdate;
        public static function find(): ElementQueryInterface
        {
            return new BirthdateQuery(static::class);
        }
    }

File: /by/prefix/element/db/BirthdateQuery.php

    <?php
    namespace by\tariffsinfo\elements\db;
    use craft;
    use craft\db\Query;
    use craft\elements\db\ElementQuery;
    use craft\helpers\Db;
    use by\tariffsinfo\elements\BirthdateElement;
    class BirthdateQuery extends ElementQuery
    {
        public $birthdate;
        public function birthdate($value)
        {
            return $value;
        }
    }

and I am getting error message:
Calling unknown method: craft\elements\db\EntryQuery::birthdate()

Could anyone please help what am I doing wrong.

Thanks


texts:
Is it possible to define custom user permissions in Craft?
I'm building some front end templates that are only accessible by logged in users. Certain parts of this members page should only be accessible to users with specific permissions. I know that I can create multiple groups and use template logic to show / hide certain pages. However, being able to define custom user permissions would be much more flexible.

Say I want to allow a user to access a form, but I don't want to grant access to the other permissions from a different user group.

{% if currentUser.can('submitForm') %}
    {# show form here #}
{% endif %}


texts:
The Rails cli has a runner feature that allows you to run a file (or a string of code) from the command line.

E.g. rails runner my-script.rb (where my-script.rb will run in the context of a fully bootstrapped Rails application). It's a fantastic way to write scripts/backfills/etc without needing to alter your application.

I know that craft includesyiic but it seems to be focused on migrations or code generation and not necessarily providing the same bootstrapped playground.

Is there an easy way to give an arbitrary script access to a bootstrapped craft application? My specific use case is that I want access to models and plugins to be able to migrate fields from one event plugin to another (this is actual content, not just a schema migration).


texts: All images uploading... except JPG files

texts:
No idea why but my local install of CraftCMS (in a MAMP environment) won't let me upload JPGs. PNG, GIF, even TIFF works (just for the heck of it). When I select the file in the browser dialog, it closes then shows the loader bar and spinning gif anim. No progress is ever shown and the spinning continues eternally. http://cl.ly/image/1a2l1W2t1P1x

Craft is up to date
Uploads on remote install works perfectly
Getting this error net::ERR_EMPTY_RESPONSE along with these details: http://cl.ly/image/3D2w1F2l2O1x
Checked my php.ini file and it allows JPG uploads

I realize this may not even be an issue with Craft but a server side issue. I just have no idea how to troubleshoot this. Any help would be much appreciated!

I also checked my phperrors.log file and I got only this which is from back in early Dec and seemingly unrelated.

  [08-Dec-2014 02:47:37 UTC] PHP Fatal error:  Allowed memory size of 33554432 bytes exhausted (tried to allocate 9792 bytes) in /Applications/MAMP/htdocs/sucasa/craft/app/vendor/imagine/imagine/lib/Imagine/Gd/Image.php on line 199


texts: Trouble calling service methods from primary module class

texts:
I created a module for Craft 3 using pluginfactory.io, and am unable to call services from the primary module class using $this->orders->method() as shown in the documentation.

The services appear to be registered correctly, as I'm able to call the service methods elsewhere in the module using the SiteModule::$instance->orders->method() format.

The line use modules\sitemodule\services\Orders as OrdersService is at the top of the module class, but removing makes no difference in being able to call those service methods from the primary module class.

What is the correct way to call service methods from a primary module class?


texts: How can I use categories to filter entries?

texts:
It's a pretty basic question, but for some reason all of the possible solutions do not work for me.

I tried this: https://craftcms.com/docs/relations#the-relatedTo-param
And also this (which I really expected to solve my problem): https://craftcms.com/support/entries-related-to-category

I'm pretty sure I may have overlooked something, but I can't see what.

I made this:

{% set lastSeg = craft.request.lastSegment %}
{% set meubels = craft.entries.section('meubels').relatedTo(lastSeg) %}

And use this as a test:

{% for meub in meubels %}
test

{{ meub.title }}

{% endfor %}

According to every answer to related questions this should work, but unfortunately it returns nothing. But lastSegment does return the required string from the URL. (At least, I'm assuming this must be a string)

I made a list of categories which all seem to route just fine, no problems there.


texts: Getting Commerce Products using Element API in Craft 3

texts:
I am trying to get Products using the Element API plugin. I set the 'elementType' to Commerce_Products, CommerceProducts, etc.., but the endpoint keeps returning:

  Endpoint has an invalid elementType

This is my endpoint:

use craft\commerce\elements\Product as ProductsModel;

return [
    'endpoints' => [
        'api/search' => [
            'elementType' => 'ProductsModel',
            'paginate' => false,
            'pretty' => true,
            'criteria' => [
                'limit' => 15,
                'search' => (Craft::$app->request->getParam('keyName')) ? 'title:'.'*'.Craft::$app->request->getParam('keyName').'*' : ''
            ],
            'transformer' => function(ProductsModel $product) {
                return [
                    'title' => $product->title,
                    'url' => $product->url
                ];
            },
        ],
    ]
];

How do I fix it?


texts: How to render plugin templates in Craft CMS 3?

texts:
I cannot find a way to render templates from a plugin controller in Craft 3. I feel as though I've tried every variation advised online but for some reason this still isn't working.

<?php

namespace abc\members\controllers;

class LoginController extends \craft\web\Controller
{
    public function actionForm()
    {
        $this->renderTemplate('abc-members/login.html');
    }
}

The plugin handle is "abc-members".

The plugin has a "templates" directory with "login.html".

I've tried the following, with and without the .html extension, but none can find the template:

$this->renderTemplate('abc-members/login.html');
$this->renderTemplate('abc-members/templates/login.html');
$this->renderTemplate('abc-members/src/templates/login.html');
$this->renderTemplate('abc/members/src/templates/login.html');
$this->renderTemplate('plugins/abc/members/src/templates/login.html');

The following works fine but then I cannot include templates from the installation's main template directory.

<?php

namespace abc\members\controllers;

class LoginController extends \craft\web\Controller
{
    public function actionForm()
    {
        \Craft::$app->view->setTemplatesPath(__DIR__ . '/../templates');
        $this->renderTemplate('login.html');
    }
}

Any suggestions as to where I'm going wrong? I find the Craft 3 docs are a bit lacking in the whole area of plugin controllers, routing and templates other than in the Craft 2 => Craft 3 upgrade guide.

Thanks


texts:
We have a user signup form (see http://thinkdif.co/me/signup) that has some extra required fields. When a craft field us missed out, the error code below works, however when a custom User field is not completed, the page does not save, but no error is presented.

We require errors on custom user signup fields, and also on the 'Update your profile' page that is presented later in the workflow.

Thanks for any help or examples. End goal is to have good required fields throughout the user workflow.

Dan

Example error code:

    {% if account is defined %}
    {{ _self.errorList(account.getErrors('occupation')) }}
    {% endif %}

Edit:

Here is a gist of the full page. https://gist.github.com/slipstreamstudio/d8dd801d722c3f275b74


texts: In some instances of my websites the icons don't load properly.  Everything else in the website works, but the icons don't load.  The other websites on the same server with the same php.ini file don't have this issue, just this one website.


texts: Why is the summary and body returning an empty object using the Element API?

texts:
I'm not sure what I'm missing, but I'm getting an empty object back from the Element API for the summary and/or body for any given entry.

elementapi.php

...
'transformer' => function (EntryModel $entry) {
    return [
        'title' => $entry->title,
        'url' => $entry->url,
        'summary' => $entry->summary
    ];
},
...

Here is the json I am getting back:

{"data":[{"title":"My Title","url":"http:\/\/local.mysite.dev\/section\/my-entry","summary":{}}

EDIT/SOLUTION

Thank you again @Oliver!

I wanted to update my post in the event someone else came across it. I am using mustache.js to render my html from the json that is getting output via the ElementAPI.

By casting the summary as a string, you will need to tell mustache to parse the html by using three curly-brackets instead of the usual two.

mustache

Title: {{title}}

URL: {{url}}

{{{ summary }}}

Otherwise you will end up with something that looks like this:

Title: My Title
URL: www.mysite.com

This is my summary


texts: Selecting a subset of entries, based on a relatedTo call

texts:
I have a question about relations... or maybe its also about making queries. First I want to select a set of data, and then I want to select a subset of that data, based on a relatedTo call.

If I first do this:

{% set caseEntries = craft.entries.section('case').relatedTo({ targetElement: creatorEntry, field: 'creator' }) %}

then, to get a sub-set of what I got before, do this:

{% set caseEntries = caseEntries.relatedTo('and', { targetElement: categoryEntry, field: 'caseCategories' }) %}

it seems as if the first relation is “forgotten” (note that it wont work if I dont include an “and” in the second related to call). Do I have to add the first relation in the second call? Feels like repeating myself... I want to avoid doing this:

{% set caseEntries = caseEntries.relatedTo('and', { targetElement: creatorEntry, field: 'creator' }, { targetElement: categoryEntry, field: 'caseCategories' }) %}


texts: FeedMe: How to import data into the Matrix field of a section?

texts:
I have a section called "Musicians" which is already set up and populated.
It has an unpopulated "Albums" Matrix field which will hold each artist's albums.

I have exported the albums as a separate JSON file. Now I like to import them into the existing "Musicians" section's Matrix field.

But my three test album entries fail to get added to the corresponding artist.

I've assigned the correct JSON fields to the matrix, but I'm not sure how to connect each album with the existing artist – adding the artist Title field or title slug in FeedMe doesn't do the job.

What am I missing?

Here is a sample JSON structure:

{
  "title":"Milyakburra",
  "url_title":"milyakburra",
  "album_artist_relate":[
     {
        "entry_id":"2590",
        "title":"Emily Wurramara",
        "url_title":"emily-wurramara"
     }
  ],
  "album_release_date":"2018-06-01",
  "album_description":"",
  "album_tracks_1":"Lady Blue\nMilyakburra\nNgarrikwujeyinama\nCarry Me Home\nBlack Smoke\nLullaby\nHey Love\nTap Sticks\nYimenda-Papaguneray (Turtle Song)\nBlue Moon, Black Sea\nBlack Boy",
  "album_tracks_2":"",
  "album_cover":"/images/uploads/resources/music/emily-wurramura_milyakburra.jpg",
  "album_fishpond_link_id":"",
  "album_amazon_link_id":"",
  "album_itunes_link_album_name":"milyakburra/1388866633"
},

Edit:
It looks like FeedMe has difficulties finding a match between a musician entry's title field and the album_artist_relate title field. If I manually add a new title field at the top of the structure (and rename the existing one to "title2") FeedMe correctly inserts the data into the matrix.


texts: Blank pages after moving from Local development to Production

texts:
I'm very new to Craft and recently built my first Craft-powered website (locally) and it works fantastic. Now, I want to move it to production, and I'm having trouble. Locally, everything went very smooth with Composer but unfortunately, I can't do that on my hosting.

I went through the following steps:

Made a database backup through the Craft admin
Made a new database my website and imported it
Moved all files from local to production
Changed .env with the correct credentials and info

But after this, I only get blank pages (both index and admin)

What am i missing? Is there a better way (without using Composer) to deploy?


texts: Identify immediate siblings block type in matrix

texts:
I have a type of content that i use on the homepage of a site I am building, the code is shown here:

    {% for point in entry.keyPoints %}

{{ point.heading }}

                {{ point.text }}

    {% endfor %}

This does exactly what i want it to do. It opens a UL and then loops through the different items which are LI's and output accordingly.

I want to use this same type of content on inner pages however as a matrix block TYPE rather than being the only type of content like on the homepage in the above example.

The problem then is that the FOR loop starts before i even know if this is the type of content i am dealing with so I can't appropriately wrap this type in a UL.

I can solve this by checking if it is the FIRST of TYPE and LAST of TYPE and outputting the opening and closing UL tags that way.

I then run into another problem that the first and last of this type are not necessarily adjacent to each other. If that is the case then all the other content TYPEs in the matrix between the FIRST and LAST of this TYPE will be inside of the UL as well.

My question then is how can i determine if the other matrix blocks that are immediately adjacent to this TYPE are of the same TYPE and if they are don't close the UL and if they are NOT then close the UL.

My code to determine what type is is just a simple FOR loop and then inside it a series of conditionals checking the TYPE and then outputting the appropriate content accordingly.


texts: Is it possible to set up predefined tags in craft which can then be used as either a select list or checkbox selection by editors, so as to only give them the option of adding preset tags as opposed to adding any tag they want?


texts: If Most Recent Instance of a Block Contains X in Y Field Then Do Z

texts:
I’m looping through blocks in a matrix field on a page. In multiple different blocks in that loop, all of which could be different block types, I’d like to have an if statement that basically says if the most recent instance of a particular block type (we'll call it "referenceBlockType") contains x in y field, then do z. Note that by most recent instance I mean the closest previous instance of referenceBlockType relative to the position of the block that contains the if statement.

referenceBlockType appears multiple times in the loop and is not necessarily a direct sibling of the block that is referencing it, nor is it always the first or last field in the loop.

How would I do that? Thanks!


texts:
Is it possible to add custom fields to a contact from that is using the
MandrillForm Plugin?

I need to add a field for phone


texts: Assets Transform returns "Image cannot be found."

texts:
I have two assets sources, Slideshow and Products. I have six Image Transforms.

On the home page I'm using a structure channel to play a simple slideshow and I'm using 3 transforms and all is working fine.

This code works fine:

{{ entry.productPhotos.first().geturl() }}

But this code throws an error:

{{ entry.productPhotos.first().geturl('productSlide') }}

If you go on my assets source path, the file is uploaded but the transform folder doesn't exist.

I tried clearing cache, deleting records in craft_assettransformindex, and most of the things suggested here, but with no luck. The weird thing is that the other Structure with the assets Slideshow works fine so it couldn't be something with the paths.

I'm using 'generateTransformsBeforePageLoad' => true, in my config/general.php file.

You can see on my phpMyAdmin screenshot that the filename is NULL in the table craft_assettransformindex but all the other transforms for the slideshow are there:


texts: How can I get only those entries with non-empty assets field

texts:
Since Craft 2.0 it is possible to pass :empty: and :notempty: to ElementCriteriaModel parameters when you’re looking for empty/non-empty values. If you are for example looking for all entries with a non-empty text field myTextField, you can do this:

{% set entries = craft.entries.section('mySection').myTextField(':notempty:') %}

However this syntax doesn't work for asset fields and I can't figure out how that syntax has to be.

An alternative would be to use the search function:

{% set entries = craft.entries.section('mySection').search('myAssetField:*') %}

But I generally try to avoid using the search parameter in queries whenever possible. It is probably not that much of a performance killer but by avoiding it I don't have to worry about my search index.


texts: Show error when normal user try to login in CP

texts:
when I login to my Craft CMS website via a normal user that user doesn't have permission to login to the Control Panel, it displays some error like HTTP 403 – Forbidden – yii\web\ForbiddenHttpException.

This error is correct but I want to display some message instead of this error.


texts: Using @webroot in templates returns a different path, can't override in config

texts:
I'd like to use @webroot in my templates using the {{ alias('@webroot') }} tag. However, when I do this it returns a longer path than what is returned when I use @webroot in the control panel.

For instance, I generate asset paths using @webroot in a control panel field. This works well: in my local dev environment, the path is referenced correctly from the root of my local web server. However, when I use the alias tag directly in a template, the path begins instead at my local hard drive.

I've tried to override this using an environment variable: WEB_ROOT="/xxx/web/" and then referencing it in the config:

'aliases' => [
   '@webroot' => getenv('WEB_ROOT'),
],

But it that doesn't seem to do anything. Even if I change the path to 'hi', both instances of @webroot remain the same. The assets using the @webroot path generated from the control panel continue to work (referenced from my web server) and the template continues to render the longer path (referenced from my local HD).

What am I missing here? Is there a cache that needs to be refreshed?


texts: Sorting SuperTable Field with SuperSort?

texts:
I'm trying to use supersort to sort my entries based on date values in a supertable field.

This is what I have so far but it's not working.

{% set artists = craft.entries.section('artists') %}
{% set entries = artists | supersort('sortAs', '{{ tourDates.tourDate }}') %}

tourDates is the supertable handle tourDate is the date field in the table. There can be multiple date entries in one table so it would need to bring them out in order as well.

I'm not sure this is even possible.


texts:
I'm sure there must be an easy way to do this, but I can't work it out...

I'm trying to add date filters to the formerly submission export, but I can't work out how to filter out the submissions between 2 dates. I got it working with a bit of a hack:

$criteria = craft()->elements->getCriteria('Formerly_Submission');
$fromDate   = craft()->request->getPost('fromDate');
$fromDate = DateTime::createFromString($fromDate,   craft()->timezone) ;
$toDate   = craft()->request->getPost('toDate');
$toDate = DateTime::createFromString($toDate,   craft()->timezone) ;

//A bit of a hack, in my case these date fields are always the same anyway
$criteria->dateCreated = '>= ' . $fromDate->format(DateTime::MYSQL_DATETIME);
$criteria->dateUpdated = '<= ' . $toDate->format(DateTime::MYSQL_DATETIME);

I tried all sorts of ways to do it properly, things like

$criteria->dateCreated ='and, > ' . $fromDate->format(DateTime::MYSQL_DATETIME) . ', > ' . $toDate->format(DateTime::MYSQL_DATETIME)'

anyone know how to do it properly?


texts: "Could not find composer.json file" error in CraftCMS 3

texts:
I recently updated my CraftCMS 3 with the help of Composer.

When I try to install a plugin with the plugin store, I get an error saying that Craft couldn't find my composer.json file. He proposes me to define the  CRAFT_COMPOSER_PATH in index.php. But, when I do, I still get the same error.

My composer.json is the root of craft folder. I seriously don't know how to solve my problem.

Here's a screenshot (sorry I use Craft in french):

Thank you!


texts: Display all entry titles on one line during FOR loop

texts:
I have a FOR loop that should be displaying all the entry titles on one line. But instead, it is outputting them on separate lines.

I want to see:

Developer: Jane Doe, Jim Doe

Instead, I am getting:

Developer: Jane Doe
Developer: Jim Doe

My code:

{% set developers = entry.GamesDeveloper %}

{% for developer in developers %}

Developer: {{ developer.title }}

{% endfor %}


texts: Why does getUrl fail when using transforms on a translatable asset?

texts:
I have a project with the following code:

{% if entry.filmPoster | length %}

{% elseif entry.locale('en_gb').filmPoster | length %}{# fall back to English if there is one #}

{% endif %}

filmPoster is an Asset field, and it is translatable. It's set to restrict uploads to a single folder, and the upload location is [whats on] {slug}

In the back end, I go to an Entry and upload an asset in this field in English, save, switch to Welsh, upload the Welsh version of the asset and save. In both cases, in the CMS, I can switch between languages for the entry and see the correct image asset in each locale. If I then look on the server, I can see the correct files have been saved in the appropriate file-path:

/content/whats-on/entry-title/image-name.jpg
/content/whats-on/entry-title-in-welsh/image-name-welsh.jpg

On the front end template, however, the image for the Welsh version is a 404 broken image.

However, if I remove the transform from the equation, the correct image loads...

{% if entry.filmPoster | length %}

{% elseif entry.locale('en_gb').filmPoster | length %}{# fall back to English if there is one #}

{% endif %}

Why is attempting to use a transform breaking? What have I got wrong?

All I see in the logs is:

2016/10/13 09:39:03 [warning] [application] [Forced] Image “entry-title-in-welsh/image-name-welsh.jpg” cannot be found


texts: Should my controllers actions 'return' when rendering templates?

texts:
When developing a plugin, I am registering routes to controller actions. Other frameworks, read that as Laravel, typically return the controllers response.

public function showProfile($id)
{
    $user = User::find($id);

    return View::make('user.profile', array('user' => $user));
}

However, in Craft to render a template from your controller you would use the following.

public function actionPluginIndex()
{
   $this->renderTemplate('pluginName/template');
}

At the same time, you can also return the rendered template this way and it functions as expected.

public function actionPluginIndex()
{
   return $this->renderTemplate('pluginName/template);
}

Looking at craft/app/controllers/BaseController.php templateRender method shows that it accepts a parameter return.

So the real question is to return or not to return and I was hoping for a more technical explanation on the way Craft handles this.


texts: Exception on trying to install Craft CMS 3 plugin

texts:
I'm trying to create a new plugin for my website in Craft CMS 3, just to do some really basic stuff, like parsing an XML file from an external site.

I created it using the plugin creator at https://pluginfactory.io/ as per the craft docs. I have only included the controller and variable components.

I've added it in to my composer.json file, run the composer require command and it has successfully been added to the plugins list with my craft install. However, when I go try and install it from the plugins page, I get this error:
"The use statement with non-compound name 'Craft' has no effect in /var/www/html/[websitename]/plugins/[websitename]/src/[websitename].php at line 15"

This is what the code that has been generated looks like (website name redacted):

11 namespace \[websitename];
12
13 use \[websitename]\variables\[websitename]Variable;
14
15 use Craft;
16 use craft\base\Plugin;
17 use craft\services\Plugins;
18 use craft\events\PluginEvent;
19 use craft\web\UrlManager;
20 use craft\web\twig\variables\CraftVariable;
21 use craft\events\RegisterUrlRulesEvent;
22
23 use yii\base\Event;

Does anyone have any idea what is happening here? I've tried reading the plugin docs but I can't see what is going wrong. I assume the plugin creator is generating files correctly, I've used it several times for Craft 2, but this is my first attempt at a Craft 3 plugin.

Thanks, Jai.


texts: Looping Related Entries with a Super Table

texts:
I need to loop related entries.

I am using a SuperTable field with the handle "related" with an entry field with the handle "contentEntry" and two text fields for alternative text and descriptions.

The "contentEntry" field is limited to two entries being selected. The issue I'm having is that the following code repeats the first entry twice and doesn't loop and display the second. What am I doing wrong?

{# Related Entry #}

{% set relatedEntries = block.related.all %}
{% set relatedEntry = block.related.contentEntry.all() %}
{% set relatedAltDesc = block.related.altDescription %}
{% set relatedAltTitle = block.related.altTitle %}

{% if relatedEntries %}

            {% for entries in relatedEntries %}

              {% for rel in relatedEntry %}

                {% if relatedAltTitle %}
                  {{ relatedAltTitle }}
                {% else %}
                  {{ rel.title }}
                {% endif %}

                {% if relatedAltDesc %}
                  {{ relatedAltDesc }}
                {% else %}
                  {{ rel.previewDescription }}
                {% endif %}

              {% endfor %}

            {% endfor %}

{% endif %}


texts: How can I time-profile the page load for a Craft request?

texts:
I would like to see how long plugins take to load, as well as other aspects of the page (loops and database requests).

My webpage can take ~2-3 seconds to return the initial request. It seems high and I'd like to figure out how I can optimize it.

Also, as I understand it, every plugin is loaded on each request (even if it's not loaded for that page). Is this true? And if so, why is this the desired behavior? If a plugin is performing poorly it can bring the entire website to a standstill (this just happened to me: Website taking 30+ seconds to load).


texts: Solspace Calendar: List only recurring events

texts:
I have a calendar for a location that combines recurring events with individual events. I'm trying to list out the upcoming events for the next 90 days, but I'm running into issues with the repeating events. I'd like to list the individual events by dates, and then have the repeating events listed once, with their rule (i.e. Every Monday: Event Title).

{% set eventOptions = {
    calendar: 'otherEvents',
    dateRangeStart: 'today',
    dateRangeEnd: '+90 days',
} %}
{% set otherEvents = craft.calendar.events(eventOptions) %}

This gives me a list of all events, but it is overwhelmed by recurring events. I can turn them off by adding loadOccurrences:false, but I'm having trouble loading them on their own.

 {% set eventOptions = {
    calendar: 'otherEvents',
    loadOccurrences: false,
} %}
{% set otherEvents = craft.calendar.events(eventOptions) %}

This gives me a list of individual events and a single instance of each repeating event, but it also shows expired events. As soon as I add a date range, the recurring events go away.

Is there any way to get JUST the recurring events, listed once, with their repeat rule? Essentially, i need a loadOnlyOccurrences option.


texts: From what I understand, the "Default" .json-file is hardcoded into the plugin, and always selected by default when creating a redactor field. I always use my "Standard.json" or "Simple.json"-files on my projects, the Default config has way too many options for less design savy clients to mess things up, so I try to keep things simple. Is there any way to make my "Standard.json" selected when creating a new field so I don't have to remember to change the .json-source every time?


texts: What's the best way to clear cached JSON responses from a third-party API?

texts:
I'm building a plugin to browse store orders via a third-party API. I make various requests to URLs that can include query parameters:

/customers
/orders/e8b48e72-9c7f-4d6f-91aa-2f7238bdf936
/orders?offset=0&limit=250&from=2014-05-26T22%3A58%3A38%2B00%3A00&to=2014-06-26T22%3A58%3A38%2B00%3A00

I've just started using Guzzle and more importantly craft()->fileCache to keep results around for a few minutes and speed up browsing. I use the query URI as the key for the cache:

 craft()->fileCache->set($query, $response->getBody(true), 600); // store result for 10 minutes

A web hook gets hit with every new order that comes in, making it an ideal time to clear out these caches I've set—but I have no idea how.

Is there any way I can tag this plugin's caches or somehow clear out only those I've made, rather than get overzealous with craft()->fileCache->flushValues()?


texts: How do you use a for loop to output to JS?

texts:
I have a map generated in JS.

I need to set the country-id and url for each country.  Both 'country-idandurlare fields in my Craft categories groupcountries`.

{
  "country-id": "FR",
  "url": "http://mysite/country/france"
},

I know (basically) how to output to JS for use in my templates.  Here is a link to an earlier question I asked on how to output to JS. This time my question is not how to include JS, but how do I generate a specific output.

How do I incorporate a for loop that produces the desired output for each member of the category country.

{% set nations = craft.categories.group('country') %}
{for country in nations %}
{
"country-id": "{{country.CountryCode}}",
"url": "{{country.url}}",
},
{% endfor %}

Part of the problem is how to I get the loop to also output the script brackets, quotes, commas and attributes that surround the data for each country?

UPDATE -- MORE INFO --- This is the full JS that the above is taken.


texts:
I'm in charge of creating a website with a 'most popular' section.

I was wondering if there was any native way/plugin that lets me sort craft entries based on most popular?

I know Expression Engine has view tracking, I'm not sure if Craft does anything similar.

Thanks!


texts:
I'm using craft-stripecheckout to accept payments on my site, but want to email the user with the custom fields after they have been redirected.

Easiest way to describe this is below:

Page 1 - User is asked for payment amount and other custom inputs such as age.

Page 2 - Confirmation of details is shown, and Stripe payment button appears.

Page 3 - User is redirected here via the plugin after payment is completed. this is when the email is sent with custom fields, such as age

What is the best way to store all of the POST data, and use it again on the confirmation page?


texts: Does Craft automatically sanitize user input?

texts:
Can I rely on Craft to clean user input, is safe to save the following data like in the below example function, if not, what is the Craft best practice for cleaning(making it safe) user input?

public function actionCustomSaveUser(){

    $user = new User();
    $user->newPassword = $_POST['password'];
    $user->username = $_POST['username'];
    // and more $_POST ...

    Craft::$app->getElements()->saveElement($user, false);
    // etc...

}


texts: One structure vs a structure per section?

texts:
I'm new to Craft CMS and I would appreciate some advice re the best approach to take for modelling content.

I'm coming from an ExpressionEngine background, where I would typically use one pages channel for standard text pages, usually in conjuction with the Structure add-on to generate a nice site tree in the control panel where users could move page entries around between various sections as needed.

Now in Craft, I see a Structure type and it's tempting to have one structure called Pages to act in a similar way. This would enable the main nav for the site to be dynamic using the nav tag, and users could easily move pages wherever they want site wide.

So I would end up with the following content model:

Singles: Homepage
Channels: News, Events etc
Structures: Pages

Pages would end up as a site map excluding the homepage, with each top level entry being a site section e.g.

About
-History
-Team
News (page used for news landing)
Events (page used for events landing)
Visit
-Facilities
-Opening Hours
Contact
etc

However, I see that the Happy Lager demo site takes a one structure per section approach. Also, early on in the Mijingo video series, it cautions against using one structure for most/all your site.

I am keen to use best practice from the off, so would appreciate if you could advise whether having one master pages structure is a valid approach or why it's a bad idea.

Many thanks


texts:
I was changing some entry types to allow for a parent/child structure when I realised that this was already something Craft could do natively. When I undid my changes and attempted to assign a parent page, I am given the following error:

  Object of class Craft\Entry Model could not be converted to int.

I am still fairly new to Craft so I am quite limited in understanding exactly what I did to break it. I can still create and edit entries, I just can't set a parent page anymore.

******************************************************************************************************
2017/10/13 22:37:16 [warning] [application] There was a problem parsing the feed: cURL error 60: SSL certificate problem: unable to get local issuer certificate

******************************************************************************************************
2017/10/13 22:37:58 [error] [php] Object of class Craft\EntryModel could not be converted to int (C:\wamp64\www\craft\storage\runtime\compiled_templates\9a\9a68f00c27a5bff3f289231a8d85ef2d821f962bf46e9f246c88cce64dc926f2.php:19)
Stack trace:
#0 C:\wamp64\www\craft\app\etc\templating\BaseTemplate.php(26): __TwigTemplate_22da5c53ac1ef5202e2f12c05417214f2feda1f7c6b451fbb37fa9ade742e5bd->displayWithErrorHandling()
#1 C:\wamp64\www\craft\app\vendor\twig\twig\lib\Twig\Template.php(403): __TwigTemplate_22da5c53ac1ef5202e2f12c05417214f2feda1f7c6b451fbb37fa9ade742e5bd->displayWithErrorHandling()
#2 C:\wamp64\www\craft\app\vendor\twig\twig\lib\Twig\Template.php(411): __TwigTemplate_22da5c53ac1ef5202e2f12c05417214f2feda1f7c6b451fbb37fa9ade742e5bd->display()
#3 C:\wamp64\www\craft\app\services\TemplatesService.php(388): __TwigTemplate_22da5c53ac1ef5202e2f12c05417214f2feda1f7c6b451fbb37fa9ade742e5bd->render()
#4 C:\wamp64\www\craft\app\helpers\ElementHelper.php(122): Craft\TemplatesService->renderObjectTemplate()
#5 C:\wamp64\www\craft\app\services\ElementsService.php(1556): setUniqueUri()
#6 C:\wamp64\www\craft\app\services\EntriesService.php(176): Craft\ElementsService->saveElement()
#7 C:\wamp64\www\craft\app\controllers\EntriesController.php(462): Craft\EntriesService->saveEntry()
#8 C:\wamp64\www\craft\app\framework\web\actions\CInlineAction.php(49): Craft\EntriesController->actionSaveEntry()
#9 C:\wamp64\www\craft\app\framework\web\CController.php(308): CInlineAction->runWithParams()
#10 C:\wamp64\www\craft\app\framework\web\CController.php(286): Craft\EntriesController->runAction()
#11 C:\wamp64\www\craft\app\framework\web\CController.php(265): Craft\EntriesController->runActionWithFilters()
#12 C:\wamp64\www\craft\app\framework\web\CWebApplication.php(282): Craft\EntriesController->run()
#13 C:\wamp64\www\craft\app\etc\web\WebApp.php(823): Craft\WebApp->runController()
#14 C:\wamp64\www\craft\app\etc\web\WebApp.php(287): Craft\WebApp->_processActionRequest()
#15 C:\wamp64\www\craft\app\framework\base\CApplication.php(185): Craft\WebApp->processRequest()
#16 C:\wamp64\www\craft\app\index.php(62): Craft\WebApp->run()
#17 C:\wamp64\www\public_html\index.php(19): require_once()
REQUEST_URI=/public_html/admin/entries/pages/90-cherries


texts:
i have a big problem on my site. One for loop requires more than 30 seconds. When i put the loop in a comment, the page loads shortly. So the loop must be the problem.

Is there any trick to accelerate a loop?

Here is the loop code:

{% for program in craft.entries.section('program_point').order('program_number') %}
    {% if program.block.first().title == program_block.title %}

            {% if program.type == "seminar" %}{% endif %}

{% if program.type != "seminar" %}#{% endif %}{{ program.program_number }}{{ program.title }}

            {% if program.short_description|length %}

{{ program.short_description }}

            {% endif %}
            {% if program.type == "seminar" %}{% endif %}
            {% if program.program_referents|length %}

                    {% set i = 1 %}
                    {% for referent in program.program_referents %}
                         {{ referent.referent_name }} {% if i != program.program_referents|length %}, {% endif %}
                        {% set i = i+1 %}
                    {% endfor %}

            {% endif %}

    {% endif %}
{% endfor %}


texts:
I'm trying to pass variants to the cart page. They variant field I want to pass is 'varHeight'. I'm using:

<form method="POST">
  <input type="hidden" name="action" value="commerce/cart/update-cart">
   {{ redirectInput('shop/cart') }}
   {{ csrfInput() }}
  {% for item in cart.lineItems %}
   ...
  {{ item.description }}
  {% for lineItem in cart.lineItems %}
   {{ lineItem.purchasable.varHeight }}
  {% endfor %}
    ...
  {% endfor %}

This works but puts the 'varHeight' value on every product in the cart instead of just the product it relates to. I'm sure it's simple but need some input on how to do this.


texts: Export Array of entries in modifyEntryTableAttributes

texts:
I am trying to return an array of selected entries in the list view, but so far I can only get first() and last() to export the names, since it's only grabbing one entry. I would like to get a comma separated list of entries tied the that specific entry.

I have tried using find() and find()->title but it gives me an error.

Here's what I have right now.

    public function getEntryTableAttributeHtml(EntryModel $entry, $attribute){
     if ($attribute == 'sponsorEntries'){
      return '<span>'.$entry->sponsorEntries->first().'</span>';
     }
    }

and then I call it:

        // Artists
     public function modifyEntryTableAttributes(&$attributes, $source){
      if ($source == 'section:9'){
        $attributes['sponsorEntries'] = Craft::t('Sponsor');
      }
     }

but I would like to get return all the entries, not just the first() one like the screenshot below illustrates.


texts: net::ERR_CONTENT_LENGTH_MISMATCH for CP after enabling compression

texts:
Also: https://plus.google.com/111272585078935192473/posts/5qNuffv3SKp which seems to be a similar problem.

I’m with a hoster where compression for PHP scripts must be enabled in php.ini adding zlib.output_compression = On to it.

After restarting the front end gets compressed as exprected, but the CP breaks, throwing net::ERR_CONTENT_LENGTH_MISMATCH for all resources (css, js etc.) which causes them not to be loaded. I have spoken with the hoster but they are unsure about this.

What is to do?
How can i get compression for my website without breaking the Control Panel?

Is there something i can do on my end?


texts: Plugin template's are not available from console commands

texts:
The if statement on Line 859 of TemplatesService.php prevent the template service from loading templates from a plugin.

Is there a specific reason for this, or is it simply a case that hasn't been needed for the command line interface yet?

I would like to use the template service to render various things like report emails. Is there another way I can do this from the CLI at the moment?


texts:
Suddenly getting errors when trying to save entries.
Have recently upgraded to latest version of Craft.

When I try up update a Single Entry I get the error:

Fatal error: Call to a member function getAttributes() on a non-object in /path-to-site/craft/app/controllers/EntriesController.php on line 484

When a try to save a Channel in IE11 it pops up - Do you want to open or save - 210-a-new-news-articlef93bf125.json(1.09KB) from domainname.com

What is causing this problem?


texts: Can a plugin force download an asset from third-party source like Amazon S3?

texts:
I have created a plugin that takes a form post, retrieves an asset id and am trying to have the browser start the download process. Is this possible if using a third party source like AmazonS3?  If so what may be wrong with this plugin controller method?

public function actionDownloadAsset()
{
    $this->requirePostRequest();
    $id = craft()->request->getRequiredPost("id");

    $attributes = array('id' => $id);
    $element = craft()->elements->getCriteria(ElementType::Asset)->limit(1)->find($attributes);

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($element->filename));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . $element->filesize);
    readfile($element->url);
}

Everytime I try the plugin from front end I get a page not found.  I have made sure the from is posting to the controller method.


texts: How to order categories in key/value for loop?

texts:
This is what I'm trying to accomplish:

All categories displayed on one page, with entries returned from each.
Only six entries shown in each category.
Categories need to be in a specific order.

I've got the first two points working, but can't figure out how to change the order of the categories. Am I going about this the wrong way?

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

{% for category, catEntries in entries | group('categoryField.first().title') %}

    {% for entry in catEntries|slice(0,6) %}

    {% endfor %}

{% endfor %}


texts: Login redirects to home page after 2.2 update

texts:
Since updating to Craft 2.2, my front-end login form now redirects to the home page.

The intended behaviour is to just reload the page that the visitor was on when they logged in.

In Craft 2.1 I achieved this by omitting the hidden redirect field. Any idea how to prevent members from being kicked to the home page now?

Thanks!