texts:
I am trying to create a Sub Task with Craft 2 that uses a task class. I have created some generic code to explain my setup:

Parent Task Class:

<?php

namespace Craft;

class Downloadxml_ParentTask extends BaseTask{
    //typical defineSettings(), getDescription(), etc

    public function runStep(){
        craft()->downloadxml_fooCalc->getFooCalc();
        return true;
     }
}

Sub Task Class

<?php

namespace Craft;

class Downloadxml_ChildTask extends Downloadxml_ParentTask{

    //No defineSettings(), getDescription(), etc
    //since we inherit from parent class

    public function runStep(){
        craft()->downloadxml_barCalc->getBarCalc();
        return true;
    }

}

Related Main Task runner:

<?php

namespace Craft;

class Downloadxml_GetAllXmlTask extends BaseTask{
//typical defineSettings(), getDescription(), etc
    public function runStep(){
    $settings = array(
        'foo' => 'yub',
        'bar' => 'nub',
    );
    $message = 'Preparing Bar for Calc';
    return $this->runSubTask('Downloadxml_Child' $message, $settings);
    }
}

Calling the task to run from Console Command:

<?php
namespace Craft;

class DownloadxmlCommand extends BaseCommand
{

    public function actionGenerateXMLForDownload()
    {
        craft()->downloadxml_taskCreateService->createDownloadTask();
        craft()->downloadxml_taskCreateService->runAllTasks();
    }
}

The plugin service the Command is calling:

<?php
namespace Craft;

class Downloadxml_TaskCreateService extends BaseApplicationComponent
{
    public function createDownloadTask()
    {
        $message = "Starting XML Download";
        $settings = array();
        craft()->tasks->createTask('Downloadxml_GetAllXml', $message, $settings);
    }
    public function runAllTasks() {

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

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

When I run the Downloadxml_GetAllXmlTask task, I get an error of:

Fatal error: Class 'Craft\Downloadxml_ParentTask' not found in <location of Main Task Runner>

The reason I am doing this is to try and keep my codebase DRY as to not have the same code for the settings for each task class. I have several classes like this, and they are failing the same way. Looking through core, it doesn't immediately appear clear to me as to why this isn't inheriting properly and working as expected. Currently running Craft 2.6.2967.


texts:
It seems that suddenly my image transforms are breaking gif animations. Weirdly, things were working fine for a couple of weeks and only recently I've been unable to upload new animated gifs. Here's an example of what I'm talking about:

https://www.dropbox.com/s/8k2mx3lysjczi1g/Screenshot%202015-11-20%2014.38.11.png?dl=0

You can see that when the gif is transformed, the frames are overlapping and resized differently from frame to frame. I'm not sure what caused this (perhaps a craft update?), but after hours of research I'm wondering if imagick needs a +repage when it reconstructs the animation after the transform... this problem seems related to canvas size... maybe? But I can't find where Craft is sending the command to ImageMagick, so can't experiment w/ the animation settings.

Another weird quirk of this bug is if I have 'generateTransformsBeforePageLoad' => true, set in my general config file, the page fails to load beyond the gif asset that's causing problems w/ the transform.

Anyone know what's going on here? I'm at a total loss...


texts: Variable "entry" does not exist in template at Structure Section

texts:
So, the subject.
I am currently working with customer of craftcms v2.
I am setting up Structure Section where I want to add Entry Type for index listing of items and add some items in list.

So, here is my setup:

Section: https://imgur.com/a/afXBU4M
Section EntryType: https://imgur.com/a/ugkEkGh
Field Settings tab: https://imgur.com/a/efAe0Kp
Field Layout tab: https://imgur.com/a/4FuZcAZ
Entry Example: https://imgur.com/a/KIxOdbO

I have 3 Entries added.
I made this setup exactly the same as was for same page type (Structure Section too). But page I did throws error as in subject title.

I've googled and found that the key for 'entry' object in template using is to check this option in Section settings:

'Entries in this section have their own URLs'

I found that in this article: https://straightupcraft.com/articles/the-craft-entry-variable

So, what may be the problem? This option is checked. Also exactly the same page (called Features) works well! It's kind of magic I think.

Simple code in template raises the error: https://pastebin.com/fjqeb1LT
I am using template in 'app/craft/templates/reviews/index.twig' folder.


texts: How do I use a Twig template to generate Email content from inside a plugin I'm making?

texts:
I'm trying to do a nicely formatted email from a plugin I'm making. The standard way I've been doing simple emails is all entirely in the code, somewhat like this:

$notificationEmail = new EmailModel();
$notificationEmail -> toEmail  = $userEmail;
$notificationEmail -> subject  = "Subject here";
$notificationEmail -> body     = "Thanks $userName, you’re now registered on our website.";
$notificationEmail -> htmlBody = " ... MASSIVE COMPLICATED STUFF THATS FAR BETTER SUITED TO TWIG ... "
craft()->email->sendEmail($notificationEmail);

I've now got an email that is far better suited to being generated via a Twig template because I'm going to have to loop through relational fields and all sorts. I have no idea how and I don't seem to know what to Google to get what I'm after... Anyone got pointers to this sort of thing?


texts:
When I include specific Twig template component multiple times, how can I give it a unique ID (or class)?

Components are not inside for loop, so I cannot use loop.index. I also don't wont to pass unique variable myself when I include it. And using random Twig function doesn't ensure that the result is unique.

Let's also assume that each component doesn't have unique Craft element assigned to it, like entry - in such case, I could just use this entry ID.


texts: I'm trying to create parent/child Single sections without using Structures.  So in other words, create a Single section and assign it a parent Single section.  Is this possible?


texts: How do I set a variable in Twig if a value exists more than once in a loop?

texts:
How do I loop through entries and set a variable if there are any duplicates in the data I'm checking?

In my case, I need to check if there are more than one entry per year. The variable I'm setting will be used in a conditional later in the template.


texts: Use Craft.postActionRequest in frontend template

texts:
Until now I've always done backend plugin development but my next task is to create a homepage with craft. To make an Ajax request I used Craft.postActionRequest but if I try this in my frontend template I always receive the error Uncaught ReferenceError: Craft is not defined

I've tried to include {%- includejsresource "js/craft.js" first -%} but it does not work. Of course I could just create a normal request via Ajax/jQuery but I would like to do it with craft methods...

So my question: what do I have to do, to get access to craft.js library?
edit: Just like this https://craftcms.com/docs/plugins/controllers#posting-to-controller-actions-with-javaScript

Thank you very much


texts: Craft Commerce "state" dropdown field fails to populate with states for new customer addresses

texts:
I'm having an issue with addresses on Craft Commerce 3 (specifically the State field).
When a new customer adds an address, the State field defaults to a text field (not the expected Select field).
If you save the address and then go back, the State field turns back into the Select field (and defaults to Alabama). This is an issue because the form isn't actually collecting a valid State the first time through.
You can see reproduce this issue at https://renewable-lubricants.net/products/checkout/addresses
This issue is happening both on my modified templates as well as the latest stock Sample Templates, with no modifications.
The problem seems to be with this block of twig code below in "addresses/form.twig". Any idea what would make "options" fail the first time through?
State
                    {% set options = (model and states[model.countryId] is defined ? states[model.countryId] : []) %}
                    <select id="{{ modelName }}-stateId" data-modelname="{{ modelName }}" class="js-address-stateId w-full {% if options|length == 0 %}hidden{% endif %}" name="{{ modelName }}[stateValue]">
                        {% for key, option in options %}
                            {% set optionValue = (model ? model.stateId : '') %}
                            <option value="{{ key }}" {% if key == optionValue %}selected{% endif %}>{{ option }}</option>
                        {% endfor %}
                    </select>
                    <input type="text" data-modelname="{{ modelName }}" id="{{ modelName }}-stateName" class="js-address-stateName {% if options|length > 0 %}hidden{% endif %} w-full" {% if options|length == 0 %}name="{{ modelName }}[stateValue]"{% endif %} value="{{ model ? model.stateName : '' }}">
                    {% if model and model.getErrors('stateValue') %}
                        {{ model.getErrors('stateValue')|join }}
                    {% endif %}


texts: Get categories with the number of entries

texts:
I would like to retrieve the categories of a group, the name and their fields, but with each one the number of entries that have this category assigned.
It's like this question  but I'm not using twig templates it is a GraphQL query.
I tried this query but the _count is not working like I want to.
query MyQuery {
  categories(group: "sectors") {
    ... on sectors_Category {
      title
      sectorImage {
        url
      }
      _count(field: "sector")
    }
  }
}


texts: Image Transform to convert animated GIF to static?

texts:
I'd like to be able to convert an animated GIF to static for displaying in my mobile view (to reduce bandwidth etc)

currently it seems I can only really set the output to JPG for this (PNG seemed to break the image and if i set to GIF it stays animated)

does anyone have any suggestions for this please? is it possible to extend the Image Transforms?

I guess I'd need to create some kind of plugin? at least that way I could extend it to define a frame number to use etc within my twig template.

thanks,
J.


texts: what is the correct way to programmatically set checkboxes (MultiOptionsFieldData) in a migration? (solved)

texts:
I need to update existing entries after the creation of a checkbox fields, to apply the default value to everything that was created before the availability of the new field.
The code should run in a migration to be deployed along the changes in the project config.
What is the correct way to programmatically set checkboxes (craft\fields\data\MultiOptionsFieldData)?
I verified the migration updates the entry (the title for instance), but not the custom field:
$entries = \craft\elements\Entry::find()
  ->section('sectionProduct')
  ->all();

foreach($entries as $entry) {
  $options = $entry->distribution->getOptions();
  foreach($options as $opt) {
    $opt->selected = true;
  }
  $entry->distribution->setOptions($options);
  Craft::$app->getElements()->saveElement($entry);
}

After running the migration, the control panel never shows the checkboxes flagged (the checkbox field has two possible values).
TIA


texts: Is it possible to have secure (private) assets?

texts:
For a member only area I would like to secure (private) assets:

The files should not be accessible when not logged in
The file download URL should be randomly generated and should expire after some time OR the files can be placed above the web root

There is for example Link Vault for ExpressionEngine which is able to achieve that.


texts: Limiting entries object when using as json_encode

texts:
I'm building a JSON array of several thousand entries using the following entries query:
{% set services = craft.entries.section('services').asArray().all() %}
The problem is there some private info is visible within the JSON and can be viewed in the browser source (not to mention the result is HUGE.
let services = {{ services | json_encode | raw }};
Is there a parameter similar to ids() where I can specify only the title, url, and ID?
If not, what's the best Twig way to reduce this array to what I'm looking for?


texts:
I am creating a calendar for displaying films and their screening times.

I already have a quite convoluted mechanism of retrieving data from the "films" channel, where I have a supertable for "filmScreenings", which contain values for "theater" for name of the theater and "starts" which is a datetime for when the screening starts.

I am trying to create a multidimensional array for storing the films and screenings per theater. This is what I would like to accomplish:

screeningsForTheater  = {
  "Theater 1" : [
    { "film" : "Movie 1", "starts" : "09:00" },
    { "film" : "Movie 2", "starts" : "11:30" },
    { "film" : "Movie 3", "starts" : "13:30" }
  ],
  "Theater 2" : [
    { "film" : "Movie 4", "starts" : "09:30" },
    { "film" : "Movie 5", "starts" : "11:00" },
    { "film" : "Movie 6", "starts" : "13:00" },
    { "film" : "Movie 7", "starts" : "21:00" }
  ]
}

From here on I would be able to loop screenings displaying films and their screenings in the correct column:

Theater 1         Theater 2
Movie 1, 09:00    Movie 4, 09:30
Movie 2, 11:30    Movie 5, 11:30
Movie 3, 13:30    Movie 6, 13:00
                  Movie 7, 21:00

Here is the twig-code for trying to create this kind of array:

{% set screeningsForTheater = {} %}

{% for film in films %}
  {% for screening in film.screenings %}

  {% set starts = screening.starts %}
  {% set ends = "calc starts + length in minutes" %}

  {% set screeningsForTheater = screeningsForTheater | merge(
    {
      (screening.theater.label) : [
        { "film" : film.title, "url" : film.url, "starts" : starts, "ends" : ends, "length" : film.length }
      ]
    }
  ) %}

  {% endfor %}
{% endfor %}

What happens is that the values for keys "Theater 1" and "Theater 2" are being replaced as the loop progresses. In the end I have an array that looks like this:

screeningsForTheater = {
  "Theater 1" : [{ "film" : "Movie 3" ... }],
  "Theater 2" : [{ "film" : "Movie 7" ... }]
};

I cant quite understand how to correctly push screenings into screeningsForTheater[theater] - any help you could offer?

Running Craft 2.6 if it has anything to do with Twig syntax.


texts:
I have tried to configure email as an SMTP client for a Google Mail server. When I click test I get a generic "There was an error testing your email settings", but no further info in Craft log files. The error displays almost instantly, so it does not seem like a connection issue, e.g. password / username error.

Craft is latest version and site is hosted with Arcustech.


texts: How would I trigger updateElements for BaseElementIndex from a plugin's JavaScript?

texts:
If I wanted to update the Elements listing based on an action taken from a plugin, would it be possible to do this?

Setup:

We're on an Elements listing page.
We filter the results with a search query.
We then click an Element's name to move to its individual editing page

The Problem:

Currently in my tests with Google Chrome if I:

Filter a list by a search query (say lastName::T* on the Users listing page),
Click on one of the usernames
Hit "Back"

My search is not saved, i.e., I'm returned to a non-filtered list.

My workaround to this is to write a simple JS plugin that stores your search query - if populated - when you navigate away from the page. I then re-populate the search query when you re-enter the page but I have to tell Craft to execute it, IE to fire updateElements.

My current workaround for this is to fire a change event on the search box if the search query is stored and it's not an Ajax request. It works, it just feels kind of hacky.

So I'm wondering if there's a more native, less hacky solution.


texts:
Does {{ url('handle') }} output the right url for localized sites?

I have a fr/en site and both lang output the english paths, but shows the right content and language/strings on the page.

I'm a bit confused. How do you guys build your navigation?


texts: Adding entries to an array, one at a time

texts:
I'm trying to loop through some entries and if they fulfil a certain condition push them into another array of entries.

{% set todaysEvents = []
{# GET TODAY'S ONE-OFF EVENTS #}
{% set todaysOneOffEvents = craft.entries.section('events').eventDate('= '~today | date("Y-m-d")).find() %}

{# ADD TODAY'S ONE-OFF EVENTS TO TODAY'S EVENTS #}
{% set todaysEvents = todaysEvents|merge(todaysOneOffEvents) %}
{# WORKING BEAUTIFULLY #}

{# FOR MULTI-DAY EVENTS THE DATES ARE IN A MATRIX FIELD, SO WE CAN'T FILTER USING CRAFT.ENTRIES #}
{# INSTEAD, WE HAVE TO FILTER EVERY ENTRY IN EVENTS WHICH USE THE MULTI-DAY ENTRY TYPE #}
{% for event in craft.entries.section('events').type('eventWithMultipleDays').find() %}
    {# NOW FIND ONLY ENTRIES WITH A MATRIX BLOCK CONTAINING TODAY'S DATE #}
    {% for date in event.dates if date.multiDate == today | date("Y-m-d") %}
        {# CORRECTLY IDENTIFIES ENTRY AS HAVING TODAY'S DATE IN A MATRIX BLOCK #}
        {# SO NOW WE ADD IT TO TODAYSEVENTS ARRAY #}
        {% set todaysEvents = todaysEvents|merge(event) %}
        {# ERROR: THE MERGE FILTER ONLY WORKS WITH ARRAYS OR HASHES #}
    {% endfor %}
{% endfor %}

What go on? See the error in the last comment. How do I pass only these filtered entries into todaysEvents array?


texts: Image not showing up in Redactor text editor

texts:
When i try to add an image in a bit of text, it does not show up. I get the assets model and can choose an image, but the image itself seems broken in the text.

I also see this error in the craft.log:

2015/07/27 13:57:03 [error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in /Applications/AMPPS/www/jipfish/craft/app/controllers/TemplatesController.php:59
Stack trace:
#0 [internal function]: Craft\TemplatesController->actionRender('entries/over/as...', Array)
#1 /Applications/AMPPS/www/jipfish/craft/app/framework/web/actions/CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#2 /Applications/AMPPS/www/jipfish/craft/app/framework/web/actions/CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Object(ReflectionMethod), Array)
#3 /Applications/AMPPS/www/jipfish/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#4 /Applications/AMPPS/www/jipfish/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#5 /Applications/AMPPS/www/jipfish/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#6 /Applications/AMPPS/www/jipfish/craft/app/framework/web/CWebApplication.php(282): CController->run('render')
#7 /Applications/AMPPS/www/jipfish/craft/app/framework/web/CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#8 /Applications/AMPPS/www/jipfish/craft/app/etc/web/WebApp.php(279): CWebApplication->processRequest()
#9 /Applications/AMPPS/www/jipfish/craft/app/framework/base/CApplication.php(184): Craft\WebApp->processRequest()
#10 /Applications/AMPPS/www/jipfish/craft/app/index.php(62): CApplication->run()
#11 /Applications/AMPPS/www/jipfish/index.php(19): require_once('/Applications/A...')
#12 {main}
REQUEST_URI=/jipfish/admin/entries/over/assets/article/bolderkar_01.jpg
HTTP_REFERER=http://localhost/jipfish/admin/entries/over/5-about
---
2015/07/27 13:57:03 [error] [application]
******************************************************************************************************

Does anyobe know what is up?

Thanks, Bob


texts: How can I insert images into a Redactor rich text field in a front-end form?

texts:
I want to allow registered users to insert (i.e. upload) images into a Redactor rich text field in a front-end form.

I dowloaded the Image Manager plugin from Imperavi (https://imperavi.com/redactor/plugins/imagemanager/) and set up my Redactor config as follows:

{% includeJsResource "lib/redactor/redactor.js" %}
{% includeJsResource "lib/redactor/plugins/source.js" %}
{% includeJsResource "lib/redactor/plugins/fullscreen.js" %}
{% includeJsResource "lib/redactor/plugins/imagemanager.js" %}
{% includeCssResource "lib/redactor/redactor.css" %}

{% set redactorJS %}
    $('#{{ elId }}').redactor({
        buttons: ['format', 'bold', 'italic', 'deleted', 'lists', 'link', 'html', 'image'],
        formatting: ['p', 'blockquote', 'h2', 'h3'],
        plugins: ['source','fullscreen', 'imagemanager'],
        minHeight: 300,
        imageUpload: '/upload.php',
    });
{% endset %}
{% includeJs redactorJS %}

I can see the image button in the toolbar and the browse files modal when I click the image button. However, it doesn’t upload anything because imageUpload: '/upload.php', is obviously incorrect. What, if anything, can I replace upload.php with? If this isn’t possible, what else could I do to achieve this functionality? Thanks!

UPDATE:

I have the following code in craft/plugins/imagesuploaderscript/controllers/ImagesUploaderScriptController.php from CloudApp share link in comment below:

namespace Craft;

class ImagesUploaderScriptController extends BaseController
{

protected $valid_extensions = array('jpg', 'jpeg', 'png');
protected $assetSourceId = 1;
protected $assetFolderId = 1;

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

    $errors = array();
    $success = array();

    if (!$_FILES['file']['error'])
    {
        $filename = $_FILES['file']['name'];
        $file = $_FILES['file']['tmp_name'];
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        if (!in_array($extension, $this->valid_extensions))
        {
            $errors[] = "$filename has an invalid extension.";
        } else {
            $uploadDir = craft()->assetSources->getSourceById($this->assetSourceId)->settings['path'];

            if (move_uploaded_file($file, $uploadDir . $filename))
            {
                IOHelper::deleteFile($file);

                $file = $uploadDir . $filename;

                $fileModel = new AssetFileModel();
                $fileModel->sourceId = $this->assetSourceId;
                $fileModel->folderId = $this->assetFolderId;
                $fileModel->filename = IOHelper::getFileName($filename);
                $fileModel->kind = IOHelper::getFileKind(IOHelper::getExtension($filename));
                $fileModel->size = filesize($file);
                $fileModel->dateModified = IOHelper::getLastTimeModified($file);

                craft()->assets->storeFile($fileModel);

                // print_r($fileModel);

                // displaying file
                $image = array(
                    'url' => 'images/'.$filename,
                    'id' => 1
                );
                $this->returnJSON($image);
                exit;
            }
            else
            {
                $errors[] = "$filename was unable to be saved.";
            }
        }
    }

    $this->returnJSON(compact('errors'));
    exit;
}

}

How do I get my form to talk to it? Also, what else do I need to do to get it to work?


texts: Removing "action" from a module's route. Is it possible?

texts:
I have a module with a route that looks like this:

http://localhost/actions/module/controller/action

Is it possible to set up a custom route within my module so I can send people to:

http://localhost/module/controller/action

I'm new to Craft 3, but so far loving it.

Cheers!


texts:
I'm adding content to a site that has been set up in Craft. However, it's been set up so that in one section, any link created has the label "How this works". It's a bit unwieldy as it means I can't use the actual information I want to send people to as the link for example:
"Spend less money" as the link rather than body text that says "Spend less money" with a link underneath that says "How this works".

Is there any way I can change this behaviour without getting the site designer to change it in template files?


texts: How can I validate that I am passing an Asset into my custom twig filter?

texts:
I'm creating a custom twig filter in Craft 3 and am struggling with a really simple thing.

{{ entry.backgroundImage.one() | filter }}

In my filter, I would like to validate that I am being passed an asset.

if (!$asset instanceof Asset)
{
    return false;
}

What should I be checking the object against? Asset or something different?


texts: $request->send fails on one server but not the other

texts:
Not sure whether this is a Craft thing or a Yii thing, but I have this exact same code running on two servers that I've freshly updated Apache, PHP, etc. On the one server it runs fine but on the other the page never loads and I have to do a server reboot to clear it.

Can anyone think of any reason this might happen?

$url = 'https://domain.com/jsonfeed'
try {
    $client = new \Guzzle\Http\Client();
    $request = $client->get($url);

    // BREAK NOW AND ALL IS FINE

    $response = $request->send();

    // BREAK NOW AND PAGE NEVER LOADS SO IT MUST BE
    // $request->send(); THAT IS FAILING

    if (!$response->isSuccessful()) {
        return;
    }

    $items = $response->json();

    reset($items);
    $key = key($items);
    return $items[$key][$id];

} catch(\Exception $e) {
    return;
}


texts: Smart Map - Sorting for closest location in PHP

texts:
I want to sort entries with a Smart Map address field for closest location. I know how it should be done in a template:

{% set entries = craft.entries.myAddress(params).order('distance').find() %}

Only, I would like to do so in my business logic and not in my template. I tried something like this.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'houses';
$criteria->myAddress->target = '90210';
$criteria->order = 'myAddress.distance';

However, this does not work.

Is this possible? I tried related options but can't seem to get anything to work. Can I also do this with the Element API plugin to return the results as JSON?


texts:
I've hacked this together to create an event archive listing, and although it works, I'm wondering if it's 'correct' or could be done more succinctly?

{% set pastEvents = craft.entries.section('eventsEntry').orderBy('eventDate') %}
   {% for date, entries in pastEvents | group("pastEvents.eventDate|date('Y')") %}

{{ date }}

                {% for event in pastEvents.all() if event.eventDate <= now %}

                    {{ event.eventDate|date('d/m/y') }}
                    {{ event.title }}

                {% endfor %}

   {% endfor %}


texts: So I've been following the docs on how to create a search form in Craft and it works fine. But instead of having a results.twig page I would like to have just one index page and get all the results with AJAX. Is there a simple way to accomplish this in Craft? And if so, does anyone have an example?


texts: How can I determine if the row being returned from a table field in a for loop is the last row?


texts: Sprout E-mail: 400: HTML Content URL Required - Campaign Monitor

texts:
I'm getting the following error when trying to send a campaign with Campaign Monitor through the Sprout E-mail plugin:

400: HTML Content URL Required

I used the example templates provided by Sprout. The Api connects well (I get the list my subscription list from Campaign Monitor in Sprout). I make a new campaign and I can preview the mail in both html and text. The preview looks fine (just some hardcoded stuff). But when I try to send the mail I keep on bumping on that issue. I figured it had to do something with the template url, so I played around with the setting in the campaign:

Entries of this type have their own URLs

I tried pointing it to the template (sproutemail/newsletter) or the name of the entry (sproutemail/{slug}), both without any luck.


texts:
Done this a couple of times before so not sure what's going on, but I'm trying to hook up S3. I have the bucket/group/policy/user all setup. But when I enter Access key ID and Secret access key in Craft and refresh, no buckets show up. No errors, just no bucket. My policy looks like this:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:ListAllMyBuckets"
        ],
        "Resource": "arn:aws:s3:::"
    },
    {
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname/*"
        ]
    },
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetBucketLocation",
            "s3:ListBucket"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname"
        ]
    }
]

}

If it matters, my bucket resides in London. Any help much appreciated.


texts:
I'm testing my email and I'm seeing the following error in the web logs:

  "Error sending email: Process could not be started [The system cannot find the path specified. craft cms"

Does anyone know what that means?

In my local environment I am not seeing what exactly causes this error.
I've tried following this article on Craft but it seems like this is not relevant to the error I am receiving?

https://craftcms.com/guides/troubleshooting-email-errors

Also, I don't see the file structure they mention on this article, I found the error log on storage/logs/web.txt.

I've tried also changing my email to SMTP with Outlook credentials to no avail.

The images show the directory structure I'm seeing: https://i.stack.imgur.com/yvDex.png


texts: How can you use the jQuery pjax plugin with Craft?

texts:
There is a jQuery plugin called pjax (https://github.com/defunkt/jquery-pjax/) for downloading page content via ajax.

How can you integrate pjax in Craft for downloading entries via ajax? Or are there other ways to download entries via ajax?


texts:
I've had this issue for a while now and have never been able to get it solved - even after chatting in Slack about it with some people. Basically whenever I go to update an entry, Craft hangs and locks up Apache. It times out in about 5 minutes or if I manually restart Apache, things go back to normal. The entry is updated after the server restarts so it appears that the database write is successful.

It's becoming a huge problem as I'm finishing up a site for a client and they're needing to put content in. I'm running this on a Google VM and have tried installing it on a fresh server with no luck. I'm running Ubuntu 14.0.3. I'm running other Craft sites on Google and have no issues.

I tried a few steps a while back (I can't remember what exactly), I believe I increased a couple parameters in PHP.ini but I honestly can't remember. I used to be getting the zend_mm_heap_corrupted error but that's gone away now from my Apache error log.

Any help is appreciated. It's getting sort of urgent at this point since my deadline is approaching and entries need to be worked on.

My Apache version is 2.4.7 if that makes any difference.


texts: Showing and playing video's in Twig templates

texts:
I want to be able to upload and play videos on my Craft CMS website.
I created a volume and field to hold these videos.
So far so good, but whenever I want to output the video in a video tag I'm not sure how to get the URL of the video.
My code:
{% set video = component.video %}
{% if video %}
   <video width="800" height="500" controls>
      <source src="## VIDEO URL ##" type="video/mp4">
   </video>
{% endif %}


texts: How do I pull related entries and assets?

texts:
I'm having a bit of a hard time wrapping my head around exactly how to work with both Relationships and Assets. Here is my current problem that I seem to be stumped on, i'm sure once I get this going I'll be good to go and fully understand how to work with both:

I need to determine if an entry is selected to be related to an entry single (the homepage) via the entry field 'featuredEvent', then
I need to determine if the 'image' block is being used in the matrix 'articleBody' in that related entry, then
I need to pull the first instance of the 'image' block (not necessarily the first block altogether), then
I need to determine if there is more than one 'asset/image' in the 'image' field in the 'image' block in the related entry, then
If there is only one image I need to output some code, and then output the image, as well as the other parameters 'size' & 'alignment', which are both drop downs, 'size' selects the pre-determined 'imageTransform' where as 'alignment' just applies a class or
If there are multiple images i need to output some code, and then output the images, as well as the other parameters 'size' & 'alignment'.

Could anybody write that code out for me and explain what is happening in each line to help me get a better grasp? Thank you so much in advance.


texts: How to prevent "Failed" errors in job scheduler in Craft CMS 3?

texts:
I have an instance of BaseJob that I occasionally queue up that involves reading an XML file from another server. However, requests to that server are rate-limited, and so occasionally it will fail with an error.

I don't mind this in terms of the logic of how it works - I just request another version a while later. However, every time it fails, it adds a message into the "Failed" tab in the CMS.

Is there any way to prevent/override this? I have tried suppressing errors in the job, I've tried wrapping the whole thing within a try/catch block, but nothing seems to work - whenever it fails, it is logged in the CMS.

Thanks.


texts: How to upload asset element on its own, not into an asset field (frontend form)

texts:
I have read this resource about uploading a file to an asset field on an entry, but I believe I need to create the asset on its own because the asset has 2 custom fields associated with it that I want to define upon its creation. Is there not something like an 'assets/save-asset' action I can use to save an asset element without having to attach it to an entry?
Update: With Marion's help I'm a little closer. Side note: apparently 'assets/save-asset' is now depreciated in favor of 'assets/upload' so I'm using that. Here is my form:
              <form method='post' accept-charset='UTF-8' enctype='multipart/form-data'>
                {{ csrfInput() }}
                {{ actionInput('assets/upload') }}
                {{ hiddenInput('folderId', 7) }}
                {{ hiddenInput('title', 'cool image')}}
                <input name='file' type='file'>
                <input type='submit' value='submit'>
              </form>

But I am now getting a 400 Bad Request error with the message No file was uploaded. What am I doing wrong to not have my file attach correctly?


texts:
Wondered what the best approach would be to get the url for a given entry page using only a slug for reference? I imagined it being something like this:

 public function getPageURL($slug) {
    $page = craft()->elements->slug($slug);
    @return getURL($page);
  }

Usage example:

Staff


texts:
I'm moving a site from EE to Craft. All is well but the redirects from the old URLs to the new do not work.

I have tried:

SproutSEO Redirects
(https://sprout.barrelstrengthdesign.com/craft-plugins/seo/docs/getting-started/redirects) - Results in a Craft 404
Retour (https://github.com/nystudio107/retour) - Results in a Craft
404
Reroute (https://github.com/davist11/craft-reroute) - Results in a
Craft 404
.htaccess redirect - Results in Craft 404

The only thing I can think of is that Craft is somehow getting ahead of these solutions and running with the 404.

Any assistance would be appreciated.


texts:
I'm looking for the best way to deal with long lists of items. In this case a subsite is a council library area which must publish a list of new books each month. In a perfect world I would suck this from the library catalogue directly, but that isn't going to happen just yet, so I need a medium term workaround. I also have other similar data lists to manage so need to have some solutions up my sleeve.

So I would have 50-100 list items manually added each month. Each item would consist of Book Title, Author, Some sort of ID number used in a link, and keys to the month (not necessarily published month) and type (e.g. non-fiction, fiction etc).

I can think of half a dozen ways to do this, but of course am seeking one that is efficient both from a data entry point of view, but also from a system and performance point of view. Ways of doing it might include (just from a brainstorming point of view):

Use a channel with each book being an entry (with fields for month and type)
Use a channel with each month being an entry and a matrix field for each book
Upload the monthly book list as an asset (XML or JSON) and display from there

The last one is the most appealing if I can work out how to get a non technical website content manager creating files in the right format (Excel should work for this). It also seems a short step from there to using a library catalogue system generated file.

I'm not quite up to writing my own plugin just yet, but perhaps it's time for me to learn.


texts:
What is the best way to do this?
I also have a number of plugins that all need updating from the same time period.
I don't think any of the breaking changes affect anything I've done, but I wonder/expect that some plugins may need to be updated to work with the new craft versions.
The PHP requirements changed twice during the various updates.
I'm currently running PHP 7.2 but I know that Craft 3.6 needs 7.2.5 or later.
I can make 7.4 available but do I change it before I start the updates or after.
I have already tried doing this once from the control panel, and Craft seemed to update and the control panel was available but all the plugins were disabled and when I tried to update any plugin it failed and I got an Internal server error page. The composer.json file hadn't been updated to show the new version of craft, I tried editing it and changing the PHP version in the config.platform but still couldn't update any plugin.
I can ssh into the server but my command line knowledge is very limited and potentially dangerous.
My server is already running composer 2.0.6


texts: Getting UTC DateTime from Model attributes

texts:
The AttributeType::DateTime in model attributes saves as UTC which is great, but upon getting that attribute I receive a Craft\DateTime object with my server timezone set for it, and thus the time gets modified accordingly.

Is there any way I could force the model to return a Craft\DateTime object with the UTC timezone?

When I created a getter method public function getDate() it doesn't get called when using object.date inside a Twig template. I have to specifically call object.getDate() instead, which isn't really an option for me.

This is how my model defines attributes:

protected function defineAttributes()
{
    return array(
        'date'  => AttributeType::DateTime,
    )
}

Maybe there are some additional rules I can set for it, that I am not aware of? I couldn't find anything in Yii's documentation.


texts: Get username and email on setpassword form

texts:
I am looking to make use of the users first name as well as their email address on setpassword page.

I am not seeing any way to grab those fields unless I am missing something?


texts: Can you set async defer when using {% includeJsFile %}?

texts:
Is there a way to set async defer on a <script> tag with the built in:

{% includeJsFile %}

It's for Google Maps e.g.:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>

I'd still like to be able to output this at the bottom of the layout from within another template. Is this possible?


texts: setPasswordPath doesn't seem to be working

texts:
This looks like a bug to me:
If I set the setPasswordPath in the general config file, then the template that I've set up is not showing up, it loads the default one when I try to load:

http://site.local/admin/actions/users/setpassword?code=


texts:
I've got a new channel for Authors where there are 3 fields:

firstName
middleName
lastName

and I'm using these fields to generate the Title of the channel entry. However I would like to add a conditional around middleName so that it isn't used if empty and I can avoid have double space between first and last name.

How can I do this?


texts: CraftCMS cookieValidationKey must be configured with a secret key inside Docker Container

texts:
I am using CraftCMS, and I am getting this error:
Invalid Configuration – yii\base\InvalidConfigException
craft\web\Request::cookieValidationKey must be configured with a secret key.

The longer error is:
1. in /code/vendor/yiisoft/yii2/web/Request.phpat line 1678
1669167016711672167316741675167616771678167916801681168216831684168516861687     * Converts `$_COOKIE` into an array of [[Cookie]].
     * @return array the cookies obtained from request
     * @throws InvalidConfigException if [[cookieValidationKey]] is not set when [[enableCookieValidation]] is true
     */
    protected function loadCookies()
    {
        $cookies = [];
        if ($this->enableCookieValidation) {
            if ($this->cookieValidationKey == '') {
                throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
            }
            foreach ($_COOKIE as $name => $value) {
                if (!is_string($value)) {
                    continue;
                }
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
                if ($data === false) {
                    continue;
                }

My .env file is such:
# The environment Craft is currently running in ("dev", "staging", "production", etc.)
ENVIRONMENT="dev"

# The application ID used to to uniquely store session and cache data, mutex locks, and more
APP_ID="CraftCMS"

# The secure key Craft will use for hashing and encrypting data
SECURITY_KEY="xxxxxxxx"

# The database driver that will be used ("mysql" or "pgsql")
DB_DRIVER="mysql"

# The database server name or IP address
DB_SERVER="mariadb"

# The port to connect to the database with
DB_PORT="3306"

# The name of the database to select
DB_DATABASE="dev_craftcms"

# The database username to connect with
DB_USER="root"

# The database password to connect with
DB_PASSWORD="abc123"

# The database schema that will be used (PostgreSQL only)
DB_SCHEMA=""

# The prefix that should be added to generated table names (only necessary if multiple things are sharing the same database)
DB_TABLE_PREFIX=""

DEFAULT_SITE_URL="http://www.amira.local/"

Am I missing anything?


texts: Simple Search form with a few drop-down choices

texts:
Looked at countless examples here but all seem to be more than I need.

I need the form to have three drop-downs

Make
-Ford
-Chevy

Color
-Red
-Blue

Transmission
-Auto
-Shift

And the search results field would look at the section called 'cars' and return any car with the exact match. One additional point is that 'Transmission' is a category.

Thanks.


texts: Categories in a RelatedTo - How do I not list the parent if there is a child?

texts:
I am going to try this again...

I have a page for a category (country) with all the entries that match that country.

I have buttons that allow you to filter the entries using categories from a second category group ('market').

All, I want to do is list the markets to make the filter buttons.
BUT, I don't want to list the parent if their is a child.  And, there is not always a child.

This is how I have things setup.

{% set entries = craft.entries.relatedTo(category).find() %}
{% set markets = craft.categories.group('markets').relatedTo(entries).find() %}

But, this prints both the parent and child of a market. I don't want to print the parent if there is a child.

Addling level(x) does not work because then it leaves out those markets that might be x+1 or x-1.

And adding last() did not work.

This has to be possible.  It's killing me.


texts: How to remove empty tags in rich text? (Redactor or Twig)

texts:
What is the preferred method to remove an empty tag from the content of a rich text element?

Example result:

  Lorem ipsum

When editing text in the WYSIWYG editor (Redactor) the result can contain empty anchor tags. This is a problem when navigating the page with the tab key, for instance, because the user can not see the focus anymore.

How can I automatically remove those artefacts?


texts: How are people adding public comments to their Craft sites?

texts:
It's not been asked as a broad question here yet, but we've all wondered: how does one go adding comments to a Craft site, such as those you'd find on a blog?

I've either used or been aware of...

Tacking Disqus (JavaScript) comments onto pages.
Integrating Google+ comments.
Using a dedicated Craft Section for comments and relating each to a post, collecting submissions with Guest Entries.

Are there others out there? Would an expert comment engineer care to answer authoritatively?


texts: How can my plugin render a generic Matrix block in the Control Panel?

texts:
Here's a sample of a matrix block:

I would like to have my own fields inside the block and retain the basic functionalities like Collapse, Disable, etc. Basically, just use the Matrix block UI without using the Matrix field.

Is this possible?


texts: How do I create a page with a dynamic id?

texts: Here’s an example: I have a job listing at www.example.com/designer and the user hits "apply" on that page. The user is then taken to a form. How can I know that the user came from www.example.com/designer and not www.example.com/developer?


texts: Migration of Craft CMS from one host to another

texts:
I'm a newbie in Craft CMS. I need to make changes in an existing craft website which is with one hosting platform.
The site was previously managed by another developer. I need to migrate to a new hosting platform and i would like to know what all credentials i would need to obtain to perform this task and how i can migrate it?


texts: Get entries using Multi-Select Field as Criteria

texts:
When querying for entries, I'm stuck on how to query for "selected" fields.

The query I'm using:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section('athletes');
$criteria->sport = 'tennis';

$players = $criteria->find();

This works just fine, but I also need to query further using a field that is a multi-select field. I'd like to do something like:

$criteria->tournaments->wimbledon = "selected";

This obviously doesn't work though. Does anyone know if this is possible and/or how to accomplish this?


texts: How to check for a value OR NULL on custom enddate field using yii syntax when calling entries?

texts:
I have a section of 'deals/coupons' with custom startDate and endDate.  These are needed so the client can load up a bunch of deals but only have them render to the page when a particular deal is 'active'.

The below syntax works to not show any deal before it's startdate has passed:

{% paginate craft.entries({
   section : 'dealDirectory',
   limit   : pageSize,
   startDate : '<=' ~ now
}) as pageInfo, dealEntries %}

And using the below code I can prevent deals from showing after their enddate but only if enddate has data:

{% paginate craft.entries({
   section : 'dealDirectory',
   limit   : pageSize,
   startDate : '<=' ~ now
   endDate : '>=' ~ now
}) as pageInfo, dealEntries %}

If enddate does not have a value it eliminates those entries from showing.  I need to find a way to check if enddate is greater than now OR is null so that it will continue to show deals that do not have an enddate. Such as:

{% paginate craft.entries({
   section : 'dealDirectory',
   limit   : pageSize,
   startDate : '<=' ~ now
   endDate   : '>= ' ~ now ~ 'or is null'  // but this syntax incorrect
}) as pageInfo, dealEntries %}

I'm having a hard time finding a reference for this type of markup.


texts: Live Preview is jumping to top of page on edit

texts: When using the live preview pane, each time I type something or move a block, the preview pane jumps to the top. When editing anywhere but the top, this is not ideal. Is this a bug? I also checked it on a previous site that I had built in Craft and I'm getting the same behavior.


texts: Is it possible to create a page that shows only a specific post type with its own url?

texts:
I have a website with a shop section with the following URL structure: homepage/shop/category/the-product.

I would like to add a page after the category to filter between post types within that category, and I want to be able to access it through the entry type slug in the URL.

I also need to change the template to match the Entry Type.

If this is possible, how do I do it?

Thanks ahead!


texts:
I am trying to use the one-click update feature and continually am getting a 500 error when attempting retrieve available updates on staging server. All my permissions work correctly as my craft install works all over except when updating.

the URL that gives this error is:

http://staging.link.com/index.php?p=admin/actions/update/getAvailableUpdates

Stacktrace:

PHP Error [500]

chmod(): Operation not permitted (/var/www/staging/craft/app/helpers/IOHelper.php:1023)

#0 /var/www/staging/craft/app/etc/errors/ErrorHandler.php(184): Craft\ErrorHandler->handleError()
#1 /var/www/staging/craft/app/framework/base/CErrorHandler.php(133): Craft\ErrorHandler->handleError()
#2 /var/www/staging/craft/app/framework/base/CApplication.php(824): Craft\ErrorHandler->handle()
#3 /var/www/staging/craft/app/etc/web/WebApp.php(681): Craft\WebApp->handleError()
#4 unknown(0): Craft\WebApp->handleError()
#5 /var/www/staging/craft/app/helpers/IOHelper.php(1023): chmod()
#6 /var/www/staging/craft/app/etc/cache/FileCache.php(138): changePermissions()
#7 /var/www/staging/craft/app/framework/caching/CCache.php(185): Craft\FileCache->setValue()
#8 /var/www/staging/craft/app/etc/cache/FileCache.php(64): Craft\FileCache->set()
#9 /var/www/staging/craft/app/services/CacheService.php(130): Craft\FileCache->set()
#10 /var/www/staging/craft/app/etc/et/Et.php(247): Craft\CacheService->set()
#11 /var/www/staging/craft/app/services/EtService.php(54): Craft\Et->phoneHome()
#12 /var/www/staging/craft/app/services/UpdatesService.php(277): Craft\EtService->checkForUpdates()
#13 /var/www/staging/craft/app/services/UpdatesService.php(170): Craft\UpdatesService->check()
#14 /var/www/staging/craft/app/controllers/UpdateController.php(57): Craft\UpdatesService->getUpdates()
#15 /var/www/staging/craft/app/framework/web/actions/CInlineAction.php(49): Craft\UpdateController->actionGetAvailableUpdates()
#16 /var/www/staging/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams()
#17 /var/www/staging/craft/app/framework/web/CController.php(286): Craft\UpdateController->runAction()
#18 /var/www/staging/craft/app/framework/web/CController.php(265): Craft\UpdateController->runActionWithFilters()
#19 /var/www/staging/craft/app/framework/web/CWebApplication.php(282): Craft\UpdateController->run()
#20 /var/www/staging/craft/app/etc/web/WebApp.php(811): Craft\WebApp->runController()
#21 /var/www/staging/craft/app/etc/web/WebApp.php(281): Craft\WebApp->_processActionRequest()
#22 /var/www/staging/craft/app/framework/base/CApplication.php(184): Craft\WebApp->processRequest()
#23 /var/www/staging/craft/app/index.php(62): Craft\WebApp->run()
#24 /var/www/staging/html/index.php(19): require_once()


texts:
I know this question has come up many times before, although after reading and trying dozens of answers, I am none the wiser.
I am currently rebuilding my website with Ubuntu 16.04, PHP7 and apache. And what worked flawlessly on my old site (Ubuntu 14) is now not, and I cannot hide the index.php within the URL without the site crashing. This of course breaks any links to finish the craft completion and therefore is not operational.
Here is my .htaccess file:

   <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

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

I have entered garbage within the .htaccess and am not receiving any change, therefore I presume it is an issue with this.
The .hta is within my web route of /var/www/public_html, which is indexed correctly withing the apache config.

I've edited apache config to  allow overriding:

<Directory />
  Options FollowSymLinks
  AllowOverride All
  Require all granted
</Directory>

I've also made sure that omitting script names is enabled:

'*' => array( // production by default
    'siteName' => '*****',
    'omitScriptNameInUrls' => true,
    'siteUrl' => 'http://' . $_SERVER['SERVER_NAME'] . '/',
    'timezone' => 'Europe/London',
    'allowAutoUpdates' => true,
    'cpTrigger' => 'mgmt',
    'rememberUsernameDuration' => false,
)

Sigh If anybody could suggest anything else, it would be very much appreciated!


texts: Craft 3 Module Working but Throwing Errors in web.log

texts:
I'm seeing a lot of "Invalid argument" errors in the web.log for a "Multiple Option Variant" module I have running. It seems to be working just fine on the site, but curious as to what the issue might be. Do I need to put in some "guards" in the code, and if so, what would that look like?

This is the error;

[error][yii\base\ErrorException:2] yii\base\ErrorException: Invalid argument supplied for foreach() in /httpd.www/craft/modules/multipleoptionvariantmodule/src/variables/MultipleOptionVariantModuleVariable.php:52
#0 /httpd.www/craft/vendor/craftcms/cms/src/web/ErrorHandler.php(76): yii\base\ErrorHandler->handleError(2, 'Invalid argumen...', '/httpd.www/...', 52)
#1 /httpd.www/craft/modules/multipleoptionvariantmodule/src/variables/MultipleOptionVariantModuleVariable.php(52): craft\web\ErrorHandler->handleError(2, 'Invalid argumen...', '/httpd.www/...', 52, Array)

The referenced file at looks like this—and it seems to be the foreach function that's the culprit;

namespace modules\multipleoptionvariantmodule\variables;

use modules\multipleoptionvariantmodule\MultipleOptionVariantModule;

use Craft;

class MultipleOptionVariantModuleVariable
{
     public function getUniqueVariantAttributeValues($fieldName, $variants, $onlyInStock=false) {
         $addedIds = array();
         $sizes = array();

         foreach($variants as $variant) {
             $outOfStock = (($variant->stock <= 0) && ($variant->hasUnlimitedStock == false));

             if (!$onlyInStock || ($onlyInStock && !$outOfStock)) {
                 if (isset($variant->{$fieldName}[0])) {
                     if (array_search($variant->{$fieldName}[0]->slug, $addedIds, true) === false) {
                         $sizes[] = $variant->{$fieldName}[0];
                         $addedIds[] = $variant->{$fieldName}[0]->slug;
                     }
                 }
             }
         }

         return $sizes;
    }
}

This is then how that is used in the template(s);

{% set variants = product.variants %}
{% set variantColors = craft.multipleOptionVariantModule.getUniqueVariantAttributeValues('variantColor', variants, false) %}
{% set variantTypes = craft.multipleOptionVariantModule.getUniqueVariantAttributeValues('variantType', variants, false) %}

I'd take any hints on how to convert that php functionality to pure twig too. :)
That would actually be ideal.


texts:
Good day!

I display the day of the week on the site {{ now|date("l") }}

How to change for example Monday to Mondays (on Mondays)?

Thanks in advance :)


texts: How to detect the model type of an item in an array of query results

texts:
When querying multiple model types (entries, Commerce products and Commerce variants) I want to be able to detect the model type of each item as I iterate over the results array.

Ideally to avoid this sort of error:

Craft\EntryModel and its behaviors do not have a method or closure named

There doesn't seem to be a clean way of doing this but I may be wrong!


texts: Show posts related to entry AND all posts not related to any entry

texts:
I'm struggling to get my head around relations. It seems overly complex for the simple thing I want to do.

I am using an entry field on my post to set relations by city. These entries are limited to a structure that has a list of cities. I am outputting a global variable that is the current location (city).

With the following code, I am able to get any posts from the current city.

{% paginate craft.entries.section("news").relatedTo(currentCityFilter).order("featured desc").limit(10) as pageInfo, pagePosts %}

{% for post in pagePosts %}

{{ post.title }}

Posted on {{ post.postDate.format("F d, Y") }}

        {{ post.body.getPage(1) }}

Continue reading

{% endfor %}

The problem is, I don't want to force the user to set every city when they wish to have a post display for every location.

What's the proper way to show any posts that don't have a city set and still filter posts that do have a city by the current city?

Similar question with no answer here: Get entries where relation matches or is empty


texts:
I'm running into a few issues trying to set up 301/302 redirects with Craft and nginx. The legacy site has /contact.php paths which I would like to direct to /info/ but when I visit mysite.com/contact.php it gives me the No input file specified. error.

I tried setting this up with Retour plugin, and inside of nginx files, but they both return No input file since there is no contact.php on my server.

Below is my nginx file for reference:

server {
    listen 80;
    listen 443 ssl http2;
    server_name mysite.com;
    root "/home/vagrant/mysite/public";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/mysite.error.log error;

    sendfile off;

    client_max_body_size 100m;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
    }

    location ~ /\.ht {
        deny all;
    }

    ssl_certificate     /etc/nginx/ssl/mysite.crt;
    ssl_certificate_key /etc/nginx/ssl/mysite.key;
}

I know Craft is doing some weird things here to avoid index.php, not sure how it affects my situation though. In addition to mapping /contact.php to /info/, I would also like to make /gallery.php?c=category to /?filter=category

Thanks for your help!


texts:
I would like to know if it is possible to protect some sections of the site with an htpasswd or not?  I know that I could protect it by using user groups in my template, but I'm looking at avoiding the cost simply because the site is very temporary (1 week) and not for external purposes.

So basically,

http://mysite.com/mysection1

http://mysite.com/mysection2

http://mysite.com/mysection3

Those 3 sections would be protected by a different password, but they would also be pages in my site.  Can I just create the real physical folder and create the same page with same url in Craft?  Is there a way to achieve this?

Thanks!


texts: Include entries to a entries section object, without 'merge'

texts:
So I have a structure with a few entries and a single. I want to list out the first level of the structure, plus the single. Then somewhere else, list out the second level.

I've tried the following:

{% set myPages = craft.entries.section('structureName')|merge(craft.entries.section('singleName')) %}

<nav>
{% nav entry in myPages.level(1) %}
  {{ entry.title }}
{% endnav %}
<nav>

<aside>
{% for entry in myPages.level(2) %}
  {{ entry.title }}
{% endfor %}
<aside>

Which returns this error:

  "Array to string conversion"

When I remove the .level(X) function it will return all the entries, on all levels; including the single.

For the purposes of making my problem more understandable, I've simplified my above example. I know I could just add the single entry directly into the <nav>. But I'm curious about ways to add to a entries section object without losing the ability to query levels.

So, in the same way I can exclude entries, is there a way to include an entry from a different section without relying on Twigs merge filter?


texts: Outputting structured product attributes in JSON-LD code with SEOMatic

texts:
My products have a lot of attributes that I would like to serve to Google AMP via JSON-LD. The attributes vary between product types.
How should I do this?
I see there is a file under nystudio107\craft-seomatic\src\seomatic-config\productmeta\JsonLdContainer.php, and I am guessing I should put that file in my own config and modify it a bit, but I am not sure how to approach this.
Edit: Then of course there is the question: What are you really trying to do?
I am under the impression that I can tell Google what the different attributes on my product are, and that Google can use this when generating rich previews of search results. I understand that Google has a list of Supported Structured Data, and from that it doesn't seem you can or should add additional non-supported attributes to the JSON-LD output...
Then again, I see there are a lot of attributes that are in fact supported. Like Brand. How do I add Brand to my JSON-LD? I guess all attributes from Schema.org are supported?


texts: How to get a few category groups in a single endpoint using Element API plugin?

texts:
I have many category groups and want to get some of them using single endpoint. Is it possible? If so, how?
Code like this return only one group:
'api/header.json' => function() {

        $header_genres = [
            'elementType' => Category::class,
            'criteria' => [
                'group' => 'bookGenres',
                'order' => 'title asc'
            ],
            'transformer' => function(Category $category) {

                return [
                    'id' => $category->id,
                    'slug' => $category->slug,
                    'uri' => $category->uri,
                    'title' => $category->title
                ];
            },
            'paginate' => false,
            'pretty' => true
        ];

        return $header_genres;
    }

But I need something like this (by design, the code below is not working):
'api/header.json' => function() {

        $header_data = [
            'genres' => [
                'elementType' => Category::class,
                'criteria' => [
                    'group' => 'bookGenres',
                    'order' => 'title asc'
                ],
                'transformer' => function(Category $category) {

                    return [
                        //...
                    ];
                },
                'paginate' => false,
                'pretty' => true
            ],

            'types' => [
                'elementType' => Category::class,
                'criteria' => [
                    'group' => 'bookTypes',
                    'order' => 'title asc'
                ],
                'transformer' => function(Category $category) {

                    return [
                        //...
                    ];
                },
                'paginate' => false,
                'pretty' => true
            ]
        ];

        return $header_data;
    }


texts:
Has anybody had issues importing JSON into table fields with the Feedme plugin?

I've got an issue where empty values in my feed are not being parsed into the correct table rows.

Source:

Result (after import):

Any thoughts on how best to resolve?


texts: Get Entries within a Category Group with no duplicates in each category

texts:
How would I loop through all categories in a group to get this scenario:

Get 4 entries per category
No duplicates across any of the categories, if it's in Cat 1, should not show in any other.
Category info (title, URL, etc)

So here is a visual:

Category 1

Entry 1
Entry 2
Entry 3
Entry 4

Category 2

Entry 1 (duplicate from Category 1, do not want here, so get 4 different)
Entry 5
Entry 6
Entry 7
Entry 8

Category 3

Entry 2 (duplicate from Category 1, do not want here, so get 4 different)
Entry 6 (duplicate from Category 2, do not want here, so get 4 different)
Entry 9
Entry 10
Entry 11
Entry 12

I hope this gives a decent visual of what I want.


texts:
Before you think this has already been answered, yes it is but I can't manage to get that fix working so I'm looking for another one.

I have a "title" field in a couple of my matrix blocks but my client want's to add a Bold word every now and then. Now I tried that with a rich text field which works fine except that it keeps adding a <p> tag to my text which makes the Indexing go wrong etc plus it shouldn't be so hard to remove but apparently it is...

This is my custom json at the moment:

{
    buttons: ['bold', 'italic'],
    maxHeight: 50,
    paragraphize: false,
    replaceDivs: false,
    linebreaks: true,
    enterKey: false
}

In every fix I find here this should do it but somehow it wont..


texts: Element query - using "search" vs using field handle as query method

texts:
With element queries, we can search for elements using search method:
craft.entries.search('someField:something')

or by using field handle as method:
craft.entries.someField('something')

How these two techniques are different from each other and when whould we use each?


texts:
I have a template that fails to load intermittently, resulting in a 404. I haven't been able to debug it since 99% of the time the page loads perfectly.

  2015/07/18 12:18:57 [error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in /var/www/html/cotm_2015/craft/app/controllers/TemplatesController.php:59
  Stack trace:
  0 [internal function]: Craft\TemplatesController->actionRender('30-days-of-pray...', Array)

Anyone have any ideas?


texts:
Well, to be honest i am completely new, not only to Craft but to most PHP stuff as well.
I am currently trying to setup a search for my page but i seem to miss a crucial step and can not find any tutorials on what to do.

On my front/ index page i included

<form action="{{ url('search/results') }}">
<input type="search" name="q" placeholder="Search">
<input type="submit" value="Go">
</form>

as stated in the Craft Documentation.

I have also set up a single page for my search results with the code from the Documentation as well:

Search Results

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).order('score') %}
{% if entries|length %}

{{ entries|length }} results:

    {% for entry in entries %}

{{ entry.title }}

    {% endfor %}

{% else %}

Your search for “{{ query }}” didn’t return any results.

{% endif %}

So, now if i try to search at the index page and hit enter, it just reloads the index page with the search term

site.url/index.php?q=test

So for sure i am missing a step here and am not loading the right page. I guess it should be stated in {{ url('search/results') }}, but i have no idea what to put there.

Would be great if anybody could help me or at least point me to a tutorial that focuses on setting up a site search in Craft CMS.


texts: How to load a template based on the first segment (and ignoring the second)

texts:
So I have my dinnermenu at example.com/dinnermenu but I want to show specific content for the next week if someone asks for it via example.com/dinnermenu/nextWeek but it should still use the entry data from dinnermenu ...

how can I achieve that ?


texts: Macros vs Variables, which one should I choose to give users of my plugin?

texts:
For Market commerce, good example templates and snippets of code are very important.

There is a few ways I can give these to the users of my plugin:

1) Example template folder. The user would manually copy the folder of templates into their templates folder. This folder could include twig macros that they could import to use in their templates and also allows them to modify the snippets easily.

2) Render a template partial from a Craft plugin Variable. This seems to be gaining a heap of popularity as I have looked through other plugins, but I don't really like the method as it does not allow users to update the code of the snippet without modifying templates in the plugins template directory. I also believe it is a remnant of eecms devs understanding of a antiquated templating system.

3) Full blown twig extensions. This gives the flexibility of doing native tags for wrapping blocks of code, it also suffers from the same issue as number 2.

I suppose a good solution would 1 & 3. The ability to easy use macros I make, with the ability to edit, but also an easy way to get core snippets of template functionality without needing to touch the html.

Maybe this is too open a question for SE, but what do you suggest is the best way to solve these issues. Should people stop putting html snippets into PluginVariables.php?

I suggest to P&T to enable a "pluginName/macros" folder to give designers the ability to import macros from the front end that they need without having to copy a whole folder of example code? This would allow the plugin dev to update the supplied macros at any time, but the designer can pick and choose which ones they want to copy into their templates folder and customize.

Suggestions and Ideas?


texts: Are there any plans to get Craft Docs in Dash App

texts: I use Dash to browse docs and was wondering if there are any plans to get Crafts docs into it. If it's not too difficult I'd like to request it for the future (eventually).


texts: Is it safe to have PHP files in the public directory of a craft cms website?

texts:
I just ‘discovered’ that the developer on my client’s craft website has been migrating his old landing pages to the new setup by cramming the older static pages into the public directory instead of using the CMS.

There are a lot of PHP files there but they are mostly using a PHP mailer setup - not any database queries.

My question is: how dangerous or safe is it to have PHP files in the public directory?


texts: Implement a compare products funcionality

texts:
I´m working in a buggy´s website, and i want to implement a "compare" functionality, where the clients can check some products from the list ( a checkbox in each product ) and be able to compare the products features side by side.

I think that i shold pass the array of values in the url from the checked products and in the compare page takes this values and filter the products. The only thing is that i don´t know how to implement it :)

Any help is welcome, thanks!

Sebastián.


texts: Is it possible to change the amount of time a user stays logged in for?

texts:
Our users are getting logged out after 1 day.

Is there a setting that changes how long users’ sessions will last?


texts:
I have a fruit Link it field that I use to allow users to choose an entry and have that page redirect to the chosen entry.  Not sure of the syntax to use to pass that link it field to the redirect field.

This does not work:

{% redirect "{{ block.redirect.url }}"  %}

Thanks


texts: Search matrix for blocks with upcoming dates

texts: I have a matrix field with one "event" block type that contains several fields. One of those fields is a date field. Is there a way to get just blocks with upcoming dates?


texts: How can I test if there are any changes in the Drag/Drop Field Layout Designer?

texts:
I've created a custom element type with it's own Field Layout Designer. The details about the custom element can be modified in the same form where the Field Layout Designer exists.  There is also a chance a person navigates away from the form without saving the changes after the Field Layout Designer is updated.

For example, if someone reorders one of the fields, doesn't save, and navigates away, the change they made in the editor may never get saved.  That's fine, and they have every right to, but I'd like to trigger a popup to warn them if they are about to navigate away without saved changes.

I can do this for all input fields with a snippet like the following.  The following snippet changes the isDirty variable to true and I can trigger a popup with my message if that value is true:

$(':input').change(function () {
  isDirty = true;
});

I can't seem to figure out how to do this for the Field Layout Designer.  How can I set the value isDirty to true whenever someone reorders a field or tab, or perhaps drags anything.

I've tried to add a listener:

this.addListener($('.tab.sel.draggable'), 'mouseup', '_onMouseUp');

And test for variables such as Craft.FieldLayoutDesigner.fieldDrag and !Craft.dragger.dragging but I haven't had any success and don't feel I'm approaching the problem with the right paradigm in my head.

Any ideas on how I can test if any items have been updated in the Field Layout Designer?


texts: How to Render a State Abbreviation in Craft CMS?

texts:
Folks,

Is there a way to render a state abbreviation in a front end template on Craft CMS? Currently, I have a plain text field that has the full text of a state and I would like to render the standard two letter abbreviation.

Here is my current code:

{% if eventType.eventState | length %}{{ eventType.eventState }}{% endif %}

I would be open to changing the field type (or downloading a plugin) if that makes things easier but don't see an address field or something that on the surface would be conducive to easily filtering down to an abbreviation.


texts:
I am trying to create the PHP $_SESSION equivalent in Craft CMS using Twig.
I have searched very long and I can't find how you can create sessions in Twig.

In previous posts I have found that I should edit some PHP controllers for this to work but I have just started using Craft and Twig and have no idea what controllers to edit to let this work.

So if someone has an solution to this can you please explain it like you are explaining it to a 2 year old kid?

Thanks in advance!


texts: Craft 3 icons not found in craftcms/cms/src/icons

texts:
Craft 3 version 3.0.4

When logging into the admin panel on Craft3 for some reason I'm getting a Yii2 PHP Warning for missing icons.

Error message:

PHP Warning – yii\base\ErrorException
file_get_contents(<pathtocraft>/craft/vendor/craftcms/cms/src/icons/c.svg): failed to open stream: No such file or directory

For some reason this icons folder is not being generated when installing craft3 via composer. This is currently happening on craftcms/cms/src/web/Application.php at line 363 where it tries to load the Yii logo.


texts: How to plan IA for a directory of content thats good for admins and users

texts:
I want to build a directory of fishing ports
It will have approx 500 entries, each geocoded for map display.
I will have 4 views;
1) Directory with map of entries
2) Country and entries
3) Cities (Ports) and entries
4) Port entry

Issues I have at this stage.

a) how to structure countries,cities and fishing ports?
admin will struggle to find stuff to edit if they have to page thru 500 entries  when entries have similar names "Stella maris centre" exists in Netherlands and Australia, denmark etc.  How can an admin distinguish the correct entry to edit?
This assumes I am using categories for country and city storage.

b) I want the url structure to be "directory/country/city/fishing-port-name"
Assuming I can use custom routes with categories to create my urls, i run into the issue above in a)

So should i create entry types for countries and cities and use them in heirarchy so admin can enjoy ease of finding stuff?

Planning around this is becoming a head spinner :)


texts: Getting server-side feedback when submitting forms with jQuery Form plugin

texts:
I've got a few simple front-end forms that users can use to update their profiles. I'm using the combo of the jQuery Validate and Form plugins to handle validation and submission.

I can successfully update profiles when the fields are technically correct, but can't figure out how to get feedback from the server if an error occurs after submission (aka invalid password, username already in use, etc).

Here's an example of my password update form:

      <form action="" class="secondary-content" method="post" accept-charset="UTF-8" id="pwForm">

Update password

    <fieldset>
      <input type="hidden" name="redirect" value="/profile">
      <input type="hidden" name="action" value="users/saveUser">
      <input type="hidden" name="userId" value="{{ user.id }}">
      <input type="hidden" name="password" value="{{ currentUser.password }}">

          New password Show password
          <input type="password" id="npw" name="newPassword" class="text-input" value="" required />

          <button class="button--red" type="submit">Update</button>

    </fieldset>
  </form>

Here is the javascript (in CoffeeScript syntax):

$('#pwForm').validate
  submitHandler: (form) ->
    $(form).ajaxSubmit
      type: 'POST'
      dataType: 'json'
      beforeSubmit: ->
        $(pwFields).transition opacity: 0
        $('#pwLoader').spin(opts).transition opacity: 1
      error: (xhr, status, error) ->
        $('#pwLoader').stop().transition opacity: 0
        $(pwFields).transition opacity: 1
        $(pwFields).append('There was an error. Please try again.')
      success: ->
        $('#pwLoader').stop().transition opacity: 0
        $(pwFields).text ''
        $(pwFields).html('
Password updated
').transition
          opacity: 1
          delay: 200

In this case, I'm actually tripping the "There was an error…" error no matter what I put in the field. If I pull out the javascript, the page refreshes and I don't get errors, but the password doesn't update.

I'm guessing it has to do with posting to the correct URL. Any ideas? Is it even worth using both/either of these plugins?

Thanks!


texts: How do I get the last uri segment from within a plugin (php)

texts:
I have some validation that checks for a unique email when creating a new person. Works great.

When I am updating the person, it's no surprise the system won't let me save because the email I am saving already exists.

I am working on a condition that compares the id to the existing person to who is getting updated.

Plugin_EmailValidator.php

...
$person = craft()->db->createCommand()
    ->select('id, 'firstName, lastName')
    ->from('people')
    ->where('email=:email', array(':email' => $model['email']))
    ->queryRow();

if(!empty($person)) {
    error_log('MATCH FOUND');

   // I have the id of the existing account. Need to compare against uri segment?
  $existingId = $person['id];
  $segment = craft()->request->getLastSegment();

  error_log($segment); // error!

   $message = Craft::t("Email already exists.");
   $this->addError($model, $attribute, $message);
}

This is what my url looks like:

/admin/plugin/controller/update/123

I see examples of using the request methods within twig, i'm trying to access it via php.

I've also tried this:

craft()->request->getQuery('update');

This will run without error, but it also returns nothing.


texts:
Is there a way to configure Craft further beyond just settings like 'cacheMethod' => 'redis',? I'm exploring the possibility of using Redis outside of the server Craft CMS is running on, and am curious if there is a way I can set this up while still using the built-in craft()->cache service.

I'd love to be able to utilize a remote cache option and configure it in the same way that cache has a db.phpconfig file where you can set your database as local or remote.

Is there any information about doing this out there and/or plans to support this eventually? Just curious.. thank you!


texts:
In the controller documentation for plugins, there's a section that talks about routing to specific actions using a Craft object like this:

var url = Craft.getActionUrl('cocktailRecipes/ingredients/saveIngredient', { id: 10 });

I think this object is the one in /craft/app/resources/js/craft.js, but I can't figure out how to make it available. I tried including it via includeJsResource, but this doesn't appear to be working

{% includeJsResource "resources/js/craft.js" %}

What do I need to include to be able to use this object in my JavaScript (it is not a load ordering issue, the URL generated by includeJsResource goes to the 404 page)?


texts: Displaying Pending users within CP users field (in plugin template)

texts:
I'm displaying a Users field within a template within a CP plugin, but when editing the entry, only Users that are active are being shown. Here is my field:

{{ forms.elementSelect({
    id: 'schoolteacher',
    name: 'fields[schoolTeacher]',
    elementType: craft.elements.getElementType("User"),
    elements: school.schoolTeacher | default,
    criteria: {"kind":[],"localeEnabled":null,"locale":"en_gb"},
    jsClass: 'Craft.AssetSelectInput',
    addButtonLabel: 'Select school teacher',
    sources: ['group:2']
}) }}

Viewing the exact same Users field within the standard CP entries section, all users are displayed irresepective of status. I think what I need to do is amend my field to allow usrs with the Pending status to be displayed. I've tried the following, but it makes no difference:

criteria: {"kind":[],"localeEnabled":null,"locale":"en_gb", "status": "active, pending"},
criteria: {"kind":[],"localeEnabled":null,"locale":"en_gb", "status": "Pending"},
criteria: {"kind":[],"localeEnabled":null,"locale":"en_gb", "status": null},

Looking through the app, I think status: null should return all of users of any status. Any ideas anyone?


texts: Tie two select fields together based on category and subcategory?

texts:
I'm trying to set up a front end form where the user can choose their city and state, which are stored as categories. I have states set up as the parent category and individual cities as sub categories.

I'd like to have the two select fields tied together so that when the state is chosen, the other select field is narrowed down to the cities in that state and vice-versa, e.g. if a user chooses Chicago only the Illinois select field should be available.

Is this possible?

Example:

Choose San Francisco --> California is selected

Choose Colorado -- > Only Colorado cities are available

Here are the two select fields. I know that using .level('1') and .level('2') is the wrong way, but I'm not sure what the correct way would be.

{% set userOptionIds = user.providerArea.limit(null).ids() %}

Parent locationCategories:
{% set parentCategories = craft.categories.group('locationCategories').level('1') %}

    <select id="providerArea" name="fields[providerArea][]">
    {% for category in parentCategories %}
        <option id="locationCategories" name="fields[locationCategories]" {% if category.id in userOptionIds %}selected{% endif %} value="{{ category.id }}">{{ category.title }}</option>
    {% endfor %}
    </select>

Child locationCategories:
{% set childCategories = craft.categories.group('locationCategories').level('2') %}

    <select id="providerArea" name="fields[providerArea][]">
    {% for category in childCategories %}
       <option id="locationCategories" name="fields[locationCategories]" {% if category.id in userOptionIds %}selected{% endif %} value="{{ category.id }}">{{ category.title }}</option>
    {% endfor %}}
    </select>


texts:
Anyone experienced with  issues setting up Craft on Windows server - getting phperror logs within Craft stating:

The directory is not writable by the Web process for cpresources

I have got the hosts to update the permissions for this folder but still throwing this error. Oddly Craft has no problem writing to the storage folder where these logs are stored and a similar set-up on the same server is working fine.


texts:
My plugin structure was created by the plugin factory. I have a setting called ulStateClass and I have been able to change the value of that setting in the Setting for the plug in. Looking at the 3.0 Docs page for settings I see the example:

// From your main plugin class:
$foo = $this->getSettings()->foo;

// From elsewhere:
$foo = \ns\prefix\Plugin::getInstance()->getSettings()->foo;

My namespace is recoveryfinder\craftnav

In my services php file I have the following to test:

echo \recoveryfinder\craftnav::getInstance()->getSettings()->ulStateClass;

I am getting the error:

  Error Class 'recoveryfinder\craftnav' not found

Making progress with Craft and enjoying it. I am guessing that this is a misuse or misunderstanding of namespaces? How Do I correct this?


texts: How can I disable/decrease the number of calls to getAuthTimeout?

texts:
The host of a client is claiming the call to getAuthTimeout is triggering their firewall, and in turn blocks my client from accessing their site for a longer duration.

Is there a way to disable or change the interval?


texts: Prevent shipping tax from doubling when item qty goes from 1 to 2 in cart

texts:
So.. it turns out commerce cannot apply tax to base shipping rates, see Calculating (Product + Shipping) + Tax? previously asked on stack.

I then tried setting the tax to a "Per Item Rate" to 99 and the "Maximum Total Shipping Cost" to 99, which I don't want exceeded no matter what. At first this seemed to work fine with a test product (price 5,-), however that was until I increased the qty to 2. The shipping cost for the cart stays at 99, however the shipping cost of the product doubles, which in this case also doubles the cart tax (20.8 to 41.6). This makes no sense to me.

I have attached a video demonstrating what I mean (I get the same result in the demo templates that come with commerce). See video: watch directly on Google Drive

We are just a week away from launch, and I just discovered this issue. Stressing out right now.

Thank you to anyone who can help enlighten me.


texts: unsucessful setFieldValues after programatically creating field on a migration

texts:
as part of a migration script I'm trying to:

create 2 new fields,
add them to a field group
add the new fields to a specific tab on an entry type
Update the values of the new fields

What I have so far works up until point 4, in the database the fields exist on the entry, I can see them there when I browse to an entry in the CMS, I can save new values to them, but, I cannot set a value with setFieldValues straight after. Can anyone suggest what I've done wrong here?
Here is my code so far:
public function safeUp()
{
    // Get contact field group
    $groupId = 31; // contact field group
    $fields = Craft::$app->getFields(); // Get fields
    $fieldGroup = $fields->getGroupById($groupId); // Get contact field group

    // Create heading field
    $headingFieldHandle = 'contactThanksHeading';
    $headingField = new PlainText([
        'groupId' => $fieldGroup['id'],
        'name' => 'Contact Thanks Heading',
        'handle' => $headingFieldHandle,
        "instructions" => "Larger heading text for the contact form's thanks message",
        "required" => false,
        "placeholder" => "Thank you",
        "charLimit" => 300,
        "multiline" => false,
        "initialRows" => "4",
    ]);
    // Save heading field
    Craft::$app->getFields()->saveField($headingField);

    // Create copy field
    $copyFieldHandle = 'contactThanksCopy';
    $copyField = new PlainText([
        'groupId' => $fieldGroup['id'],
        'name' => 'Contact Thanks Copy',
        'handle' => $copyFieldHandle,
        "instructions" => "Smaller copy text for the contact form's thanks message",
        "required" => false,
        "placeholder" => "One of our team will get back shortly...",
        "charLimit" => 300,
        "multiline" => true,
        "initialRows" => "4",
    ]);
    // Save copy field
    Craft::$app->getFields()->saveField($copyField);

    // Get contact single section
    $contactSection = Craft::$app->getSections()->getSectionById(2);
    // Get the section's entry types
    $contactEntryTypes = $contactSection->getEntryTypes();

    // Find entry type 2
    foreach ($contactEntryTypes as $entryType) {
        if ($entryType->id === '2') {
            $contactEntryType = $entryType;
            continue;
        }
    }

    // Get the field layout for entry type 2
    $contactFieldLayout = $contactEntryType->getFieldLayout(2);
    // Loop on tabs to find common
    foreach($contactFieldLayout->tabs as $tab) {
        if ($tab->name === 'Common') {
            $contactCommonTab = $tab;
            continue;
        }
    }

    // get the common tab's existing fields
    $tabFields = $contactCommonTab->getFields();

    // Set the sort order of the new fields to append them to the tab
    $headingField->sortOrder = count($tabFields);
    $copyField->sortOrder = count($tabFields)+1;

    // Add new fields to Common tab array
    $newFields = array_merge($tabFields,[$headingField, $copyField]);
    // Save fields to tab
    $contactCommonTab->setFields($newFields);

    // Set the tabs on the field layout
    $contactFieldLayout->setTabs($tabsForSaving);

    // Save the contact field layout
    Craft::$app->fields->saveLayout($contactFieldLayout);

    // get the contact entry
    $contactEntry = Craft::$app->entries->getEntryById(8);
    // Set the contact entry values
    $contactEntry->setFieldValues([
        $headingFieldHandle => '1',
        $copyFieldHandle => '1',
    ]);
    // save the contact entry
    Craft::$app->elements->saveElement($contactEntry);
}


texts: How do I hide a login form if user is logged in?

texts: What conditional statement would hide a form if a user is logged in?


texts:
I'm building a plugin for Craft CMS. This plugin will load on the edit/content page, where the standard Redactor WYSIWYG editor will be loaded too (by CraftCMS).
I want to get the HTML/text contents of the Redactor editor.

For example tinymce.activeEditor.getContent() will get the HTML contents of the TinyMCE editor in WordPress.

How do I achieve this in Craft CMS?

The API documentation says var text = this.clean.getPlainText(html);.
But how do I know reference to this.


texts: 403 forbidden error when moving entries in structure

texts:
We're running on fortrabbit.

I cannot sort entries in a structure without getting:

403 index.php?p=admin/actions/structures/move-element

Unauthorized
User is not authorized to perform this action

This is the only user and it's a super user / admin.


texts:
I´m using for the first time Guest Entries plugin to collect some info and some files from users, great! All it´s going great, the site admin will see all the info that the clients sends and the files from each one, but i would like to know if there is a way to download the assets from a specific entry, so keep it simple to download the assets sended by some specific user.

Something like this plugin does, but it doesn´t work.
https://github.com/Hambrook/AssetLinks

I found this one too, but it downloads the assets of a entire source.
https://github.com/mattstauffer/craftcms-DownloadAssets

Any help? Thanks!


texts:
I've already adjusted the php.ini with max values for timeout and file size. This is really perplexing me. I'm on Dreamhost VPS. I've triple checked all file permissions. I consistently get this error: "Upload failed for brooklyn_bridge.jpg. The error message was: “Error uploading the file: Uploaded file was empty" no matter what I try.

Here was a recent error after turning devmode on:

$_FILES=array (
  'assets-upload' =>
  array (
    'name' => 'brooklyn_bridge.jpg',
    'type' => '',
    'tmp_name' => '',
    'error' => 6,
    'size' => 0,
  ),
)

$_COOKIE=array (
  'b8d03c16c0ad94ea360e045e078389acusername' => 'fef6a177a0a30714376a5da4ec0d0f325256546as:60:"19b3e1b40c907258470bb0eada9aea0a67c491cdczo2OiJqb3NodWEiOw==";',
  'CraftSessionId' => 'XgGRKqGqqi1,Yosu0A37i0',
  'b8d03c16c0ad94ea360e045e078389ac' => 'dfb0e07d4a3e09dd9d62a5b04372e50bb9480660s:396:"315becd5240726fc3c5e92aca8e9c9b29fc61fdfYTo2OntpOjA7czo2OiJqb3NodWEiO2k6MTtzOjMyOiJIelM3UzhNWER0ODNlbEdmRUlTUXhORnFXOVFrRVUzbiI7aToyO3M6MzY6IjM4MmM2YzllLTY3NjItNGNiMy1iNjkzLTAxZjZmODQ2MTRmZiI7aTozO2k6MDtpOjQ7czoxMjE6Ik1vemlsbGEvNS4wIChNYWNpbnRvc2g7IEludGVsIE1hYyBPUyBYIDEwXzExXzUpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS81MC4wLjI2NjEuMTAyIFNhZmFyaS81MzcuMzYiO2k6NTthOjA6e319";',
)

$_SESSION=array (
  'b8d03c16c0ad94ea360e045e078389ac__id' => '1',
  'b8d03c16c0ad94ea360e045e078389ac__name' => 'joshua',
  'b8d03c16c0ad94ea360e045e078389ac__states' =>
  array (
  ),
  'b8d03c16c0ad94ea360e045e078389ac__timeout' => 1465416905,
  'b8d03c16c0ad94ea360e045e078389ac__auth_access' =>
  array (
    0 => 'uploadToAssetSource:36',
  ),
  'assetsSourcesBeingIndexed' =>
  array (
    0 => '1',
  ),
  'assetsMissingFolders' =>
  array (
  ),
)


texts: Element API - Entries Related to a Category

texts: In Craft 3, I want to list all the categories in a group and all the entries related to them. How can I do this?


texts: Require shipping method in Commerce order flow

texts:
I have a page, almost exactly the default Commerce shipping.html template and flow. With just the default shipping method (Free), the user can simply click through without being required to select a shipping method. I've found how to use a Business Logic plugin to address required fields for the address/billing section, but there doesn't seem to be an event I can hook to so I can yell and provide a flash error message if the user clicks "Select Shipping Method" without actually selecting one.

I know I can redirect back to the shipping method page on the payment page by checking the cart (ex: {% if not cart.shippingMethod %}...) but this doesn't provide a flash error unless I use some hacky method like a GET string error message.

Is there an event I can hook to I'm not finding in the docs that will let me force the choice of a shipping method? Or a setting in the plugin I'm missing?

Edit

So I'm close, here's my event code that isn't working as I expect it to (did I tell you I'm new to Craft yet?):

    craft()->on( 'commerce_orders.onSaveOrder', function ( Event $event ) {

        $order = $event->params['order'];

        if(craft()->request->getPost('validateShipping')){

            // add error to shippingMethod and see if we can get it
            $order->addError('shippingMethod',Craft::t('Please select a shipping option.'));
            $event->performAction = false;

            // pass a flash for testing
            craft()->userSession->setFlash('error', 'No shipping elected');
        }
    });

So this moves on to the payment page and doesn't return to the shipping page with the added error. However, I am able to retrieve the set flash message on the payment page but {{ dump(cart.getErrors()) }} results in an empty array, so either the error is not attached to the cart properly in my event, or it is lost for some reason.

Edit

I see I'm getting some up views; If anyone can still help I'd appreciate it. I have yet to get this working as per the only answer, and would love to know what I'm doing wrong in my Craft Commerce event.


texts: FeedMe error with iTunes RSS compatible feed

texts:
I am trying to ingest an iTunes compatible RSS feed on the template with FeedMe... the enclosures have things like <itunes:description> in them. When I try and access these properties I get the following error:

Unexpected token "punctuation" of value ":" ("end of print statement" expected).

Anyone know how I can access these enclosures without creating a Twig error?

Example current Twig code:

{{ feed[0].itunes:image['@href'] }}


texts:
I'm just looking for a little guidance here. I have a decent grasp of the matrix field but the functionality I want exactly is causing me some issues.

Im trying to setup a matrix field with the following:

Category name: Football (need the ability to set the category is in panel)

 -> PDFs

  -> PDF Title (Title of PDF)
  -> PDF Asset (Upload PDF Here)

  -> PDF Title (Title of PDF)
  -> PDF Asset (Upload PDF Here)

Category name: Rugby (need the ability to set the category is in panel)

 -> PDFs

  -> PDF Title (Title of PDF)
  -> PDF Asset (Upload PDF Here)

  -> PDF Title (Title of PDF)
  -> PDF Asset (Upload PDF Here)

  etc.

So looking at the matrix field it look like I need someway to create a matrix field within a matrixfield? I see i can use some plugins for this, But i want to make sure im not missing something first.

Thank you very much.

UPDATE

I've setup my matrix field like this, is this correct for what I want?


texts:
I am brand new to craft and have loved it so far.  Only area that I'm having a hard time understanding is why I cannot use my template variables in my templates.

I am routing news/ to an action which then uses the renderTemplate() method to do just that...render the template.  The result is sent to the browser but it is accompanied by the following php error:

Fatal error: Cannot declare class Craft\WassermanNewsVaraible, because the name
is already in use in /usr/share/nginx/craft/plugins/myPlugin/variables/MyPluginVariable.php on line 5

So that tells me that the class is obviously already declared somewhere.  If so how can I access it?  I am currently trying to access it as the documentation describes and is shown below:

{% for item in craft.myPlugin.myMethod() %}
  <div>
   Test
  </div>
{% endfor %}

Here is my template variable class which is in myPlugin/variables/

namespace Craft;

class MyPluginVaraible
{
    public function myMethod(){
        craft()->myPlugin->myMethod(); //which is in the service
    }
}

Is there a difference between how templates are rendered via controllers as opposed to the regular behavior?  I saw that the method had a second parameter however I still could not insatiate my template variables to pass that way as it was still already declared somewhere.

I've been banging away at this one for a while.  Any help or insight would be much appreciated.


texts: How can we use TaxJar with CraftCommerce?

texts: Is there anything akin to a presave event or postsave event where we can make a call to TaxJar API to get calculate and report sales tax? I find the integrated tax system impractical at the moment. I would like to create a plugin that can access the existing tax api platforms, but need to know the best insertion points for this.