texts: An extra event upon usergroup assignment onAssignUserToGroup

texts:
I have come across a scenario where I need an event like "onAssignUserToGroup". This is purely for a client request and to modify functionality in the backend CP for my plugin, but this is the second time the need for something like this has arisen in the past one month. I have created the event in the userGroups service for now but it will be overridden by updates hence I would appreciate it if something like this was added to the official craft codebase. If that is not possible then let me know if there is another way to get something similar.

In my craft/app/UserGroupsService.php:

public function assignUserToGroups($userId, $groupIds = null)
{
    craft()->db->createCommand()
        ->delete('usergroups_users', array('userId' => $userId));

    if ($groupIds)
    {
        if (!is_array($groupIds))
        {
            $groupIds = array($groupIds);
        }

        foreach ($groupIds as $groupId)
        {
            $values[] = array($groupId, $userId);
        }

        craft()->db->createCommand()->insertAll('usergroups_users', array('groupId', 'userId'), $values);

        *// Custom event
        $this->onAssignUserToGroup(new Event($this, array(
            'userId'   => $userId,
            'groupIds' => $groupIds
        )));*
    }

    return true;
}

That is partly what I have done for now.


texts: Is there simpler, less assuming Craft documentation?

texts:
I'm really struggling with understanding how Craft works at the moment.
I've been started mid-way on a particular project and I just can't get my head around how Craft works.

Their documentation seems to assume some knowledge I just don't have and combined with the intermediate-to-expert level of Craft-use in the project I'm on, I just can't figure it out.

Right now I'm failing at even the simplest things. I see fields as 'variables' of an entry, which are then sectioned?
I'm doing things that work one particular way:

{% set entries = craft.entries.slug('xyz') %}
{{entries.navigationCaptionTitle}}

..but not another:

{% for block in entries %}
  {{ block.navigationCaptionTitle }}
{% endfor %}

..and I think it's down to my basic understanding of how Sections, Entries and Fields work, how Craft manages them and their basic terminology. I'm definitely a visual learner so anything remotely graphical will help.

I don't have any CMS background, largely just working on html, css and js.


texts: Craft Commerce 2, turning on debug bar and getting error

texts:
Craft Commerce 2, turning on debug bar and getting an error.
"Invalid Configuration, Payment currency not allowed."

Could anyone shed any light of this error please?


texts: I set up a local environment. I can log in, but if I select the site icon or preview I get a 404 message

texts:
HTTP 404 – Not Found – yii\web\NotFoundHttpException
Template not found: $DEFAULT_SITE_URL
1. in /Users/brenbauer/morphd/craft3/vendor/craftcms/cms/src/controllers/TemplatesController.php at line 90
81828384858687888990919293949596979899    {
        // Does that template exist?
        if (
            (
                Craft::$app->getConfig()->getGeneral()->headlessMode &&
                Craft::$app->getRequest()->getIsSiteRequest()
            ) ||
            !$this->getView()->doesTemplateExist($template)
        ) {
            throw new NotFoundHttpException('Template not found: ' . $template);
        }

        // Merge any additional route params
        $routeParams = Craft::$app->getUrlManager()->getRouteParams();
        unset($routeParams['template'], $routeParams['template']);
        $variables = array_merge($variables, $routeParams);

        return $this->renderTemplate($template, $variables);
    }
2. craft\controllers\TemplatesController::actionRender('$DEFAULT_SITE_URL', [])


texts:
I have a complex html/css structure per 'row' that I would like to use Matrix to populate. Design markup as follows:

Title

Lorem Ipsum...

Title

Lorem Ipsum...

How would I get Matrix to change the markup per 'row'? I looked at switch but that seems to be for types of block content/types.

TIA.


texts: Subsites not found when running Craft 3 on shared hosting

texts:
On most shared hosting, you can't set the webroot. As an alternative, a rewriterule to the web folder can do this.
Could be something like RewriteRule ^(.*)$ web/$1 [L].

This works on main sites in Craft 3, but breaks subsites.

I've found an answer from Brandon Kelly, suggesting to use different indexes.php and loading the correct one via the htaccess. (based on subsite prefix)

Is there a better solution since this date, that might prevent the need for different indexes?


texts:
I'm going through(learning) class reference TableFieldType in Craft 2 and I'm having trouble pulling out the value from a table field and save it as variable. I'm not sure I've started with the right approach.

This is the piece of code I'm working on where contact details are saved to the table field. The problem starts when I need to get the email address value from that table field and use it further on.

public function init()
{
    craft()->on('guestEntries.success', function (GuestEntriesEvent $event)
    {

        /** @var EntryModel $entryModel */
        $entryModel = $event->params['entry'];

        if($entryModel->getSection()->handle === "orderId")
        {

          $emailSettings = craft()->email->getSettings();
          $email         = new EmailModel;
          $emailAddress = '';

          // Questionable, not complete block of code
          // Get value of "emailAddress" singleline type column from the "contactDetails" table field type
          foreach ($entryModel->getFieldLayout()->getFields() as $fieldLayout)
          {
            $field = $fieldLayout->getField();

            if ($field->getFieldType()->getName() == Craft::t('Table'))
            {

              foreach ($entryModel->{$field->myHandle}-> ??? as $input)
              {
                 $emailAddress = $input->???;
              }
            }
          }

          $email->toFirstName = $entryModel->getAuthor()->firstName;
          $email->toLastName  = $entryModel->getAuthor()->lastName;

          // Test if email address from "contactDetails" table field is present
          $email->toEmail     = !empty($emailAddress) ? $emailAddress : $entryModel->getAuthor()->email;

          $email->fromEmail   = $emailSettings['emailAddress'];
          $email->replyTo     = $emailSettings['emailAddress'];
          $email->sender      = $emailSettings['emailAddress'];
          $email->fromName    = craft()->config->get('siteName');
          $email->subject     = craft()->config->get('siteName') . " - New order received";
          $email->body        = "...";
          craft()->email->sendEmail($email);

        }

    });
}


texts: Is it possible to adjust Redactor config on a per-user basis?

texts:
So in the Redactor config file, I have the standard "source" plugin enabled:

"plugins": ["source"]

This is great for the admins who want to go in a play with around with the markup. However, I'd like to avoid certain user types from having that level of control. Essentially I want to stop clients messing with stuff they shouldn't.

Is this possible?


texts:
I'm using the Hacksaw plugin to truncate text and it does a great job except instead of rendering HTML entities such as "&", it's outputting them as "&amp;". How can I correct this? Putting them in allow="" doesn't work. Do I need to do something to manipulate the text string first before applying the Hacksaw filter? Or is there a Hacksaw option that would correct this?

Edit for more info...

Example of text as it should appear:

Colour & Light; A House Re-crafted, cover & pg.99-108

Example of text output from Hacksaw:

Colour &amp;amp; Light; A House Re-crafted, cover &amp;amp; pg.99-108

Stupidly I hadn't looked at the HTML until now. It looks like the first &amp; is rendering correctly but then there's a second partial entity after it?!

Template code I've tried:

{% set summary = article.newsArticle.type('text').first().text|hacksaw(words='35', append='...') %}

{% set summary = article.newsArticle.type('text').first().text|hacksaw(words='35', append='...')|raw %}

{% set summary = article.newsArticle.type('text').first().text|raw|hacksaw(words='35', append='...') %}

The order of plugin doesn't appear to have any effect. I get same result with all three of these arrangment above, including no Raw plugin at all.

Edit for answer

As per accepted answer below, final working code is:

{% set summary = article.newsArticle.type('text').first().text|htmlEntityDecode|hacksaw(words='35', append='...') %}

The Craft Helpers plugins did the trick.


texts: Unwanted output when using Twig conditional

texts:
I am displaying a series of icons and associated labels in an unordered list. Some of the icons should only be displayed when a user is in a specific set of user groups, so I am using a conditional. Without the conditional, the icon and label displays perfectly, but when I wrap it in a conditional, it seems to output an extra blank character which breaks my layout.

Entry 1

{% if currentUser.isInGroup('admin') %}

Entry 2

{% endif %}

Chrome Inspector shows two quotation marks separated by a blank line between the li.icon elements, which I think indicates one blank character. When I remove the conditional, these quotation marks and the blank line don't appear, and the layout looks correct.

If I collapse all the logic and HTML elements into one long line of characters with no spaces between them, this weird blank output still occurs. Wrapping the block in the {% spaceless %} tag doesn't seem to work either.

What might be causing this?


texts: compiled_templates folder using up inodes on Ubuntu 14.04 Server

texts:
My server has gone down twice in the last 3 weeks because of an excessive number of files being created in the compiled_templates folder. This causes all of the inodes on our server to be used up causing the site to crash.

We previously thought this may have been because of a security test that hit multiple URLs on the site and generated too many templates. The original question can be seen here Security test generated large compiled_templates directory, site outage

This time there was no unusual traffic spike, so I can't assume it was because of the security testing. The only common thread seems to be that garbage collection is either not deleting the old compiled templates or craft is mis-configured. Any insights into this issue would be much appreciated.

EDIT: Looking in the compiled_templates folder it seems there are a few hundred different folders with names like 00 a9 b3 ... and inside those folders are sometimes hundreds of PHP files. I can't track down what templates some of them go to. For example one of the comments up to reads: /* __string_template__cc8a06d92434271d04fe341ad237b568da4c65f004cfec4d1fc576ee4e9b6c4a */

They have functions that echo out single lines of text, these functions are called doDisplay. I am not the original author of this site and am not an expert at Craft. I appreciate the help.


texts:
I'm using the most recent Craft CMS 2.6.2791. I'd like to generate preview thumbnails for pdf assets in my templates, so I found this plugin:

https://github.com/carnesmedia/pthumb

However, following the instructions on the readme page gives a nonsense url. In my template, I have:

<img src="{{ craft.PThumb.thumbnail(pdf) }}">

If I inspect the src generated by this I see

http://localhost:8888/myproject/public//assets/pdfs/previews/b15c8529f2b4a9b354c5e592e84d1ac5.png

However, this renders as a broken image. I check my project structure and the previews directory is nowhere to be found. Am I doing something wrong or perhaps missing a step?

I'm also open to any other solutions that could generate a thumbnail from the first page of a pdf asset automatically. Thanks!


texts:
I'm trying to set a 404 HTTP status response code for an ajax controller action in a plugin.

Yii has a response object where the code can be set, but I can't find a way to access it from craft.


texts: Where should I add the file to write the code for the `afterSend` event for contact form plugin?

texts: I am using the contact form plugin in Craft CMS 3. I want to add the afterSend event. Where should I add the file to write the code for the afterSend event?


texts: Amazon S3 endpoint is wrong when accessing Asset info

texts:
Amazon S3 is returning the following error for a file in a bucket that is in Ireland (s3-eu-west-1):

  [PermanentRedirect] The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

The URL prefix is setup to be s3-eu-west-1.amazonaws.com, and using the S3.php class standalone with my key/secret, the bucket are listed as being in eu-west-1.

I tried logging out inside S3->getObjectInfo() what endpoint Craft/S3.php was using when accessing the file.

For some reason, it's s3-us-west-2.amazonaws.com. Isn't that weird?


texts: Next in structure if lightswitch field off?

texts:
I'm trying to get the next field in an entry if a passwordRequired Lightswitch Field is switched off.

How would I go about that?


texts: Is There a Way to Add Tabs in Global Fields?

texts:
I see that it is not possible to add tabs to Global fields (unlike, say, with entries, where one can organize one's fields into different tab groups).

Is there a way (without editing the core files) to change this so that I can organize my global settings fields into tabbed sections?

Thanks.


texts:
I have this form (am forms plugin):

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

          {% for error in errors %}

{{ error }}

          {% endfor %}

  {% endif %}
{% endmacro %}

{% from _self import errorList %}

{% set form = craft.amForms.getForm('contactForm') %}

<form method="post" action="" accept-charset="UTF-8">

  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="amForms/submissions/saveSubmission">
  <input type="hidden" name="handle" value="{{ form.handle }}">

   {{ 'Nachricht' | t }}*
   <textarea id="frm_message" name="fields[message]" value="{% if formHandle.message is defined %}{{ formHandle.message }}{% endif %}"></textarea>
    {% if form is defined %}
        {{ errorList(form.getErrors('message')) }}
    {% endif %}

  <input type="submit" value="Submit">

</form>

This is not displaying any errors if the field is empty. What do I miss? I made the field required in the CP but the macro is not showing when hitting "submit" with the field empty.


texts: Excluding entries based on a tag across whole site

texts:
I'm trying to exclude entries that are tagged "DO NOT PROMOTE" on any page where craft.entries is used minus their actual entry page.

What I've come up with so far is this:

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

    /*
        Exclude DO NOT PROMOTE tagged entries
    */
    // Get DO NOT PROMOTE tag id
    $tagCriteria = craft()->elements->getCriteria(ElementType::Tag);
    $tagCriteria->title = 'DO NOT PROMOTE';
    $tag = $tagCriteria->first();

    // Get Entries related to above tag
    $entryCriteria = craft()->elements->getCriteria(ElementType::Entry);
    $entryCriteria->limit = null;
    $entryCriteria->status = null;
    $entryCriteria->relatedTo = [
        'targetElement' => $tag,
        'field' => 'tags'
    ];
    $doNotPromoteEntries = $entryCriteria->ids();

    craft()->on('elements.beforeBuildElementsQuery', function(Event $event) use ($doNotPromoteEntries) {
        $criteria = $event->params['criteria'];

        $criteria->id = 'and, not ' . implode(', not ', $doNotPromoteEntries);
    });
}

Now this kind of works. The issue I'm running into is the homepage is now showing an entry post... which is should not be. So, my modifying the criteria has caused this issue.

Is there a more eloquent or better way to accomplish this?


texts: Manually override feed element in settings using the FeedMe plugin

texts:
I'm fairly new to Craft so I could be missing out on some basics.
I need to import an events feed (xml) using the FeedMe plugin. The feed has some Link tags.
Ex.
<link rel="sales" type="text/html" href="[LINK TO TICKETSHOP]" />
<link rel="image" href="[LINK TO IMAGE]" />

I've got an Asset field but I can't properly set the Feed Element. It only shows <link/@href> or <link/@type>. If I select @href then it goes though all the elements with @href and generates a lot of errors because some aren't assets.
I've tried <link/@rel="image"> in the default value field but then it imports the same value for all the Events. So all the Entries end up with the same image.
Is there a way to manually define the Feed Element?


texts: Can I change the image position dropdown in Redactor?

texts: I want to change the image position dropdown in the "Edit Image" window or add a new one that give me a different way to control image position. Rather than having this dropdown change the float, I want it to add a class to the image. i.e., instead of "float: left" class="left". How do I do that?


texts: Create filters from Matrix Blocks on entries or products

texts:
I have a range of products on a product collection page. Each product has a matrix block (ageRange) with a group of checkboxes (values 1-10).

I am currently trying to get loop through all products, get the matrix block values and push them into a new array, with the amount of times the value appears!

{% set myArray2 = [] %}
{% for product in craft.commerce.products({relatedTo: category}) %}
  {% for block in product.ageRange %}
    {% for option in block.options %}
      {% set myArray2 = myArray2|merge({ ('key'): option }) %}
    {% endfor %}
  {% endfor %}
{% endfor %}

{{dump(myArray2)}

This seems like a very bad approach. Even if I can get this working, it is clunky and no doubt un-performant.

Essentially I am looking for a way to attached fields to products, and easily get the total amount of times that that field is used.

Have I overlooked something simpler?
if not, is twig the right place to do this?

Desired output would be:

1 (6)
2 (3)
3 (3)
4 (6)
5 (0) // i'd hide this
6 (1)


texts: Moving from staging (MAMP) to live production server

texts:
I'm a long time WordPress developer who's moved over to Craft CMS (loving it).

When moving over WordPress sites from MAMP to a live production server, I follow this process:

Upload all WP files to live server
Export database via phpMyAdmin
Create database on live server and import database dump
User search and replace tool to change URLs
Flush permalinks via WP admin

For Craft, I've done the following:

Upload all Craft files to live server
Export database from CP in Craft
Create database on live server and import Craft DB zip
Via live Craft CP, change Site URL and Asset URL

Everything is working perfectly, but I just want to check I hadn't missed anything here? Not having to do a search and replace is awesome.


texts:
I want to Number validation for my site, but not able to show custom validation message to user.

       'CVV' => [
            'label'    =>  'CVV Number',
            'type' => 'numerical',
            'numberPattern'=> '^[0-9]{3,3}$',
            'min'   =>  100,
            'minLength'   =>  3,
            'max'   =>  999,
            'maxLength'   =>  3,
            'required' => true,
            'integerOnly'   =>  true,
            'tooSmall'  =>  'CVV Number is too small (minimum is 3 characters).',
            'message'  =>  'CVV Number is too small (minimum is 3 characters).',
            'tooShort'  =>  'CVV Number is too small (minimum is 3 characters).',
            'tooBig'  =>    'CVV Number is too long (maximum is 3 characters).',
            'tooLong'  =>    'CVV Number is too long (maximum is 3 characters).',
        ],

I tried to set

AttributeType::Number

Also. But it didn't work.
The issue:
in the case of numbers like less than 3 characters, I am getting error message:

CVV Number is too small (minimum is 100).

Please Can anyone help me to get this expected message.
Thank You.


texts:
I am trying to bring some of the order status history from my clients commerce shop orders into a web page. I seem to be able to get the Current/Previous Status (prevStatus/newStatus.name), but cannot seem to get the elements in the attached image - 'Updated By' and 'Date'.
I have tried a few different tags e.g. 'order.orderStatus.date|datetime' but they just seem to update the the time 'now' rather than the time of the order status change.
Its probably an obvious answer but i cant find this tag to output-  if anyone can help that would be great
Thanks
Malcolm


texts:
I've used redactor's custom formatting option before, but now I can't get anything to work. Here's what my file currently looks like:

{
    "buttons": [
        "formatting",
        "bold",
        "italic",
        "lists",
        "link"
    ],
    "formatting": ["p","blockquote"],
    "formattingAdd": {
        "h2": {
            "title": "Heading",
            "args": ["h2"]
        },
        "h4": {
            "title": "Subheading",
            "args": ["h4"]
        },
        "caption": {
            "title": "Caption",
            "args": ["p", "class", "caption"]
        }
    },
    "buttonsAdd": ["sup", "sub"],
    "linkNewTab": true
}

I have the "h2" and "h4" under "formattingAdd" because I wanted them to use custom titles.

The problem is, none of my custom formats are working. The "p" and "blockquote" from "formatting" are working properly, but the other three styles don't do anything. They appear in the list, but don't restyle the text in the editor, or create the elements in the output.

Is there something in the syntax I'm missing? I'm in Craft 3, with the redactor plugin updated to the latest version.


texts: Displaying entries with pagination on a category page where the entry's last category in the array is the current category

texts:
I want to only display entries on the category page which is the last in the array of the entries category, so that it doesn't also show on parent category page.

Let say these are my categories:

Shop

List item
Shoes
T-shirts

Entries with a category of "shoes" displays under both "shop" and "shoes" because of the way categories work as an array. My aim is to have it show only on "shoes", not "shop".

Here is my current code:

    {% set params = {
      section: 'shop'
    } %}

    {% if category is defined %}
      {% set params = params | merge({
        relatedTo: category
      }) %}
    {% endif %}

    {% set blogEntries = craft.entries(params) %}

    {% paginate blogEntries.limit(9) as pageInfo, pageEntries %}

      {# for entry in pageEntries if category.id == entry.productCategory.last().id #}
      {% for entry in pageEntries %}

{{ entry.title }} ({{ entry.productCategory | join(', ') }})

      {% endfor %}

  {% if blogEntries|length > 9 %}
    {% include "_partials/pagination.twig" %}
  {% endif %}

I've managed to display the entries under the correct categories with the
if category.id == entry.productCategory.last().id on the for loop displaying all the entries, however this does not work with pagination.

My question is, is there a way to bake the conditional into the initial category params to avoid looping through all entries where the current category doesn't match the last category within the entry's array.

I hope this makes sense, please feel free to get in touch for any clarification.

Thanks,
Teegan


texts: Using Composer to Manage Site-Level Dependencies

texts:
I would like to use Composer to manage dependencies for my site, like Twitter's Bootstrap.

Is there a recommended way to integrate Composer with Craft to support managing this type of Global dependency (as opposed to managing dependencies for an individual plugin)?

Or should I make a plugin that somehow sets up Bootstrap as the theme for my site?


texts:
Maybe I have not understand how entries work but I would like to create a rich text field in my plugin without having an entry.

All I want is creating a rich text field with twig but how can I do this? I already read this https://craftcms.com/docs/rich-text-fields but it was not really helpful. I would just like to have something like this just for a rich text field instead of a normal textfield

{{ forms.textField({
    label: 'Ingredient Name'|t,
    required: true,
    name: 'ingredient[name]',
    value: ingredient ? ingredient.name : null,
    errors: ingredient ? ingredient.errors('name') : null,
 }) }}

Could someone please help me?

if I make {{ entry.richTextFieldHandle }} I get the error Variable "entry" does not exist and I don't know how to define entry since I don't use an entry. Do I have to include my own redactor.js if I just want to have an html editor?


texts: Web folder content moved up a level - Craft Path settings

texts:
I use subdomains for staging environments. That meant in Craft 2 I had to move the public_html folder content up a level and change

$craftPath = '../craft';

To:

$craftPath = 'craft';

I'm getting myself in a bit of a mess how to do this for Craft 3. I've moved the contents of 'web' into the root folder for the subdomain.

I think I have to change these settings

define('CRAFT_BASE_PATH', dirname(__DIR__));
define('CRAFT_VENDOR_PATH', CRAFT_BASE_PATH.'/vendor');

but it's a bit over my head, so any help to what I change these to would be much appreciated.

My hosting doesn't allow configuring the webserver to point to the /web folder.

Structure:

index.php
css
js
craftcms

config
modules
storage
templates
vendor


texts:
In Craft 2 Commerce 1 one could apply a coupon code with "per email limit" during checkout, without having the email added to the order/cart model(s).
In Craft 3 Commerce 2 the same scenario yields this error;

Discount is limited in use to those who have supplied their email address.

This is probably good behavior, for the most part, but is there any way around it to have it work like in Craft 2 Commerce 1? Meaning; make coupon codes with email limits applicable to carts without an email. The reason being the convention of having your cart overview with some initial cost details, wherein you could add discounts and then proceed to checkout and shipping and all that.


texts:
New to Craft and general novice full stop. I'm not sure about the correct way to use craft and git together. I currently use BitBucket for version control and have been using ExpressionEngine... so installing Craft and understanding the proper workflow is a bit confusing to get my head around.

I installed Composer locally and ran the command to install Craft 3, but then I just ended up putting all those files into BitBucket and then connecting that with my server, I created a database and then installed Craft on the server instead of locally. I have a feeling that's the wrong way to go about it, especially after reading that I shouldn't be putting the .env file in version control (which I can't understand?? if the .env file doesn't make its way to the server how does Craft know what database, etc. to connect to?)

Can anyone tell me or point me in the right direction to how I can learn the propper/correct flow and setup?

Thanks


texts:
We have a commerce site that provides samples of its items. We have a single product that handles all the samples and displays them in a dropdown.  What I'd like to do is have a link on the product page that passes this product name/slug to the sample product. What would be the best way to approach this?

The sample product url is /samples/sample. I have tried something like Order a Sample. But that tries to look up a product with that url and it does not exist.

In the dropmenu I am trying

{% set prodSlug = craft.request.getLastSegment() %}
<select>
{% for purchasable in product.variants %}
    {% set current = (product.slug == prodSlug) %}
       {% if current %}
        <option {% if purchasable.stock <= 0 and purchasable.hasUnlimitedStock == false %}disabled {% endif %} value="{{ purchasable.id }}">
        {{ purchasable.description }}  {{ purchasable.price|commerceCurrency(cart.currency) }}</option>
       {% endif %}
{% endfor %}
</select>

Is there a way to setup a product that could accept different slugs to make this work? Maybe with a route?


texts: How to display data in field type with dropdown multi select checkbox?

texts:
I'm able to get data using API but when I use checkboxField then it only display the blank checkbox without value. In Model,

    if($result){
        if (isset($result->error)) die($result->error_message);
        //convert json data to array
        $arr = json_decode($result, true);

        //Get project array from API
        $json = $arr['projects'];

        foreach ($json as $i => $v){

            return array_merge(parent::defineAttributes(), array(
                'someField'     => array(AttributeType::String, 'default' => $v['name']),
            ));
        }

And my template,

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

{{ forms.checkboxField({
id: id ~ 'someField',
class:'nicetext',
name: name ~ '[someField]',
value: values.someField,
checked: value,
errors: values.getErrors('someField'),
required: false,}) }}

Need some help. TIA!


texts: Craft Commerce: Add to Cart and then Redirect to Product Page?

texts:
On my product page I have the default button that "Adds to cart" which adds a line item to the cart and take you to the cart page.

How do I create a second button alongside the default that adds the line item to the cart BUT then redirects the customer to the same page to select and customise another line item to add to cart?

Note: Ill very likely change the styling and text on the button (just in case anyone is concerned about usability) ;)


texts: How to enforce capitalisation on users First Name and Last Name

texts:
We have developed a Craft 3 site that has user registration. Once a user account has been confirmed and activated, they are shown in a Contacts directory, which other users can search through.

As the user is responsible for adding their own details, a few users have submitted their names in lowercase:

jamie wade instead of Jamie Wade.

Whilst there is nothing wrong with this, it doesn't look great. Is there anyway we can enforce capitalisation in Craft on the users First Name and Last Name fields?

I am aware of Twig's title filter, and this is a good fallback if there isn't anything else.


texts: I'm trying to create a multi user blog, where multiple authors can edit the same entry. Is this possible with Craft CMS? Is there a way to assign multiple authors to an entry? I only managed to assign one user as an author.


texts: Updates on live server without using Control Panel

texts:
I'll freely admit to being a bit of a newb when it comes to SSH but wanting to start utilizing it more for my Craft3 sites. Maybe this is an irrelevant question but is it possible to update craft on the live server through ssh?

I'm ssh'd into my server and tried ./craft update all but I keep getting Permission denied.

composer update works fine though. Am I making a mistake or is it more of a hosting configuration issue?


texts: Catch-all routes based on template structure

texts:
I have many of the templates organized into sub-folders. E.g. /manager/entries/edit.html, /manager/users/edit.html etc.

The site is using 4-segment URLs to access code in those templates, e.g. http://site.com/manager/entries/edit/{slug}, http://site.com/manager/users/edit/{id} etc.

Currently I have to set up custom route for every template, e.g.     'manager/users/edit/(.*)'        => 'manager/users/edit', etc.

Is there a way I could set up a "generic" route which would first check for existing templates in a subfolder (whether globally or on per-folder basis) and try to use that first? So I would not need to create route for each individual template.


texts: Translate icon appears but no translations exist

texts:
I have a site in development that i replicated from another project.
The other project was multi lingual and had some fields that were translated.
This new site does not require any translations but the transalte icon is still appearing next to some fields which is very annoying.
Any idea how I can safely remove these?


texts: Over ride auto-generated alt tag on image added via Rich Text field

texts:
When I add an image via a rich text (doing as port of a flexi layout approach) somehow an alt tag gets auto output, e.g:

alt="sketch2.jpg#asset:308

I wondered if there is a way to over ride or edit the HTML via the rich text field for the auto generated alt tag?


texts: Setting Shipping Country and Method for the Cart screen

texts:
I want to set the default countryId and a default shipping method (there is only one shipping method but contain several rules), so that the cart screen shows this and we can then present a shipping cost. I then want to build a facility for the customer to change their country on the cart screen so that they can update their country to see the new shipping costs.

Any ideas how to approach this?

If I pass in the following;

<input type="hidden" name="shippingAddress[countryId]" value="77">
<input type="hidden" name="shippingMethod" value="standard">

on the product/add to cart screen then the flash messages shows;

  ERROR! CART NOT COMPLETELY UPDATED.

And whilst it sets the shippingAddress[countryId] on that product page (I checked for it) when I navigate to the cart screen the shippingAddress[countryId] is then not set at all.


texts: PayPal Express not redirecting back to Craft Commerce

texts:
I have entered API Username, Password and Signature from PayPal and added 'tokenParam' => 'craftToken' in Craft config and yet when I try to make a payment using PayPal Express I get the following....

https://www.site.com/index.php/actions/commerce/payments/completePayment?commerceTransactionId=114&commerceTransactionHash=0ec5451ed35b360311214dfa75aee88f&token=EC-9GX1527947961953D&PayerID=RFN3LXKUP6SVQ

With the following error:  The requested URL was not found on this server.

Any suggestions on what I have missed.

Here is my craft/config/general.php file.

$domain = 'www.site.com';

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $domain . $_SERVER["REQUEST_URI"]); exit();
}

define('URI_SCHEME',  ( isset($_SERVER['HTTPS'] ) ) ? "https://" : "http://" );
define('SITE_URL',    URI_SCHEME . $_SERVER['SERVER_NAME'] . '/');
define('BASEPATH',    realpath(CRAFT_BASE_PATH . '/../') . '/');

return array(
    '*' => array(
            'siteUrl' => SITE_URL,
            'environmentVariables' => array(
            'siteUrl'  => SITE_URL,
            'basePath' => BASEPATH,
            'defaultImageQuality' => 60,
            'omitScriptNameInUrls' => true,
            'tokenParam' => 't',
        ),
    ),
);

FORM

{% if cart.paymentMethodId %}

    <form method="POST" class="form-horizontal" id="paymentForm">

        <input type="hidden" name="action" value="commerce/payments/pay"/>
        <input type="hidden" name="redirect" value="/shop/customer/order?number={number}"/>
        <input type="hidden" name="cancelUrl" value="/shop/checkout/payment"/>

        {{ getCsrfInput() }}


texts: Are categories the best way to organize Commerce product filters?

texts:
The Commerce site I'm working on (my first Craft project) will have a product listing page with filters. These will function as you would expect, but clicking a filter name will link to another version of the product listing page with another set of products, as opposed to updating the page via AJAX. I'm doing the content modeling now and am wondering if Craft categories are the best way to structure this or if there is a better way. I see it working somewhat like the Patagonia product page (click through the categories toward the top of the sidebar and note the URI change). However, unless there's an advantage to doing otherwise, I was just going to use categories for both of the filter sets below. Patagonia uses query string parameters when filtering by sport, whereas this site would have a unique slug(s) for each combination of filters.

Here's what the filters look like. A checkbox or some other visual indication would be given when a filter is selected:

Product Categories

Category 1 (slug: category-1)
Category 2
Category 3
New Products

Shop by Use

Use A (slug: use-a)
Use B
Use C
Use D

The selection options are:

Only one Product Category can be selected at a time (choosing another deselects the previous selection), but a selection is not required.
Only one Use can be checked at a time (choosing another deselects the previous selection), but a selection is not required.
A selected filter can be unselected by clicking it.
With the Product Category and Use options unselected, a page with ALL products is displayed.

A few more notes:

Every product will belong to at least one Product Category but can belong to multiple.
Every product has at least one Use and most have multiple.
'New Products' is a unique category that would ideally expire based on a date chosen when adding a product.
I was picturing the URIs being something like the following:

Category selected: domain.com/products/category-1
Use selected: domain.com/products/use-a
Category and Use selected: domain.com/products/category-1/use-a or domain.com/products/category-1-use-a

Questions

Are categories the best tool for this job? If not, what would work better? If so:
Would it make sense for Product Categories and Shop by Use to be their own category groups?
Creating category pages is simple enough, but I'm not sure how best to create a page that represents a combination of categories / selected filters (e.g. Category 2 + Use A). I know I can use relatedTo to list products from multiple categories, but what is the best Craft element to use as a container for these pages? This answer was helpful, but it's not quite the same (for one thing, it's not Commerce-specific; it refers to products but I believe they are just standard channel entries). Should the combined-category pages be in their own channel?
New Products: I'm thinking this should be a static link, possibly to a single (/products/new) that lists products whose "newness" has not expired. Is there a better way?

I'm probably overthinking this! I mainly want to know if I'm heading in the right direction.


texts: Is it safe to remove the craft/storage/runtime/sessions folder?

texts:
I'm unable to transfer a site over to my development server because I keep getting problems with disk space. Space is actually fine, it's the number of inodes being used up. Using cPanel I get an error when using file manager to view the sessions folder, so I think that's the issue.

Using the following command, which I think is the one for counting the number of files in a directory:

ls | wc -l

It looks like there are over 300,000 files in there. How safe is it to delete the entire directory?


texts: Use .env values in Craft 3 plugin settings

texts:
I’m writing a plugin and need some of its settings to be pulled from the .env file. According to the docs the following should work, but the getter isn’t getting called whenever the plugin’s youtubeApiKey setting is requested; it just keeps returning $YOUTUBE_API_KEY.
When I set the property visibility to protected instead of public, it does call the getter but also reveals the (sensitive) key in he admin settings panel.
class Settings extends Model
{
    public $youtubeApiKey = '$YOUTUBE_API_KEY';

    public function getYoutubeApiKey(): string
    {
        return Craft::parseEnv($this->youtubeApiKey);
    }

    public function behaviors()
    {
        return [
            'parser' => [
                'class' => EnvAttributeParserBehavior::class,
                'attributes' => ['youtubeApiKey'],
            ],
        ];
    }

    public function rules()
    {
        return [
            [['youtubeApiKey'], 'string'],
            [['youtubeApiKey'], 'default', 'value' => ''],
        ];
    }
}

I suppose my understanding of the settings getters is incorrect, but what I’m trying to achieve is for MyPlugin::getInstance()->getSettings()->youtubeApiKey to return the actual API key (not $YOUTUBE_API_KEY) and for the settings field (below) to display $YOUTUBE_API_KEY (not the actual API key).
{{ forms.textField({
    'id': 'youtubeApiKey',
    'label': 'YouTube API key',
    'name': 'youtubeApiKey',
    'suggestEnvVars': true,
    'value': settings.youtubeApiKey
}) }}


texts: FormBuilder - PHP notice Trying to get property of non-object

texts:
I'm trying to do a form, I'm using FormBuilder plugin.
I have the form and the fields, but when I try to acess ../admin/entries to manage the content of the page, I have this error, why is that? What did I miss?
I The code in that page:

{% block content %}

{{ entry.title }}

<form method="post" accept-charset="utf-8" name="{{ form.handle }}" class="formbuilder-form" id="{{ form.handle }}" data-parsley-errors-container=".formbuilder-notification"{% if form.hasFileUploads %} enctype="multipart/form-data" {% endif %}>
<input type="hidden" name="action" value="formBuilder/entries/saveFormEntry">
<input type="hidden" name="formredirect" data-redirect="{{form.successPageRedirect}}" value="{{form.redirectUrl}}">
<input type="hidden" name="formHandle" value="{{form.handle}}">

{% for tab in tabs %}
  {% set fields = tab.getFields() %}

  <fieldset class="{{loop.index}}">
    <legend>{{ tab.name }}</legend>
    {% for field in fields %}
      {% set input = craft.formBuilder.getInputHtml(field) %}
      {{ input | raw }}
    {% endfor %}
  </fieldset>
{% endfor %}

{# Error/Success Messages #}
{% if craft.session.hasFlash('error') or craft.session.hasFlash('success') %}
  {% if craft.session.hasFlash('error') %}

{{ craft.session.getFlash('error') | raw }}

{% endif %}
  {% if craft.session.hasFlash('success') %}

{{ craft.session.getFlash('success') | raw }}

{% endif %}
{% else %}

{% endif %}

<button type="submit">Submit Message</button>

</form>

{% endblock %}


texts:
Is there any way to output the actual source code from an SVG asset in Craft?

Rather than linking to it, I would like to embed the code in the page.

I tried a twig include, but I cannot include files outside the templates folder.

Thanks!


texts: How to modify and save a field in entry on EVENT_AFTER_SAVE in a plugin?

texts:
I'm trying to build my first little plugin.
I'm stuck with a problem: I need to modify the value of the specific field reference, right after the saving of the entry because the new value is supposed to be based on the same entry id.

This works to get the Entry object and modify the reference:

Event::on(
            Element::class,
            Element::EVENT_AFTER_SAVE,
            function(Event $event) {
                if ($event->sender instanceof Entry) {
                    $idLast = Entry::find('id')
                        ->section('annunci')
                        ->orderBy('elements.dateUpdated desc')
                        ->one();
                    $newRef = 'AV' . $idLast['id'];
                    // assign new reference ? At this point the record is already saved!!!
                    $event->sender->setFieldValue('reference', $newRef);
                    // then what?
                }
        });

I can  manage to retrieve the last saved entry, grab its id, and then create my $newRef, but after that, how am I supposed to resave the entry and update the entry record with the new value?

Second question: I would like to intercept the event only on the first save (aka on creation), and avoiding recalculating the field value on every successive saving. Is this possible?

Thanks in advance for any help, much appreciated!


texts: Smart Map - Static map displays fine, dynamic map does not

texts:
I enabled the three API's at Google:

Google Maps JavaScript API
Google Maps Geocoding API
Google Static Maps API

I get a static map OK. All I get with the dynamic map is a "Loading Map...".
My code:
{% for entry in craft.entries.section('groups').limit(5).find() %}

{{ entry.title }} , {{ entry.address }}, {{ craft.smartMap.map(entry.address) }}

{% endfor %}


texts: Why does asset creation not work for hidden images?

texts:
Im creating a gallery for Fancybox and only wish to show the first image. The rest are hidden in a container and only referenced so that Fancybox can call on these latter. I've tried two approaches: anchor tag with and without the image tag.

I am sure that this is a recent change as I have been using this technique on earlier craft versions and gettting good results.

The image is generated but it looks like in a temporary location "...cpresources/transforms..." to which Fancybox doesn't recognise.


texts:
I have a field in a site I'm creating which is weather and uses a TABLE field in order to enter the MONTH, TEMP, RAIN etc etc. Im using 2 locales within the site, EN and FR...

Initially I've setup the default values for the MONTH to include JANUARY > DECEMBER which is great, i don't really want the client to have to re-enter this information each time. But is it then possible to set the DEFAULT french values for this field too?

Cant see to find a way around this...

B.


texts: How can I retrieve older versions of a custom entry type in bulk?

texts:
I am building an API that returns instances of an entry type. Only authenticated users can access the API. There are different tiers of user - paid and free. Free users can access the API, but the content should only be updated weekly. I have a scheduled task that regularly updates my entries.

How can I query the database for a particular entry type, but only retrieve versions of entries that are at least 7 days old?


texts: Memory usage in sub tasks vs. regular tasks

texts:
I'm currently implementing a task-based application, which pulls some data from an external API before creating a number of entries based on the payload.

After creating the entries, the app will need to download a fair amount of images, storing the files as Assets and adding them to an Assets fields on one of the entries (each entry has a set of ~30 related images on an external server, that needs to be pulled).

Currently, I'm running 1 task per entry, with a sub task for downloading all of the images related to each entry (1 step per image, so ~30 steps per sub task). The images are quite large – around 5MB each.

The sub task takes an entry ID and an array of image URLs and metadata as its settings. Each step of the sub task looks like this:

The entry the image will be related to is pulled from the entry ID.
The task attempts to pull any existing Asset for the image (criteria based on filename)
If Asset not found, the remote image is downloaded using Guzzle to a temporary folder, before the Asset is created using craft()->assets->insertFileByLocalPath.
Another criteria to pull the newly created Asset.
Asset is updated with the metadata (which could've changed, regardless of whether the Asset was previously saved)
The IDs for any Assets in the entries Asset field is pulled using $entry->assetField->ids().
The new Asset's ID is added to the ID array, the asset field is updated with $entry->getContent()->setAttribute('assetField', $ids); and the entry is resaved through craft()->entries->saveEntry.
The temporary image file is deleted using the IOHelper class.

This is running on a 2GB droplet, where PHP/Craft has access to the full 2GB RAM – which I assumed should be plenty, though the server is running out of memory, intermittently. At one point, MySQL even crashed and had to be restarted :/

The memory issues never appear when Craft is running one of the regular, parent tasks – it always happens when one of the image sub tasks is running, which is why I'm debating my current setup.

From Brad Bell's comment to this answer, I know that 1 task = 1 request, even if that task has multiple steps and/or sub tasks. What I take from that is that having loads of sub tasks is potentially more dangerous in terms of memory usage and possible timeout issues, than having loads of smaller regular tasks. Is this a correct assumption?

In closing, which of the following approaches would be the safest, in terms of memory usage (and/or other issues I might not have considered):

One regular task per image (~30 tasks)
One regular task per image set (~30 steps)
One sub task per image (~30 sub tasks)
One sub task per image set (~30 steps, my current implementation)

I should mention that in this case, it doesn't really matter if the parent task completes before the image tasks run/complete, so I don't actually need to use sub tasks for the downloads.

Also, devMode is currently false on the server and I'm still having issues.


texts:
I am working on a product page where I want to give the option to the user to select between which sections they want to use eg banner section, description section, video section etc.

Now since the product pages might have some differences between them eg the description section on one product contains an extra image and an extra video I figured out that I can use a matrix field that contains a super table (plugin that allows matrix field within a matrix field) and another matrix field. By doing that I give the user the option to select the content they want to use within the sections.

Am I overcomplicating things here and is there a cleaner way of achieving the same logic?


texts:
As an affiliate I want one field where the links are stored, this link is saved as an entry. I've tried to call the template_from_string function but variables in the url are not overwritten. Is there another way to do this?
Thanks


texts: dynamic urls for channel/structure that's linked to the main structure

texts:
I'm trying to create dynamic urls for a channel or structure section that depend upon the url structure of a different structure (or the first entry in that structure). For example, if the main structure has "foo.com/news/" I want the 'news' channel entries to have urls of "foo.com/news/{slug}".

I came across this question/answer which seems like a great solution: Dynamically setting a channel's Entry URL Format with Craft tags  However, like mentioned it's not really dynamic as you need to go back and resave if the parent slug changes. I started doing this and it's turning into a disaster.

Has anyone found a way to do this completely dynamically? Would routing be the right way and how would it be done (I have not used routing)? Or backwards relational entries from the channel to main structure (which seems much less intuitive from CP UI perspective)?

...and if you don't have any ideas, HOW do you deal with urls when you have a 'pages' structure and linking from that to a channel? Based on extensive research, this seems to be the best way of blending structures and channels but my site is too large and complex to hard-code the url structures for the outlying channels/structures.

I don't have the rep to comment on the post above, hence the new question. Thanks much in advance!

****See my comment below gioppe's answer. I have decided against using this dynamic url approach, as explained in my comment.


texts: How to output entries related to a locale, IF a section is targeted to all locales?

texts:
The documentation doesn't say much about it, only How to access it.

What I'm trying to achieve here?

Display entries only related to a locale.

I'll present it you with an example.

There are 3 targeted locales enabled in 3 sections. 1 entry in each section, created by 3 local users. So math says, that one locale has 3 entries, where the whole example.com has 9 entries together.

So, When I try to index entries on selected section I get that:

example.com/section1/ -> all entries from all locales are outputted, because entries are targeted in all locales of a section.
example.com/locale1/section1/ -> the same situation as with example.com/section1/, except with two differences, that entries's URL has /locale1/section1/{slug} and the locale is matched with active one.

I've looked into database, and all entries published are linked with each locale, even when Local User1 published to Local1 only. If that is gonna work, I don't know, if that will have any impact on storage efficiency.


texts: How to retrieve a data from a custom table to JSON?

texts:
I'm trying to retrieve the data from the database and return it to JSON so that I can access the data in jquery...

thanks!


texts: Force an image transform to images inserted into Redactor

texts:
I know this essentially does the trick, however I was hoping I could apply a custom transform to all image assets if one hasn't been defined by the user.

The problem I have is trying to convey the importance of defining image transforms to my "less-than-savvi" clients.

So, as a fallback I'd like to know if I can query any images and apply an image transform. I feel like this might be a step in the right direction, but not sure what to do next:

{{ include(template_from_string(entry.body)|raw) }}

Cheers.


texts: Enforce password change every 90 days (3 months)

texts:
I am currently building an intranet for a client and one of their requirements is that staff must update their passwords every 90 days.

I assume I would need to build a plugin for this, but what would be best to way to approach this? I was hoping it might work whereby this was set 90 days after the last password change, rather than a fixed date for every user.

Thanks


texts: Craft 2 to Craft update - timeout when updating database

texts:
I am trying to update a site from Craft 2 to Craft 3. I first set up a new server, installed Craft 3, copied over config settings from the original site, and moved over a copy the original database. I have done this successfully on quite a few Craft 2 to 3 updates with no problem.
After pointing my browser to mysite/admin I got the prompt to finish up / update the database as expected, but the process timed out. The sql file I moved over is about 8mb, not especially large. In any case, is there any way I can run the database update process from the console in order to avoid the timeout issue?


texts: Why does asset uploading fail with the error "Uploaded file was empty"?

texts:
Recently I've noticed that file uploads through the Craft admin panel have started to fail with the response "Error uploading the file: Uploaded file was empty". This error occurs when trying to upload a file to the server or to S3.

At first, I was able to get around the issue by switching to a different browser or clearing the current browsers history and cookies. For some reason that would consistently alleviate the issue for any user who tried it, but as of last week this no longer appears to work.

So far I have tried:

Checking file permissions for the asset folder, they're set to 777
Increasing the php memory_limit, post_max_size, and upload_max_filesize
Uploading different file types and sizes looking for specific type or size that works, even a 20kb jpg fails.

Has anyone seen this before or have an idea where to look to fix the issue?


texts: Output SuperTable fields from inside Matrix field

texts:
Having looked at other answers I'm pretty sure I've got this correct but it's still not working for me.  I've stripped the code down to make it easier to read.

Error i'm getting is "Impossible to access an attribute ("packageName") on a string variable ("40")."  This error repeats for packageTitle, packageShortIntro etc if I delete the packageName line etc..

All other fields, 'block.body', 'block.subTitle' are coming through fine.

Also please note there is also a Table field within the SuperTable.

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

        {% case 'bodyText' %}
            {{ block.body }}

        {% case 'packages' %}
            <!-- Supertable -->
            {% for row in block.package %}
                {{ row.packageName }}
                {{ row.packageTitle }}
                {{ row.packageShortIntro }}

                {% for items in row.itemsAvailable %}
                    {{ items.item }}
                    {{ items.isAvailable }}
                {% endfor %}

                {{ row.packageCost }}
            {% endfor %}
            <!-- End Supertable -->

        {% case 'subTitle' %}
            {{ block.subTitle }}

    {% endswitch %}
{% endfor %}

Many thanks for looking and any advice you can offer.


texts: requireLogin not redirecting to login page

texts:
I'm trying to get the following behavior, but it's not working:

If a user goes to http://example.com/addresses he should get redirected to the Craft login form. So the corresponding template has a {% requireLogin %} tag. After a successful login the user should be redirected to the page he was trying to access (in the case http://example.com/addresses)

Without any additions to the config array the redirect goes to http://example.com/login which is a 404 page.

If I add the loginPath setting to the config file and set it to 'admin/login' it redirects to the correct Craft login form, but after login it's not going to /addresses but /admin/addresses

What settings would lead to the desired behavior?


texts: Is there a safer way to Cycle Through Post Data in Craft

texts:
Currently, I am doing this.

$responses = array(
        "E" => 0,
        "I" => 0);

foreach ($_POST as $key => $value) {
    if (strlen($value) == 1) {
        ++$responses[$value];
    }
}

Is there a way to use craft()->requests for this? I tried

foreach (craft()->request->getPost() as $key => $value) {
    if (strlen($value) == 1) {
        ++$responses[$value];
    }
}

But this did not seem to work.


texts: Limitation on number of users for Craft Calendar 2.x

texts: We are considering using Solspace Craft Calendar 2.x for our new start up users to use as a rostering tool. Is there any limitation on number of users we can subscribe to use Calendar 2.x? We are hoping to scale up within 12 months to have 1200-1500 users.


texts: Building a filtering system using both OR and AND relations

texts:
I'm trying to set up a filtering system similar to the one found on the product pages on asos.com. That system has different category groups of filters, where selecting multiple filters inside a particular category group widens the results list (OR / conjuction), whereas filters across category groups narrow the results list (AND / disjunction).

I'm trying to replicate this behaviour in Craft, but I'm struggling to combine AND and OR relations. I currently do the following to build up a list of filters across category groups from a comma separated query string in the form ?regions=22,33&teams=65&sectors=42,43,44:

{% set categoryGroups = ['regions', 'teams', 'sectors', 'topics'] %}
{% set relations = ['and'] %}
{% for group in categoryGroups %}
  {% set filterValueString = craft.request.getParam(group) %}
  {% if filterValueString != '' %}
    {% set filterValues = filterValueString|split(',') %}
    {% set relations = relations|merge(filterValues) %}
  {% endif %}
{% endfor %}

{% if relations | length > 1 %}
  {% set params = params | merge({ relatedTo: relations }) %}
{% endif %}

{% set results = craft.entries(params) %}

This results in a relations array which looks like ['and', 22, 33, 42, 43, 44, 65], and creates a system where adding a filter to an already filtered category group restricts the result set further, instead of widening it to encompass the new filter. I thought perhaps that I could construct relations to look like ['and', [22, 33], [42, 43, 44], 65], and the inner arrays (category groups) would default to an OR (as it would when passing a standard array of element IDs into relatedTo), with the outer relation providing the AND, but this doesn't appear to work.

Is there anyway to get the behaviour I'm looking for?


texts: Escaping rich text fields to json but keep html markup

texts:
I am trying to create an export from an old Craft2 site over to a new Craft3 site.

The structure and fields are all different, so I figured the easiest way was to create a json file from my entries and use FeedMe to import them back into Craft3.

Right now I'm having problems formatting the text so that it validates as json, but keeps the html markup so it looks nice again when imported to Craft3.

I have tried the following:

"bio": {{ person.mainContent }}",
"bio": {{ person.mainContent|escape }}" (with and without ('js'), ('html')
"bio": {{ person.mainContent|raw }}",
"bio": {{ person.mainContent|json_encode }}",

And a combination of these.

There seem to be some invisible newline or other character(s) preventing this from validating.

I have tried the |replace filter with "\n" and "\r" to " but it still fails.

The only times I have gotten the json to validate and get imported by FeedMe the HTML is encoded too, so it just shows up in the rich text editor.

Is there some easy fix I am missing, or do i have to create a gigantic replace function?


texts: Saving Custom Field Values to User Profile

texts:
I have a custom user field 'myuserfield'

How do I save a value to this field via a plugin in Craft3?

Here is my current attempt.

    $myvar = '12345';
    Craft::$app->getUser()->getIdentity()->setFieldValue('myuserfield', $myvar);
    $myid = Craft::$app->getUser()->getIdentity()->getFieldValue('myuserfield');

When I echo $myid it does, in fact, give me the new value ($myvar or 12345) but when I check the control panel the value is not saved.


texts:
Before I go into detail and share my error logs and plugin details, I'll ask the simple question first:

When testing my 404 page, no plugin functionality works. Is this intentional?

Just for testing purposes, I tried to include the index template file in my 404 template:

{% include 'index' %}

This pulls in the homepage fine, but still causes an error:

  Variable "pluginName" does not exist in "404"...

The following returns 'yes' when legitmately on the homepage, and 'no' when on a 404 page, which uses the include I just mentioned.

{{ pluginName is defined ? 'yes' : 'no'}}

Any insight would be great.

Mark


texts:
I'm trying to work out if the following is possible in Craft.

Assuming I have a single entry, I want to theoretically tag it as a 'blog' and 'about', both of which are sections
I want to then have that entry displayed within both the blog, and the about sections.

From what I can tell an entry is constrained to it's parent section. But is this possible using tags or something similar?

Ideally a craft2 answer, as the site is being developed in craft 2, with the plan to upgrade to craft3 in the summer.

Thanks!

Tim

UPDATE

I feel like I need to describe the problem more, with an example.

Say I have an entry called 'Meet the team', and two sections 'England' and 'U.S.A', the country sections act like normal structure sections - but the Staff Team entry is applicable to both sections.

Is it possible when displaying the England entries to display the Staff Team entry in addition to the USA entries to display the Staff Team entry?

The site in development is planning on having many of these types of pages - so a hard-coded solution to 'get' the post isn't possible.

Another way of describing it is the Wordpress way, of having 1 page in multiple categories, so each category shows that page.


texts: Any way to manually generate a transform on an asset source?

texts:
I imported all of the posts from a WordPress blog, using a regular expression to update the image URLs to their new location in a Craft Asset Source. However, many of the original photos are straight out of the camera - 2000x3000px or whatever. What I would like to do is use that same regex to update them to a transformed version: so /wp-content/uploads/2014/12/photo.jpg would become /media/blog/_fullWidth/photo.jpg. I already set up that replacement and it's working great.

The problem is that the "Full Width" transform hasn't been generated, and just calling the URL from a Rich Text field bypasses Craft, so it never gets generated. Short of manually re-adding every photo through Redactor with the transform, is there any way to force Craft to generate a particular transform on all the images in an asset source?


texts:
In a structure like the following:

Offices             US          Albuquerque
[offices]                       Boston
                                Chicago
                                Denver

                    Mexico      Acapulco
                                Buenavista
                                Chihuahua

                    Canada      Ajax
                                Brampton

writing this code on the offices overview page

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

{{ entry.title }}

{% endfor %}

gives me an output of everything in the whole structure

when writing:

{% for entry in craft.entries.section('offices').level(1) %}

{{ entry.title }}

{% endfor %}

I get the title from the entry in the first level.

But how do i target a specific entry in the structure?
Let's say only Albuquerque, Chicago & Chihuahua?

I looked around but can't seem to find anything in the docs about that. Who can point me in the right direction?


texts: Lookup row in matrix field by "Name" column?

texts:
If I have a matrix field with 2 fields "Name" and "Entry" is it possible to lookup the first row in that matrix field which has a specific "Name"?

Context: Twig template.


texts:
This is my code:

$giveaway = Craft::$app->globals->getSetByHandle('promotions');
$giveaway->giveawayName = "New Name";
$success = Craft::$app->globals->saveSet($giveaway);
return($success);

Controller returns true, but no changes have been made to the "promotions" global set. What have I missed?


texts: Redactor settings: stripping out classes from table

texts:
I have a site (Craft 2.5.2754) and am trying to add a class to a table within Redactor. Even if I disable Clean up HTML and Purify HTML (which would rather not do) the style is getting stripped out on save.

I've had a look through the config/settings for Redactor and there is an 'allowedAttr' setting for earlier versions but seems to have been removed in Redactor II.

Any suggestions on stopping the class being stripped out, preferably without having to disable Clean up HTML and/or Purify HTML?


texts: Error when calling an image transform from matrix field

texts:
I'm trying to call an image via an image transform from a matrix field.

So when I do this:

{% if block.type == "standardImage" %}
  {% set image = block.imageFile.first() %}
  {% if image %}

  {% endif %}
{% endif %}

I get this:

So you can see the width, height and title are all being called successfully, but the image is broken on the web page.

And when I skip the transform and just use {{ image.url() }} the image is called successfully with

Finally when I add this to the config file

'generateTransformsBeforePageLoad' => true,

I get a PHP error

Image “district.png” cannot be found.

I suspect then that the transformed image is unable to be created, but I don't know how to progress this idea, or if I am on the right track at all.


texts: Is it possible to move an entire asset source?

texts: S3 is seemingly costing us a lot. While it has its benefits, I think we could do with moving images from s3 to the server we are running the site from. How difficult/impossible of a task would that be?


texts: I am looking at Craft Commerce (https://craftcommerce.com/) and I am wondering if anyone has any experience using this in Craft 3? Seems like it is only for 2.x for now.  I am struggling to find any information on a Craft 3 release for Commerce.


texts:
my url looks like this:

domain.tld/slug-1/slug-2/variable

And in Twig it shall look for an entry with the slug slug-1 and show it, then an entry with the slug slug-2 and show it and look up for a global where the name of the global is variable.

How do I do this? I found:

{% set entry = craft.entries.section('section_handle').slug('my_slug') %}

But how do I tell Twig whats the first and whats the second slug?

There are always 2 slugs and one variable.

Thank you!


texts: Separate cache per user or user group in Blitz cache

texts:
We're using Blitz cache for a client website. Works fine.

Now we need to introduce variable content for different users (based on user groups)

Is it possible to have different cached versions per user or per user group?

For example, can we extend Blitz to alter the key (folder structure) under which a cached page is being saved?


texts:
I have a section where its entries have a matrix field (matrixField). In the first matrix block there is a date field (dateField). I want to get my entries ordered by that date field. Is this possible? Pseudocode:

{% for entry in craft.entries.section('dates').order(matrixField.first().dateField).limit(5) %}
    ...


texts:
I want to build a subnav with all entries from the current Section.

{% set pages = craft.entries.section(getCurrentSection).level(1) %}

I'm looking for the handle "getCurrentSection". I will use this for pages in 5 different sections, so I don't want to select the section by hand, like:

{% set pages = craft.entries.section('Section 1').level(1) %}
{% set pages = craft.entries.section('Section 2').level(1) %}
......


texts: Why isn't Craft displaying my plugin's changelog details?

texts:
I can't figure out why Craft won't display my plugin's changelog details as expandable version headers, like it does for other plugins. I assume there's something wrong with the formatting in my CHANGELOG.md file, but I can't spot it.

The below screenshot is how my CHANGELOG.md renders inside Craft's update utility – notice that the version headers aren't expandable, which means there's no way to actually read the details for each version update:

The raw CHANGELOG markdown can be found here: https://raw.githubusercontent.com/mmikkel/Retcon-Craft/master/CHANGELOG.md

The changelogUrl attribute in the plugin's composer.json file is correct.


texts: Plugin CKEditor outputs something with nothing?

texts:
I have a problem with the CkEditor for Craft CMS.
If I leave the textfield empty and save it, the output in the browser will still contain <p>&nbsp;</p> when I want it to be blank. I am thinking about to filtering out with javascript, but I hope someone has a better idea about what to do.


texts: Error when trying to test Craft Pro on .dev

texts:
I have a fresh Craft install set up locally at mysite.craft.dev. I would like to start building out the features offered by the pro license, but when I click the "Show me" link in the footer, I get "An unknown error occurred."

I am seeing this error in craft.log:
015/04/03 17:13:55 [error] [php] Cannot modify header information - headers already sent (/Users/aaron/Sites/mysite/craft/app/framework/web/CHttpRequest.php:1392)

In potentially related news, tasks do not seem to be behaving correctly.

Anyone ever experience this before? Any help is appreciated :)


texts: How to search for content in a specific Matrix field?

texts:
I'm not entirely sure how to search a specific Matrix field for a given bit of content. I can use:

{% for cta in entry.homeCtas.search('"Lorem Ipsum"') %}

{{ cta.ctaTitle }}

{% endfor %}

to find any Matrix rows with "Lorem Ipsum" (not in a specific field). But when I try something like this:

{% for cta in entry.homeCtas.search('ctaTitle:"Lorem Ipsum"') %}

{{ cta.ctaTitle }}

{% endfor %}

It returns nothing. Is my field syntax incorrect? Am I missing something obvious?


texts: Uploading user photo with content-type multipart/form-data

texts:
I'm using Vue + Axios to update user information. Everything is working well when the content-type header is set to application/json, but when a user tries to upload a profile image with the  multipart/form-data content-type header, I get an error saying "Username cannot be blank" and "Email cannot be blank".
I'm guessing that the necessary data for users/save-users is not passed when using the multipart/form-data header type, but how can this be solved?
Not working (I have temporarily disabled CSRF protection to be able to debug as far as possible. Also I have tried to add username and email as part of the json object, but to no avail. I guess they are not needed when passing the userId anyway):
const json = {
    userId: this.user.userId,
    photo: input.files[0].name
};
const config = {
    headers: {
    "Content-Type":
        "multipart/form-data; charset=utf-8; boundary=" +
        Math.random()
        .toString()
        .substr(2) +
        ";",
    },
};
axios
    .post("actions/users/save-user", json, config)
    .then((resp) => {
        if (resp.data.error) {
            reject(resp.data.error);
        }
    })
    .catch((err) => {});
}

Working code:
const json = {
    userId: this.user.userId,
    fields: {
        userCity: this.user.city,
        phone: this.user.phone,
    },
    CRAFT_CSRF_TOKEN: this.user.CRAFT_CSRF_TOKEN,
    headers: {
        responseType: "json",
        headers: {
        "Content-Type": "application/json",
        },
    },
};

const config = {
    responseType: "json",
    headers: {
        "Content-Type": "application/json",
    }
};
axios
    .post("actions/users/save-user", json, config)
    .then((resp) => {
        if (resp.data.error) {
        reject(resp.data.error);
        }
    })
    .catch((err) => {});
},


texts: How do you deploy Craft 3 on Heroku with Postgres?

texts:
I'm relatively new to Craft 3, and am able to run Craft locally with a Postgres db and Valet as my server. When I try to deploy to Heroku, I run into issues with (I think) Postgres.

Background

I tried setting up Craft to work with Heroku by following this guide (see the "Publishing" section near the bottom of the guide). I found that if I just run a heroku create and then push my local branch to the remote server, I get an "Internal Server Error" when loading the remote site on Heroku.

Instead, I created an app.json file as per this guide by @edenspiekermann. Then I run https://heroku.com/deploy with arguments to create the Heroku app, and this allows me to access the Craft admin page at /admin/install on the remote server.

Following the first guide, I also push my local Postgres database to Heroku with heroku pg:push DB_NAME DATABASE_URL --app HEROKU_APP_NAME.

Questions

-How does Heroku know the right DATABASE_URL to use in /config/db.php? Locally, that variables comes from .env which is not pushed to my repo or Heroku.

-Why does Heroku show an internal server error if I just push my local branch to the remote server (whereas creating a Heroku app with https://heroku.com/deploy works)?

My db.php file:

preg_match('|postgres://([a-z0-9]*):([a-z0-9]*)@([^:]*):([0-9]*)/(.*)|i', getenv('DATABASE_URL'), $matches);

$user = $matches[1];
$password = $matches[2];
$server = $matches[3];
$port = $matches[4];
$database = $matches[5];

return [
  'driver' => "pgsql",
  'server' => $server,
  'user' => $user,
  'password' => $password,
  'database' => $database,
  'schema' => getenv('DB_SCHEMA'),
  'tablePrefix' => getenv('DB_TABLE_PREFIX'),
  'port' => $port
];

My Procfile for Heroku:

web: vendor/bin/heroku-php-apache2 web/

My .env file:

# The environment Craft is currently running in ('dev', 'staging', 'production', etc.)
ENVIRONMENT="dev"

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

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

# The database server name or IP address (usually this is 'localhost' or '127.0.0.1')
DB_SERVER="localhost"

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

# The database password to connect with
DB_PASSWORD=""

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

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

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

# The port to connect to the database with. Will default to 5432 for PostgreSQL and 3306 for MySQL.
DB_PORT="5432"

DATABASE_URL="postgres://atc:@localhost:5432/blogdb"

DEFAULT_SITE_URL="https://landing-page.dev"

Error I receive when navigating to homepage on Heroku after I've pushed my local Postgres db to Heroku remote:

HTTP 503 – Service Unavailable – craft\web\ServiceUnavailableHttpException


texts:
I'm looking to use a Craft3 installation as a bridge app to synch a client's contacts from their CRM server to their Email Service Provider, via respective APIs.

I'll be storing their contacts as users in Craft. They have four contact lists with numbers (there may be some overlap) totaling:

12,000 contacts
55,000 contacts
23,000 contacts
22,000 contacts

Is storing these in Craft as users a realistic option? We'll be editing/adding new users in small batches on a daily basis, slicing them off the full list on the source side by last updated date, and then filtering records to push to the destination using the Craft API.


texts: Do assets have to be below public_html to access them in redactor?

texts:
I love that Redactor lets you choose existing entries, categories, and assets!

I am trying to set up a 'Files' source whose File System Path would be something like

/home/hostingaccount/craft/files

where index.php is at

/home/hostingaccount/public_html/index.php

But what source URL can point to that file location? It doesn't like http://mydomain.com/files. Or am I all wrong, and the assets have to be in something like this:

/home/hostingaccount/public_html/files


texts:
I'm using the following code on a category listing page to list the sub-categories that contain products:

{% set entryIds = craft.commerce.products.ids() %}
{% if category is defined %}
    {% set currentCategory = craft.request.getSegment(2) %}
    {% set categories = craft.categories.descendantOf(category).relatedTo({ sourceElement: entryIds }).groupId(1).order('title asc').find() %}
{% else %}
    {% set categories = craft.categories.relatedTo({ sourceElement: entryIds }).groupId(1).level(1).order('title asc').find() %}
{% endif %}

What I'm experiencing is that craft.commerce.products.ids() only returns the ids for products that have a Post Date in the current month. This is not ideal since some products might've been added months ago but still remain active on the site.

Is this normal behaviour for craft.commerce.products.ids() or is this a possible bug ? Any ideas on a workaround ?


texts: How can I retrieve all the related entries?

texts:
I have 3 entries. One of the entries got the entries field where Ive attached the two other entries. Im trying to display all the related entries whether entry 1, 2 or 3 is chosen.

For example:

Entry 1: Has the entries field. When this entry is selected, I need to show entry 2 and 3
Entry 2:  When this entry is selected I need to show entry 1 and 3
Entry 3:  When this entry is selected I need to show entry 1 and 2

Is this possible?


texts: Error uploading images on admin panel ( Failed to load resource: net::ERR_EMPTY_RESPONSE )

texts:
I have a problem uploading images on the CP. Small images success, but one with a 2Mb site fails with the error below.

File was renamed to only ASCII chars, but problem still occures.

PHP settings:

memory_limit    128M
upload_max_filesize 64M

Craft version: 2.6.2791


texts: Add an assets field to a field type plugin template

texts:
I have a plugin that creates custom field types to extend crafts default field types.

The custom field types hold several different form input fields. For example the field may be called video and contain a title field, caption field, video slug field and a thumbnail field.

When the plugin is installed these fields appear in the default field dropdown list.

I now want to change the html template in the plugin so that the thumbnail field makes use of the default assets field built into craft. So I'd like to know if there is a way to add an asset field to the twig template in my plugin. The plugin does not need to use it's own database so can make use of the existing assets database.

Is this possible?

This is what I have so far.

In the fieldtype class:

public function getInputHtml($name, $value)
{
    // If value is null, we set it to an array to prevent template errors
    if(!$value)
    {
      $value = array();
    }
    return craft()->templates->render('customfieldtypes/video', array(
        'name'  => $name,
        'value' => $value
    ));
}
public function prepValueFromPost($value)
{
    return json_encode($value);
}

public function prepValue($value)
{
    return json_decode($value, TRUE);
}

In the video template:

Title
<input class="text nicetext fullwidth" type="text" name="{{ name }}[title]" value="{% if value %}{{ value.title }}{% else %}{{ null }}{% endif %}">

Description
<textarea class="text nicetext fullwidth" type="text" name="{{ name }}[description]">{% if value %}{{ value.description }}{% else %}{{ null }}{% endif %}</textarea>

Caption
<input class="text nicetext fullwidth" type="text" name="{{ name }}[caption]" value="{% if value %}{{ value.caption }}{% else %}{{ null }}{% endif %}">

Link
<input class="text nicetext fullwidth" type="text" name="{{ name }}[link]" value="{% if value %}{{ value.link }}{% else %}{{ null }}{% endif %}">

Thumb
<input class="text nicetext fullwidth" type="text" name="{{ name }}[thumb]" value="{% if value %}{{ value.thumb }}{% else %}{{ null }}{% endif %}">


texts:
Recently moved site to a new server.

Attempting to edit a post created before migration fails. The edit page reloads with the changes removed. Note: 1) this happens for only SOME, but not ALL of entries in the same channel. 2) the entries that fail and those that succeed are set to use the same templates.

Utilities - Logs shows this error message:

Level     error

Category  exception.Craft\HttpException.404

Message   Craft\HttpException in
  /home/method/craft/app/controllers/TemplatesController.php:72


texts: Adding more data to the "commerce/cart/update-cart" action

texts:
Is it possible to add additional data to the "commerce/cart/update-cart" callback? For instance, we want to include an Asset field so we can populate a cart modal with the item's image in one call?

Or is there a better way to tackle this type of functionality?


texts:
Good morning, If have have a URL that passes parameters: http://url?month=January&Year=2018, how would I go about querying all entries in section where the postDate equals January 2018?

I can get the parameters by using: craft.app.request.getParam('month') and craft.app.request.getParam('year') but I can seem to figure out the correct way to only show me entries based on these parameters.

Thanks in advance.

I noticed a post that had the following answer and the response was that it worked. I tried it, and received the error:
Object of class DateTime could not be converted to string.

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

{% set firstDayOfMonth = now | date_modify('first day of ' ~ month ~ ' ' ~ year ~ ' 00:00:00') %}
{% set lastDayOfMonth = now | date_modify('last day of ' ~ month ~ ' ' ~ year ~ ' 23:59:59') %}

{% set entries = craft.entries.section('yourSection').postDate('and', '>= ' ~ firstDayOfMonth, '<= ' ~ lastDayOfMonth) %}


texts: Authorize.net not connecting in Craft Commerce?

texts:
I'm very lost with the gateway. It seems that Authorize.net is highly supported with Craft Commerce but the gateway isn't working. I had the dummy gateway working perfectly fine so that when I'd go through the whole processes and the order would show up. I put in authorize.net AIM as a new gateway and now when I get to the payment it does nothing at all. I put in this code

{% if craft.config.devMode and (craft.session.hasFlash('notice') or craft.session.hasFlash('error')) %}

  {% set noticeFlash = craft.session.getFlash('notice')|join('|') %}
  {% set errorFlash = craft.session.getFlash('error')|join('|') %}

    Notice: [{{  noticeFlash }}]
    Error: [{{  errorFlash }}]

 {% endif %}

and I get back

  Error: [Payment method does not exist or is not allowed.]

I've put in the API user and key and the link at the bottom. Am I supposed to set the gateway as default somewhere?


texts: How do I update the content of a field type in the onAfterElementSave() method?

texts:
I am building a field type for Craft that needs to do additional processing to the saved data once the element id is available. For this reason, the prepValueFromPost() method won't work, since the element id isn't available yet.

So how to update the content of the current element from the onAfterElementSave() method?


texts:
I've been looking for an event that get triggered when an entry is moved from a disabled to enabled status.

Currently I'm trying to find it through the EVENT_AFTER_SAVE_ELEMENT event but I have no idea what the previous status of the entry was so I can't tell if it was just updated:

current

Event::on(
    Elements::class,
    Elements::EVENT_AFTER_SAVE_ELEMENT,
    function(Event $event)
    {
        $element = $event->element;

        // Get the status, but I don't know the previous status.
        $status = $element->status;
    }
);

I also had this pointed out to me https://docs.craftcms.com/api/v3/craft-events-setstatusevent.html but I don't know what emits this event as a parameter.


texts: Empty matrix object after checking for a block type

texts:
Not sure if this is a bug or my logic is off. I'm trying to add caching logic to templates to not cache certain pages if they have a block type form present because of the dynamic CSRF tokens.

The logic:

{% set doNotCache = entry.mainBody.type('form').all()|length or craft.retour.getHttpStatus != 200 ? true : false %}

If the page returns true, the page renders properly. If the logic returns false the entry.mainBody object is empty (ie. doesn't render the matrix content). If I remove the logic all together the pages render properly.


texts:
How do you save Widget Settings?

I read this tutorial https://craftcms.com/docs/plugins/widgets several times but I could not find an answer. I'm new to Craft and this is my first plugin.

If I want to save plugin settings I create a Twig template like this

<form method="post" action="" accept-charset="UTF-8">
        <input type="hidden" name="action" value="sRGoogleAnalytics/settings/saveSettings">
        <input type="hidden" name="redirect" value="srgoogleanalytics/settings">
        <input class="btn submit" type="submit" value="{{ 'Submit'|t }}">
</form>

and know my function public function actionSaveSettings() in my SRGoogleAnalytics_SettingsController is going to be executed but I don't know how to do the same for widget settings since the widget itself already has a "submit" button and when I create a form in the template there will be two submits.

Could you please explain what I have to do exactly in order to get a callback into a specific function?

Thank you very much


texts:
Why does this work fine

{% paginate craft.entries().limit(7).section('events').eventStartDate('>= ' ~ 2014 ~ '-' ~ 09) as entriesOnPage %}

But this does not

{% paginate craft.entries().limit(7).section('events').eventStartDate('>= ' ~ 2014 ~ '-' ~ 09) as entriesOnPage %}

I get this http://d.pr/i/NRvg

I also get errors when simply using '<' so it seems to require only either a less than or equal to or a greater than or equal to operator.

Can someone point to some kind of documentation for what is allowed within the custom field filter -------------> this part ('<= ' ~ 2014 ~ '-' ~ 09)


texts: How can I render a page template from a queue job/console controller?

texts:
I'm trying to call craft\web\View::renderPageTemplate from within a console controller (also tried from a queue job), but running into all kinds of trouble:

E.g.

Exception 'Twig_Error_Runtime' with message 'An exception has been thrown during the rendering of a template ("Session does not exist in a console request.").'

I discovered the this was due to registerAssetFlashes: https://github.com/craftcms/cms/blob/279116ba4091edc67c92fcbbefc257bb4fe30335/src/web/View.php#L1418

No plugins that register twig functions/filters work

Currently I'm doing:

$view = Craft::$app->getView();
$view->setTemplateMode($view::TEMPLATE_MODE_SITE);
$view->renderPageTemplate($template, $variables);

The end goal is to render a template, cache it, and send the html to a web service.

How can I do this without everything breaking?

…Or is there another way to do this, or should this be a feature request?


texts: $order->dateOrdered returns a string value the first time and DateTime after that. [Order got through event]

texts:
I am using the Commerce 2 plugin and I am experiencing a very odd issue. Once an order is complete I want to use the dateOrdered property to create a csv which I send through a request endpoint. That worked fine.

BUT! Since recently (somewhere this month), on the first attempt to create and save the .csv, when calling $order->dateOrdered->getTimestamp() I get dateOrdered as a string.

On the second attempt to create and save the .csv I get dateOrdered as a DateTime.

The method which I am calling is the same so I think it has something to do wiht order statuses.

I tried to trace the problem in Commerce's Order.php class but I still have no clue why this occurs or what I am doing wrong.

Any help is more than welcome. Thank you in advance!


texts: How Customizable is the Craft Admin Interface?

texts:
Could a tool like AngularJS or VueJS or React help in significantly customizing the Craft admin interface? Could it help add additional functionalities?

For instance, let's take the example of adding external links to a post. Vox Media's Chorus lets writers save links in a browser bookmarklet (during their research process), and then pop it on the sidebar in their CMS admin interface when the writer clicks on the bookmarklet. The writer could now just select a phrase in his copy, and then click on a link in the sidebar and have it added to the text automatically. No selecting the text and then clicking on Add link and then copy-pasting the link. Lot of steps reduced.

The above cannot be done on Craft by default and in my research I haven't found a plugin that enables such a functionality.

Could the admin interface in Craft be altered to include such functions that aid in speeding up the editorial workflow?


texts: Solspace Freeform plugin: AJAX without jQuery – how?

texts:
I am trying to post data using AJAX.

The docs describes a method here. But that is mainly for jQuery.

I have also looked at this url, which also uses jQuery.

But from what I understand, the "action" parameter in <input type="hidden" name="action" value="freeform/api/form">is where the data is sent. But if I send data to that URL, I get a 404.

How do I properly submit a form using AJAX?


texts:
As per the title, I have disabled a plugin in admin and now the admin is not accessible.  It returns an Internal Server Error.

Any help would be appreciated


texts:
Hi I know my way around CraftCMS and twig a little bit but totally new to the CraftCMS Commerce plugin. I have installed the Commerce plugin and I have added the default templates to get me started. There are a number of example products in a "Clothing" category which I assume the Commerce plugin added during installation.
When I click the "View" button from the edit page of one of those products I expect to see that product in the front end of the website using the example _product.twig template but instead just get the "New Website!" example news item. I don't know how to fix this. I deleted the news item to see what the product would link to instead but all I get now is the Home page.
I can see the product if I click "Preview" in the product editor and see it in split screen.
The URL seems to be correct such as: mywebsite.com/shop/products/ant-001
Can anyone tell me what schoolboy error I'm making?
Thanks in advance.


texts: Width, length and dynamic pricing - Commerce

texts:
We've built quite a few sites in Craft CMS and have been waiting for a project to get stuck into Craft Commerce - that time is here! BUT, one thing - it's for a carpet company so allowing the user to add a width and length of carpet is critical.

After reading many similar questions, I see that everyone's pointing to creating variants for each option. This isn't practical for this case as they have many types of widths let alone being able to type in a length. Plus, they get new stock quite often.

They're currently using WooCommerce and we really don't want to go back to Magento so it'll be a shame if we couldn't use Craft Commerce.

So here are my questions - has anybody released a plugin that can do the above? If not, is a plugin the way to go for this? Finally, are there any plans to add this functionality into Craft Commerce?


texts:
Is it possible to check for a value in a supertable field during the for loop:

{% for item in craft.products.supertable.lightswitch(1).all() %}
  {# stuff #}
{% endfor %}

This returns

  Impossible to invoke a method ("lightswitch") on a null variable.

So I guess the content of the supertable field is not available yet?
Because if I write:

{% for item in craft.products.all() %}
  {% if item.supertable.lightswitch == 1 %}
    {# stuff #}
  {% endif %}
{% endfor %}

This works nicely. Is this not a part of the element criteria model?


texts:
One of the shipping companies that my client will use works by distance.
This company offers an api where you tell the pickup address and the shipping address. You also specify what type of package to carry (small or medium).
When I have a complete address, I make the call to the API of this company and it returns the shipping cost to me.
Given the particularity of this shipping company, I would like to be able to specify the price of the shipping cost without depending on any shipping method of the system itself. Is this possible?
thanks in advanced


texts: Uploaded Assets always get 600 File Permission and are therefore not displayed (403 Error)

texts:
After a fresh manual Craft CMS install everything runs fine, except uploading Assets. Well, the uploading part works fine but uploaded assets always just get file permissions of 600 (adfrw) Group and User are set correctly. Tried it with a fresh install at 2 different hosts still they always get the same permissions.
Does anyone have any idea of what's the problem?


texts: Can plugins add functions to AssetFileModel?

texts:
I am currently working on a Craft CMS plugin, which adds functionality on top of assets, that should be callable in templates. I have come up with a Twig Extension that allows templates to call it like this:

{{ image | myCustomMethod }}

However, I would like to provide the method directly on the image itself instead (because it is more readable/intuitive and makes sure image is included in the craft element cache):

{{ image.myCustomMethod() }}

Is it possible for a plugin to extend the AssetFileModel class to do that? If so, how?


texts: Sorting categories by the post date of the entries related to them

texts:
I need to sort my categories based on the date of entries returned within the category. I am trying to sort sermons from a church by the series they were contained within. I have the sermons grouped by their series and outputting correctly on that front but they display in order based on the category creation date.

I need the sermon series to show in chronological descending order.

So we have Sermon Series A, Sermon Series B, Sermon Series C... within each one of those categories we have individual sermons related to the category. For example:

Sermon Series B

Sermon 1 (1/10/2013)
Sermon 2 (1/17/2013)

Sermon Series C

Sermon 1 (9/10/2014)
Sermon 2 (9/17/2014)

Sermon Series A

Sermon 1 (5/10/2014)
Sermon 2 (5/17/2014)

Currently my output looks very similar to the above example but what I need is for it to show like this:

Sermon Series C

Sermon 1 (9/10/2014)
Sermon 2 (9/17/2014)

Sermon Series A

Sermon 1 (5/10/2014)
Sermon 2 (5/17/2014)

Sermon Series B

Sermon 1 (1/10/2013)
Sermon 2 (1/17/2013)

Since the entries contained within the categories are in that order by post date.

Here is my current Twig code:

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

{% for category in craft.categories.group('sermonSeries').relatedTo(entries).order('dateCreated desc') %}

  {% for entry in entries.relatedTo(category) %}

But as I stated above this doesn't output my content with the desired effect.


texts:
So I'm trying to get my Matrix as JSON with the Craft CMS Element API plugin.

<?php

use Craft\elements\Entry;

return [
    'endpoints' => [
        'api/sites' => [
            'elementType' => craft\elements\Entry::class,
            'criteria' => ['section' => 'sites'],
            'elementsPerPage' => 1,
            'transformer' => function(Entry $entry) {
                $matrixBlocks =[];
                foreach ($entry->contentMatrix as $block) {
                    switch ($block->type->handle) {
                        case 'sectionTitleBlock':
                            $matrixBlocks[] = [
                                'content' => $block->sectionTitleBlock
                            ];
                            break;
                    }
                }
                return [
                    'matrix' => $matrixBlocks,
                ];
            },
            'paginate' => false,
            'pretty' => true,
        ],
    ]
];

The error message im getting is

  "error": {
      "code": 2,
      "message": "Invalid argument supplied for foreach()"
    }

I think the problem is that $entry->contentMatrix is giving me a MatrixBlockQuery Element.

$sectionTitleBlock is a normal text field


texts: How do I get a list of craft provided events at runtime?

texts:
The documentation provides a very comprehensive list of events provided by Craft  but I would like to know if there is a way to get a list of those events at runtime.

Having such list would enable me to display a <select> field whereby a user could choose the event that should trigger an action.

Think of it as dynamic event registration!


texts:
In the general.php config file, I can target settings for multi-environments like so:

return array(
  '*' => array(
    'devMode' => false
  ),

  '.loc' => array(
    'devMode' => true
  )
);

Is it possible to do something similar in the routes.php file too?

return array(
  '*' => array(
    'test' => 'index'
  ),

  '.loc' => array(
    'test' => '_test/index'
  )
);

I don't want to differentiate the locales, but the environment instead. I know it's possible to query how content gets included within the templates themselves. I just wondered if this is possible instead... I don't actually have a use-case example.

Maybe a time will arise where I want to allow certain content to be accessible for 'staging.' domains only.

Thanks,

Mark