texts: For loop through custom field in JavaScript

texts:
I'm using a script to animate four sets of numbers on a page.  I would like the numbers to be editable from within the admin (a SuperTable field).

Currently I have this:

   {% for stats in entry.statsPanels %}

0{{ stats.statDescription }}

   {% endfor %}

Which is working fine for looping through and pulling back the 'Stat Descriptions'.

Somehow I also need to loop through the 'Stats Number' column and embed this into the JavaScript that animates the numbers...  at the moment they're hard coded '400, 60, 1800, 40'.

     $(document).ready(function(){
      function numberWithCommas(n) {
       var parts=n.toString().split(".");
       return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      }

      var endingCounterVar = [400, 60, 1800, 40];

      for (let i = 0; i <= 3; i++) {

      let counter = { var: 0 };
      let tal = document.getElementById("tal-"+i);

      TweenMax.to(counter, 5, {
       var: endingCounterVar[i],
       onUpdate: function () {
        let nwc = numberWithCommas(counter.var);
        tal.innerHTML = nwc;
       },
       ease:Circ.easeOut
     });
    }
   });

Any help is very much appreciated.

Thank you

Martin


texts: What’s the recommended way to set the site URL?

texts: There are multiple ways to set the site URL. What is the recommended way?


texts: Redactor plugin for Bootstrap Responsive Image

texts:
Doing a quick redactor plugin to added a class to images after upload. Based on the docs, imageUpload should be the callback used.

The plugin loads, but am I doing this wrong:

if (!RedactorPlugins) var RedactorPlugins = {};

RedactorPlugins.responsiveimage = function () {
  return {
    init: function()
    {
      var that = this;
      console.log("loaded");
    },
    imageUpload: function(image, json){
      console.log(image);
      image.addClass("img-responsive");
    }
  };
};


texts: Limit the for loop returns with an if statement

texts:
I've got a for loop working perfect with a limit of 5. Then I throw in the if statement to filter those entries that correspond with a global variable I have set. The problem is the if statement is after the for loop with the limit and only doing it's thing to the 5 entries and not all of the entries.\

I want to use the if statement on all the entries to return the ones I want, then limit it to 5. In another DIV I have and offset(5), so the rest go there. I hope that makes sense.

{% for entry in craft.entries.section('news').order('articleOrder desc').limit(5).find() %}

    {% if entry.currentYear2 == currentEdition.currentYear2 and currentEdition.currentMonth2 in entry.currentMonth2 %}

{{ entry.title }}

{{ entry.body }}

    {% endif %}

{% endfor %}


texts: 500 Error after Dreamhost server upgrade

texts:
Dreamhost upgraded my VPS overnight and I immediately got a 500 error. The site currently works on another Dreamhost VPS (the original below) and an Arcustech server.
After checking the error logs I'm receiving this error:
AH01215: php73.cgi: unable to extent pixel cache `No such file or directory' @ fatal/cache.c/CacheSignalHandler/3626.: /dh/cgi-system/php73.cgi

The server was upgraded from:
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty

to:
Distributor ID: Debian
Description:    Debian GNU/Linux 9.12 (stretch)
Release:    9.12
Codename:   stretch

I've done the following to try to resolve it

Deleted composer.lock & vendor/ and reinstalled everything.
Started a fresh directory and change the site to run out of that directory
restarted the MySql VPS, and VPS
Deleted mysqlVPS and VPS, the ordered a fresh build of both, reinstalling node, composer, etc.and rebuilding the site there

Dreamhost was ...uh...less than helpful on the matter.
Has anyone ever seen this problem?


texts:
I have a page on one of my sites which requires entries to show even if the entry is disabled, but just greyed out. Is there a way I can disable an entry and make it still show up on my webpage?

I have tried using {% if not entry.enabled %} but it doesn't show up either way. Also I'd rather it showed up in the order its laid out in the admin, not before or after.

The field I am trying to display is an entries field which is taking data from another Structure and is disabled in that Structure, not the one which it is being called into.

Anyway of doing so?


texts:
I'm trying to programmatically set group permissions. I came across the method saveGroupPermissions(). According to the documentation all you have to do is pass in the group ID and then an array of the permissions you want to apply. Great, seems simple enough. So I attempted the following:

craft()->userPermissions->saveGroupPermissions($group->id, array("accesssitewhensystemisoff"));

The string accesssitewhensystemisoff is a built-in Craft permission, I'm not attempting to set my own custom permission... Not even sure if that's possible but we'll save that discussion for later.

Anyway this is not working and I have no idea why. There are literally zero examples of how to properly do this so I'm wondering if anyone else has solved this problem?

On a related note does anyone know if it's possible to set a group permission that gives access to a plugin? Or do I need to whip up my own plugin to handle that?

Thanks!


texts:
I recently purchased the Digital Download plugin for Craft.

I'm wanting to secure a PDF download generated by another plugin called Enupal Snapshot. Reviewing the Digital Download documentation I'm not entirely sure how I would do that using the following code which generates the PDF on the fly?

Update 1

Advice has been given that we need to provide the file path. In order to get the file path in Enupal Snapshot you need to return the asset model of the PDF.

Update 2

The code was changed to reflect asset model requirment. Unfortunatly I get a "Impossible to invoke a method ("getPath") on a string variable" highlighting {% set filePath = assetModel.getPath() %} in the code.

Code

{% set pdfName = 'now'|date('Y-m-d') ~ '-' ~ date().timestamp ~ '-evaluation-' ~ companyName ~ '-' ~ firstName ~ '-' ~ lastName ~ '-' ~ submissionId ~ random(50, 500) ~ '.pdf' %}

{% set assetFolderRef = evaluationSettings.evaluationAssetRef %}
{%
    set settings = {
        filename: pdfName,
        inline: false,
        overrideFile: true,
        asModel: true,
        singleUploadLocationSource: assetFolderRef,
        cliOptions: {
            'header-html': 'evaluation-tools/evaluation/pdf-header',
            'footer-html': 'evaluation-tools/evaluation/pdf-footer',
            'orientation': 'Portrait',
            'page-size': 'A4',
            'title': 'Evaluation for ' ~ companyName,
        },
        variables: {
            passSubmissionId: submissionId,
        }
    }
%}

{% set assetModel = craft.enupalsnapshot.displayTemplate("evaluation-tools/evaluation/pdf-report", settings) %}
{% set token = craft.digitalDownload.createToken(assetModel, options) %}

     Download Report


texts:
Similar to this question: Output URL to section

Let's say we have a section with handle 'places' which defines its URL format as 'places/{slug}'—how do I get the link to the 'places' index page? The question above goes via the entries in that section but that just gets the url of the first entry in that section.


texts: Get full url of asset, not just the path

texts:
I'm trying to output the full asset URL. Using Craft 3.0.0-RC7.1

In .env:

ASSETS_BASE_PATH=/Users/user/code/sitename/web
ASSETS_BASE_URL=http://sitename.test

In config/volumes.php:

'siteAssets' => [
    'path' => getenv('ASSETS_BASE_PATH') . '/assets/images',
    'url' => getenv('ASSETS_BASE_URL') . '/assets/images',
],

In my template:

<meta property="og:image" content="
{{ entry.socialSharingImage.one.getUrl('socialSharing') }}
" />

Output:

<meta property="og:image" content="
/index.php?p=actions/assets/generate-transform&amp;transformId=58">

As you see, no site url at the start. Any ideas?

It seems the getUrl() method returns the path. Prepending it with {{ siteURL }} creates two /'s e.g. http://sitename.test//asseturl.jpg. Same results in dev and production.

Thanks!


texts: Issues with Twig template includes when rendering from a service called from a CP-triggered event

texts:
I have a listener for the entries.saveEntryevent that is calling a service, which generates an email from a rendered template. The template is attempting to import macros.

MyaddonPlugin.php::init()

craft()->on('entries.saveEntry', function(Event $event) {
    if ($event->params['isNewEntry']) {
        craft()->myaddon_emails->generateEmail($event->params['entry']);
    }
});

Myaddon_EmailsService.php::generateEmail()

$emailHtml = craft()->templates->render('myaddon/email');

plugins/myaddon/templates/email.twig

{% import '_macros/mymacro' as mymacro % }

When I attempt to run this I get this error:

Unable to find the template “_macros/mymacro”.

When running the same service/render code from a Controller, everything works. It seems like there is a difference with how paths are set or handled in a Controller vs. an event handler. I tried manually setting the template path based on this page, but same results.

Any thoughts on how to resolve this?

Thanks in advance!


texts: How to upload several images & automatically create an entry for each one?

texts: I have more than 1000 images that I want to upload on Craft. Is there any way to bulk upload all the images and automatically create one entry for each one of them? Including their fields, like categories and tags?


texts: Front end asset uploads not correctly rotated

texts:
Running into an issue whereby front end asset uploads are not the correct orientation. I've spotted this mostly with user profile pics.

What's the best way to start debugging this?

My server has ImageMagick extension installed. I believe it's happening when a photo is being directly uploaded from a phone/mobile device. (The one time I managed to recreate it was a direct upload of an untouched photo from my iPhone.)

Any help appreciated. Thanks.


texts:
I'm building a custom registration process in which a set of entries and a user are created at the same time.

Currently I'm not able to pass back my errors in my controller into the front-end template.

(The following code should error out on purpose to test this functionality)

In my plugin controller:

$user = new UserModel;
$wasSaved = craft()->users->saveUser($user);

if ($wasSaved) {
     $was_assigned = craft()->userGroups->assignUserToGroups($user->id, array(1));
} else {
     $user->addErrors($user->getErrors());
     var_export($user->getErrors());
     return false;
}

In my template

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

     {% for error in errors %}

{{ error }}

      {% endfor %}

{% endif %}
{% endmacro %}

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

With the var_export($user->getErrors()); in my controller, I can see the errors at the top of the page:

array ( 'username' => array ( 0 => 'Username cannot be blank.', 1 => 'Username cannot be blank.', ),
'email' => array ( 0 => 'Email cannot be blank.', 1 => 'Email cannot be blank.', ), )

but these errors are not making it back into the actual template.

Any ideas?


texts:
Can the backend entry form be adjusted by a template. It's not a very compressed view.
See this image

It would look a lot better if I can add some float:left; to parts.
See this image


texts: Custom module controller getView()->renderTemplate() path not working

texts:
Module loads and controller actions work. Craft 3.3.7.

I'm trying to find out what is the path to use to render the view.

From the Doc:

return $this->renderTemplate('plugin-handle/path/to/template', $variables);

https://docs.craftcms.com/v3/extend/updating-plugins.html#rendering-templates

What I have and doesn't work:

return Craft::$app->getView()->renderTemplate('subscribing-module/src/views/default/index',['mypost' => $request]);

Returned error for above: Unable to find the template “subscribing-module/src/views/default/index”.

Here is the direct path from the root of the website:
modules/subscribingmodule/src/views/default/index.php

Bootstrap in config/app.php:

'bootstrap' => ['subscribing-module'],


texts:
I'm using Solspace Calendar for events, I also have a standard channel for reviews. What I need is the ability to connect the review with the event.

Solspace offers "Calendar Events" custom type field to do that, however, when I use it and attach an event to it this code:

{% set reviews = craft.entries.section('reviews').relatedTo(event) %}
{% if reviews|length %}
   {% for review in reviews %}

{{review.title}}

{{review.description|nl2br}}

   {% endfor %}
{% else %}

There are no reviews yet

{% endif %}

isn't working, and I have the same code working for a standard entry. How do I use relatedTo on custom fields?

This works on a different page with entry present

{% set reviews = craft.entries.section('reviews').relatedTo(entry) %}

This doens't work when event present

{% set reviews = craft.entries.section('reviews').relatedTo(event) %}

I've made sure that:

the event is fetched, and I'm successfully accessing it via code above
there are indeed reviews with this event attached


texts: Add Salesforce Lead record with file attachment

texts: Can anyone know if it is possible to upload a file to the SalesForce service using the Freeform, Express form or another plugin...? (i.e. need to add Lead record with file attachment) Thanks


texts: Dynamic email notifications based on submitted form values in Solspace Freeform

texts:
Let’s say my form contains a <select> element named inquery_type with the following options:

General Inquiry
Reservations
Other

And let's say that I want to automatically send an email notification only if the form is submitted with an inquiry_type value of Reservations.

Is this possible. And if so, how would I handle this?


texts:
I'm trying to get all Entries that are from a specific Entry Type.

My Section is "Site".
Which has 3 different Entry Types.

Now I want to get all Entries from the Entry Type "Program".

I'm trying to reach my goal with Craft::$app->sections-> or Craft::$app->elements->


texts: Return entries where field is "not empty"

texts:
I'm trying to return entries where a specific field named "productSale" is not empty. Unfortunately, my code attempts keep throwing the "Expected name or number" error.

Code attempts include:

{% set products = craft.entries.section('product').productSale.(':notempty:').find() %}
{% set products = craft.entries.section('product').productSale.('not null').find() %}
{% set products = craft.entries.section('product').productSale.('is not null').find() %}
{% set products = craft.entries.section('product').productSale.('not empty').find() %}

Three questions then:

What is the "Expected name or number" error saying exactly?
Where in the available docs (Craft or Twig) would I look for explanation on this? I didn't find much in my first pass.
How do I return entries where a specific field is "not empty"


texts: Can I set a JS variable to a Twig output tag?

texts:
This came out of a previous question

I need to set a variable of a tag group that I can reference in jquery for use with a plugin.

I'm declaring this variable in a  tag so my included js files can access it.

Here's what I want to do:

<script type="text/javascript">
    var gameTags = {{ craft.tags.group('gameTags') }};
</script>

Javascript clearly doesn't like that syntax, so I tried setting the variable with Twig and calling that:

{% set gameTags = craft.tags.group('gameTags') %}

<script type="text/javascript">
   var gameTags = gameTags;
</script>

JS considered that undefined.

I'm probably going about this the wrong way. I'm relatively new to javascript and very new to craft, so I'm a little stumped.


texts:
I have some matrix fields containing a date. I then loop through the entries in a category looking for entries containing a matrix field with a date during the next month. Everytime a matrix field is found, the entry id is added to an array of entries. Like so:

{% for event in craft.entries.section('events').type('eventWithMultipleDays').relatedTo(category).find() %}
    {% for date in event.dates if date.multiDate >= now | date("Y-m-d") and date.multiDate <= now | date_modify('+1 month') %}
        {# ADD THE FILTERED EVENT TO THE CATEGORYSEVENTS ARRAY #}
        {# NOTE SQUARE BRACKETS CREATE AN ARRAY - NECESSARY FOR THE MERGE #}
        {% set categoryEvents = categoryEvents | merge([event]) %}
    {% endfor %}
{% endfor %}

Not surprisingly, some entries contain several matrix blocks with dates falling within the next month, which means the array is containing duplicate entries. That means when I output the entries array, I'm getting repetition, using this, as you'd expect:

{% for event in categoryEvents %}
    {# details output #}
{% endfor %}

Is there a way to only get unique values out of this array? Or, if not, a better way to create the array perhaps?

Thanks,
Clive


texts:
When I add a new user in the admin area, they get a link to activate their account. On the screen that link goes to, they are prompted to set a password. After the password is submitted, they are returned to /dashboard. How do I alter that return? I have the following config variables set

'useEmailAsUsername' => true,
'autoLoginAfterAccountActivation' => true,
'activateAccountSuccessPath' => 'members/index',


texts: How do I pull categories from another category group for members of another category?

texts:
`I will try this again.

I have an index page for each category within category group 1 (markets).

I loop through the descendants of the given category to create filter buttons.

How do i pull all the categories from a 2nd category group (country) assigned to each market from markets  - listing them only once

For the market from category group-1 (markets), I am using:

{% set segments = craft.categories.descendantOf(category) %}
{% for category in segments %}
button html using {{ category.title }}
``{% endfor %}

For the countries from category group-2 (country), I tried using:

{% set name = craft.categories.group('country').relatedTo(category) %}
{% for nation in name %} button html with {{ nation.countryName }}
{% endear %}

Where countryName is the field name for the country group.

I did not get a template error.  But nothing printed.


texts:
So I've wasted a day because I couldn't figure out how to get an error back from an action I'm using in a plugin...

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

$newUserSuccess was empty, and it turns out the reason was because the new user was trying to register with an existing user's email address, which fails. I could not figure out how to get any useful information back. I had tried this:

if (!$newUserSuccess)
{
    AutoUserEntryPlugin::log('Couldn't save the new user: '.print_r($newUser->getErrors(), true), LogLevel::Info);
    throw new Exception(Craft::t('Couldnt save the user.'));
}

but in the log all that was output was "Couldn’t save the new user: Array"

How should I be doing this?


texts: Deploying Craft 3 site to production has working admin but 503 front end

texts:
I have just deployed my first Craft 3 site to a production server with the following process:

Deploying git repo to the server
Then running the composer command to download the required files for Craft etc that were ignored from git (from https://nystudio107.com/blog/setting-up-a-craft-cms-3-project)
Set up database etc

However, when I open the site in the browser it is returning a 503 Service Unavailable error yet the admin side of the site works absolutely fine.


texts: craft.request.getParam('entryId') returns null on edit page of an entry

texts:
I have a plugin that's loaded on the edit page of an entry.

Whenever I open the entry edit page, I would like to retrieve the id of this particular entry. I've tried this:
{% set someId = craft.request.getParam('entryId') %}

But this just returns null.

I need the id because I use it in my service: craft.pluginName.getRecordByEntryId(someId).
Which will return information that's bound to that page.

I've also tried this:

{% for entry in craft.entries %}
{% if entry.id %}

EntryId: <input type="text" value="{{ entry.id }}"/>

{% endif %}{% endfor %}

But this will return all the entry id's, which I can't really use.

Any help or advice on how I should tackle this differently?

Thanks in advance!


texts:
I need all of the custom fields on an order submitted to ZenDesk to create a new ticket once the order is completed.

Once a ticket is created in ZenDesk, we will need the ticket number saved on a new custom field on the order. This will be used later for grabbing comments on the ticket.


texts: Using ImageOptimize, how do you loop through photos?

texts:
I'm stumped on a basic concept for looping images. I'm using the plugin ImageOptimize with Imgix and Amazon S3. The code below works but only shows one image (when there's more for that field).

For the code below, how are you suppose to loop through the assets without showing the different srcset image sizes?

{% set optimizedImages = entry.clientWork.one().imgixTransforms %}

    <picture>
        <source srcset="{{ optimizedImages.srcsetWebP() }}"
            sizes="100vw"
            type="image/webp" />

        <img src="{{ optimizedImages.src() }}"
            srcset="{{ optimizedImages.srcset() }}"
            sizes="100vw" />
    </picture>


texts: What's the best way to increment a number of a class or id?

texts:
I have the following code which works fine. I'm just wondering if there is a more simple way of incrementing the id number?

{% set counter = '1' %}
{% for block in entry.news %}
  {% if block.type == "bodyBlock" %}
    {{ block.body }}
  {% elseif block.type == "codeBlock" %}
  {% set counter = counter + 1%}
    <div id="accordion{{ counter }}">
    ...
    </div>
  {% endif %}
{% endfor %}


texts:
I am new to Craft..
I created the Entries but didn't understood how to setup them to display as a menu. Seen the documentation, templating references.. But not get any idea about how to add navigation menu for the entries type. I am using the default template.

Thanks


texts: Multi sites: how to give each site a home single entry?

texts:
I've been experimenting with Craft 3 and Multi Sites and feel like I'm missing something...

My organisation has a main homepage and multiple sub-sites. I have a Single Section called 'home' that creates the main site homepage. I want each sub-site to have an individual homepage too. Each sub-site should only be able to edit their own homepage entry.

If I enable the 'home' Single Section across all sub-sites then they can all edit the main site homepage entry. The 'Propagate entries across all enabled sites?' option isn't available for Single Sections.

So how do I achieve this? :|


texts:
Is there a way to create conditional validation on 2 fields related to the same desired input using the Charge plugin? The Reason plugin does not work when defining fields in the CP->Charge->Settings->Field view.

I have a set of radio buttons and a text field for the user to input a chosen value. The user can either choose the buttons or type in a numeric value into the text field. However, it's possible that the user can simply not choose a value from neither the radio buttons nor type in a value into the text field.

I see in the documentation that there is an onBeforeCharge event that can be used, so perhaps I could create a custom validation rule there, but I don't know if that should be defined in a template or in Javascript. Any ideas?

Thanks.


texts: How to keep the setPasswordPath config when reset password link is expired?

texts:
In config.php file, setPasswordPath is set to match a custom template. This is working fine by following the reset password link sent by email (for a front end user).

But after I've changed the password (with users/setPassword action), if I click again on the reset password link in the email, I am redirected to a page within the default Craft template that inform me that the verification code is now wrong.

How can I also set a custom template for this page?


texts: How-to display a dropdown field with optgroups?

texts:
The display of a dropdown without optgroups is defined:

{% set field = craft.app.fields.getFieldByHandle('<FieldHandle>') %}

<select name="fields[<FieldHandle>]">
    {% for option in field.options %}

        {% set selected = entry is defined
            ? entry.<FieldHandle>.value == option.value
            : option.default %}

        <option value="{{ option.value }}"
                {% if selected %}selected{% endif %}>
            {{ option.label }}
        </option>
    {% endfor %}
</select>

The following error occurs:

Key "default" for array with keys "optgroup" does not exist.


texts: CRAFT_BASE_PATH problems when installing Craft 3 in subdirectory

texts:
My client wants Craft 3 installed in a subdirectory of the main site. So I placed it in http://mainsite.com/subdir.

The issue now is that the webroot for the domain is at http://mainsite.com, so my Craft index.php isn't being hit when I go to http://mainsite.com/subdir since it's further down in the /web folder.

I'm trying to pull my index.php out of /web and into the /subdir directory by setting a custom CRAFT_BASE_PATH, but I've tried several different paths to no avail.

The error is simply: "This page isn’t working. mainsite.com is currently unable to handle this request. HTTP ERROR 500"

My directory structure is:

var/www/html/subdir/
├── craft/
│   └── config, vendor, templates, .env, web etc
├── index.php

But if it would be better if I stuffed index.php back into /web and went about this a different way I'm all ears. I'm not the network admin, so if there is a way to set a custom root for a subdirectory on the server or something, I'll have to ask someone else to do it for me, which is fine if that's the best way to do it.


texts: Child page not appearing in the main menu

texts:
On our website www.efcgroup.net we have created new new product under a ghost page (under parent). We can see the new page heading in side bar but not under main menu at home screen.

In this example, the page is BOP hoists under Subsea Handling Equipment under mechanical handling. Please help


texts: Removing a matrix row via front end entry form

texts:
Read some similar posts on here but they don't quite solve my problem. I've gt an entry form with a matrix field in it, and I’m trying to make it editable via front end entry form. Specifically I'd like to be able to remove rows – either delete them, or disable them.

So my form has a ‘Remove’ button (Remove) on each row. Clicking the button should remove or disable the matrix row, save and reload the entry/page. Javascript isn’t my forte but here’s what I’ve got so far:

document.addEventListener('DOMContentLoaded', function () {
    function getAll(selector) {
        return Array.prototype.slice.call(document.querySelectorAll(selector), 0);
    }
    var $removeBtn = getAll( '.remove' );
    if ($removeBtn.length > 0) {
        $removeBtn.forEach( function ( $e ) {
            $e.addEventListener('click', function () {
                var target = $e.dataset.target;
                document.getElementById( target ).value = null;
                $( '#failures' ).submit();
            });
        });
    }
});

On my template I’ve got:

<input type="hidden" name="fields[{{ assessment.assessmentActionPlan }}][{{ block.id }}][type]" id="type-{{ block.id }}" value="failure">
<input type="hidden" name="fields[{{ assessment.assessmentActionPlan }}][{{ block.id }}][enabled]" id="enabled-{{ block.id }}" value="1">

My script is correctly setting the enabled field value to null and submitting the form (#failures), but the matrix field on the entry remains unchanged. Where am I going wrong? Thanks for any help.


texts: Plugin: Tags field for front-end Entry Form

texts:
I would like to add tags via a front-end entry form - not like here, but as follows:

Text field in a front-end entry form where user add tags (separated by commas).
After pressing the save button, the plugin should:
check for every tag, whether it exists already (and create the tag if not)
save the tags together with the rest of the entry form [see also here](including the text field with the user defined tags)

Now, I am looking for a developer (I am willing to pay for it).


texts:
I'm trying to get pagination and cache to work together but it's failing.

Here's my current code:

{% cache globally using key
   craft.request.path ~ '/p' ~ craft.request.getPageNum
   for 2 hours %}

{% paginate topicEntries.limit(10)as pageInfo, topicEntries %}

  {% for topic in topicEntries %}

      more code here

  {% endfor %}

{% endcache %

When I use this I get a template error that Variable pageInfo does not exist.

Then if I put the opening cache tag below the paginate tag. The first page shows 10 entries, but each page after that only displays 1 entry per page.

{% paginate topicEntries.limit(10)as pageInfo, topicEntries %}
 {% cache globally using key
    craft.request.path ~ '/p' ~ craft.request.getPageNum
    for 2 hours %}

  {% for topic in topicEntries %}

      more code here

  {% endfor %}

{% endcache %}

What I need to know is how to cache paginated entries so it's 10 per page and when a new entry is added the cache is cleared correctly.

Please advise.


texts: Set asset uploader from frontend entry form

texts: Now that Craft keeps track of which user uploaded an asset, I'm wondering if it's possible to set this information when an asset is uploaded via a frontend entry form. I have a form that includes an asset field and I would like the assets that are created to be "owned" by the current user. Can this be done via a hidden input, or would I need to hook into an asset event?


texts: Checking if a value is in an array of IDS - using a filter?

texts:
Is there an easier way to achieve this?
Perhaps using a |filter function?
{% set variantIds = [] %}
{% for variant in product.variants %}
  {% set variantId = variant.id %}
  {% set variantIds = variantIds|merge([variant.id]) %}
{% endfor %}

{% if wheelSpacer in variantIds %}
  this spacer
{% endif %}


texts:
I have built and deployed dozens of Craft sites, so I know how to remove 'index.php' from urls, but now I have a site that refuses to accept my most determined efforts to remove it.

This is the situation:

I am using the Craft supplied .htaccess file with the same settings
as all of my other sites.
Just to be thorough, I added 'omitScriptNameInUrls' => 'true', to the config file
double checked all of the general settings in the CP and all is as it should be

After trying a few things, I found that if I use {{ siteUrl }}path I get a clean url, but if I use {{ url('path') }} it leaves that nasty index.php in the url. The same is true for {{ entry.url }}. One last bit of puzzlement - if I manually enter a full path, e.g. http://sitename/news it works fine

I suspect I am missing something obvious, but it is definitely driving me nuts!


texts:
I'm trying to set up caching and have it disabled for my local environment using {% cache unless craft.config.devMode %}. This works fine on non-local environments, but on my local environment I'm getting the error Method "devMode" for object "Craft\ConfigVariable" does not exist. Even though it does, this is my config file:

return array(
    '*' => array(
        'addTrailingSlashesToUrls' => true,
        'omitScriptNameInUrls' => true,
        'enableCsrfProtection' => true,
        'cpTrigger' => 'example-admin',
        'siteUrl' => (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https://" : "http://" . $_SERVER['HTTP_HOST'],
        'environmentVariables' => array(
            'basePath' => $_SERVER['DOCUMENT_ROOT'] . '/data/uploads/',
            'baseURL' => (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https://" : "http://" . $_SERVER['HTTP_HOST'] . '/data/uploads/',
        )
    ),
    '.local' => array(
        'devMode' => true
    )
);

If I {{ dump(craft.config.devMode) }} I get bool(true) so it is being set, it's just when being used in the cache conditional.


texts: Suppose I have an assets field in my orders fields, how could I attach those files in the confirmation email?


texts:
I'm using dotphpenv for environment specific config.

This works perfectly for my db config. I added another 2 environment vars for devMode and allowAutoUpdates

DEV_MODE=false
AUTO_UPDATE=false

and updated general.php

<?php

return array(

  // Default

  '*' => array(
    ...
    'devMode' => getenv('DEV_MODE'),
    'allowAutoUpdates' => getenv('AUTO_UPDATE'),
    ...
  )
);

But with that set, dev mode and auto-update are still available to production.

If I set both to false we have no problem. This is obviously a phpdotenv thing because Craft is doing what it's supposed to but if anyone can shed light I'd appreciate it.


texts:
I'm trying to get a basic locals sub directory system working on Nginx:

/entry - en local.
/fr/entry - french translation.
/it/entry ect..

Having read this knowledge base article and some other forum posts I'm still having difficulties with 404 errors when following them or duplicate '/fr/fr'/entry issues.

Do I need to use duplicate index.php files with locals declared in them if I'm adding url paths in the section admin pages? What about site baseUrls in the config file?

The documentation seems very conflicting in these cases and having tried nearly every possible configuration option my site still won't serve up different locals.

I've had the most luck with this nginx config, together with specifying the local in the section urls in the cms for each section.

server {
    listen 80;
    server_name site.com;
    root /sites/site/public;
    index index.php;
    client_max_body_size 30M;
    location /en/ {
            root /sites/site/public;
            if (!-e $request_filename) {
                    rewrite ^/(.*)$ /index.php?q=$1 last;
            }
    }
    location /ru/ {
            root /sites/site/public/ru;
            if (!-e $request_filename) {
                    rewrite ^/(.*)$ /ru/index.php?q=$1 last;
            }
    }
    location /zh/ {
            root /sites/site/public/zh;
            if (!-e $request_filename) {
                    rewrite ^/(.*)$ /zh/index.php?q=$1 last;
            }
    }
    location / {
            root /sites/site/public;
            if (!-e $request_filename) {
                    rewrite ^/(.*)$ /index.php?q=$1 last;
            }
    }
    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(.*)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_ignore_client_abort on;
            fastcgi_param  SERVER_NAME $http_host;
    }

    location ~ /\.ht {
            deny  all;
    }
}

(each index.php has its own set local var within it like so for fr):

// Path to your craft/ folder
$craftPath = '../../craft';

// Tell Craft to serve the local site
define('CRAFT_LOCALE', 'fr');

// Do not edit below this line

My General config is

<?php

/**
 * General Configuration
 */

return array(
    'siteUrl' => array(
        'en' => 'http://www.site.com/',
        'ar' => 'http://www.site.com/ar/',
        'es' => 'http://www.site.com/es/',
        'fr' => 'http://www.site.com/fr/',
        'hu' => 'http://www.site.com/hu/',
        'it' => 'http://www.site.com/it/',
        'ru' => 'http://www.site.com/ru/',
        'zh' => 'http://www.site.com/zh/',
    ),
    'maxUploadFileSize' => 2147483647,

    );

This results in the server displaying the correct links to my localised articles in the menu and the en language serves up entries correctly, however other languages are found at /local/local/entitypath not local/entitypath.

Adding site_urls to my config seems to break things more, causing locals to not be served up at all.


texts: Checked "Require a password reset on next login" on my account, can't log in anymore

texts:
As a test, I checked the "Require a password reset on next login" box for my account and then logged out.

I tried logging in, expecting some sort of password reset screen, but nothing happened.

I then tried to reset my password at the login screen -- something I was able to do before -- and nothing happened.

In both cases, I get a "500 (Internal Server Error)" in the console.

Any ideas for fixing this? At the very least, can I just reset my password directly in the DB via phpMyAdmin?

FWIW, I also ran into this problem using a Craft demo site.


texts: Matrix field freezes on localhost when I try to make a new entry

texts: I have a simple Matrix field that includes two sub-fields: a one line plain text field, and a multi-line plain text field. When I try to create an entry Craft freezes at the Create New Entry screen. When I run the same Craft configuration on a remote apache server no freezing occurs. I'm using a wamp server (on a PC of course). I have the same problem on my wamp-craft setup on PC at work and my PC at home. I've never had a problem with any wamp server before and have never had a problem with Craft. My guess is it's a wamp permissions problem that's specific to the Matrix field (this is my first attempt at using the Matrix field feature). Any suggestions?


texts: Entries from all categories in a category group via URL?

texts:
I'm familiar with the option in the category settings that allows for categories within a category group to each have their own URLs:

I have this setup and it is working fine. However, I'm wondering if there is a URL structure that will allow me to have a category group "home" URL in which entries from all categories within the category group are shown.

I know there are a couple of different ways I could do this by setting up templates for each category group "home" page, but I would prefer a way to do this using a single template that took into account the URL structure.


texts:
How do I display my entry post date, formated as "May 24, 2015"?

I know this is a very basic question, but I can never find these easy answers in either the Craft or Twig documentation.


texts: Sort entries in a category or entries field?

texts:
I have a Products Section and a Product Category Structure Section
In Products there is an Entries Field where the Category is selected from the Product Category section.

Is it possible to sort the products per category manually?

I see with the ManytoMany Plugin - https://github.com/page-8/craft-manytomany
You can display the products which appear in each Category and the Custom Ordering of the second Relationship is in the pipeline which would probably work but not available yet.

Is there any other option?


texts: alternative global variable to siteUrl or the primary website?

texts:
I am currently developing a multilingual craft website. To include assets like styles and scripts, I have so far built the URL following the pattern "{{ siteUrl }}/assets/css/main.css".

However, as soon as I change from German to English in the frontend of the website, the siteUrl changes, too, so that the styles and scripts can't be found anymore.

Is there another global variable, like {root_url} in expressionengine, which returns only the URL of the primary website or the root URL, regardless of the chosen language or site?

thanks!


texts:
Right now, we have a matrix field called post body which has all our content, we have text, image, video etc... In our image block we have 2 fields, An asset field called image & a plain text field called caption.

When I first set this site up, admittedly I didn't plan it properly at all and now we allow several images to be uploaded in the single field but we want to be able to set individual captions for each of the images.

Not sure if this is the right way to phrase the question, how would I go about moving the contents of postbody.block.caption to postbody.block.image.caption for every image in that field?

This is going to be a once off migration of content so I'm not sure if it warrants a plugin, would I be able to do this with a quick & dirty sql/yii query?

Here is what I have so far

<?php

$craft = require '../craft/app/bootstrap.php';

$criteria = $craft->elements->getCriteria(Craft\ElementType::MatrixBlock);
$criteria->fieldId = $craft->fields->getFieldByHandle('postBody')->id;
$criteria->type = "image";
$criteria->limit = null;
$blocks = $criteria->find();

foreach ($blocks as $block) {
    if ($block->caption) {
        foreach($block->image as $image) {
            $block->image->imageCaption = $block->caption;
        }
        $block->caption = NULL;
        $craft->matrix->saveBlock($block);
    }
}
?>

But that gives Property "Craft\MatrixBlockModel.caption" is not defined.

Edit  I’m now at the stage where the contents of the caption field has been saved to each of the images in that block, but i cant seem to set the caption field on the block to null. Here is what I have at this stage

 $craft = require '../craft/app/bootstrap.php';

$criteria = $craft->elements->getCriteria(Craft\ElementType::MatrixBlock);
$criteria->fieldId = $craft->fields->getFieldByHandle('postBody')->id;
$criteria->type = "image";
$criteria->limit = null;
$blocks = $criteria->find();

foreach ($blocks as $block) {
    if ($block->caption) {

        $caption = "<p>".$block->getContent()->caption."</p>";
        foreach($block->image as $image) {
            $asset = $craft->elements->getElementById($image->id);
            if(empty($asset->getContent()->imageCaption)) {
                $asset->getContent()->imageCaption = $caption;
                $success = $craft->assets->storeFile($asset);
            }
        }

        $block->setContent(array(
            'caption' => '',
        ));

        $success = $craft->matrix->saveBlock($block);

        dd($success);

    }
}


texts: I want to sort entries by Entry Type in the order they appear when you create/edit entry types in the CP (which can be reordered). I can't seem to find an argument for order() that works. Can this be done?


texts: Updating Entry field with GraphQL mutation

texts:
I'm trying out the GraphQL mutations and would like to issue an update of an Entry, triggered from a webhook.
However, documentation on mutations seems sparse, and I find GraphQL highly confusing. Most examples talk about creating new entries, not update current ones, and how you actually call graphQL relies on implementation, it's hard to figure out how to deal with this in Craft.
I found https://github.com/craftcms/cms/issues/4835, which shows an example of creating an entry. Documentation talks about creating drafts, and publishing drafts, but no examples are shown, just a bunch of words thrown around.
First it says:

To save a draft for an entry, use the entry type-specific mutation which will have the name in the form of save___Draft

But then followed by:

To create a draft use the createDraft mutation., which requires the id of the entry for which to create the draft as an argument and returns the resulting id of the draft as the result.

For publishing a draft, you should use the publishDraft mutation, which requires the id of the draft to publish as an argument and returns the id of the entry it belongs to as the result.

None of these things makes sense to me...
Anyone have any comprehensible examples they can give?


texts: What criteria can the Element API plugin accept?

texts:
I have a structure called "locations" that contains two entry types:

State
Location

I'd like to access specific states at the URL locations/ny.json, for example, and get a JSON object with all the location entries nested under that state.

The entries are already properly nested for HTML output, but I'm trying to get the JSON to match.

This is my elementsapi.php file right now:

<?php
namespace Craft;

return [
  'endpoints' => [
    'locations.json' => [
      'elementType' => 'Entry',
      'criteria' => [
        'section' => 'locations',
        'type' => 'location'
      ],
      'transformer' => function(EntryModel $entry) {
        return [
          'title' => $entry->title,
          'url' => $entry->url,
          'latitude' => $entry->latitude,
          'longitude' => $entry->longitude,
          'jsonUrl' => UrlHelper::getUrl("locations/{$entry->id}.json")
        ];
      },
    ],
    'locations/<slug:{slug}>.json' => function($slug) {
      return [
        'elementType' => 'Entry',
        'criteria' => [
          'section' => 'locations',
          'type' => 'state',
          'slug' => $slug
        ],
        'transformer' => function(EntryModel $entry) {
          return [
            'title' => $entry->title,
            'url' => $entry->url,
            'latitude' => $entry->latitude,
            'longitude' => $entry->longitude,
            'jsonUrl' => UrlHelper::getUrl("locations/{$entry->id}.json")
          ];
        },
      ];
    },
  ]
];

The second endpoint is currently returning a single state entry, but I would like it to return all locations that are a descendant of that state.

Is this possible using a criteria param such as descendantOf?
What criteria params are available?


texts: How to debug or log some special variables in Craft CMS? (Especially in a controller)

texts:
I am going to debug the variables in controller files.

But I couldn't figure out how I can debug it and show the values into front-end site or in log files.

Do you have any ideas about this?

What is your debug mode which you often use when you work in a controller?


texts: How to add Setting Page in my plugin after updating plugin

texts: I had created a plugin, but now I need to add a setting Page. If I remove plugin through composer remove and install it again through composer require, I get the setting page, but if I just update the plugin files and do an uninstall and install, I do not see the setting page. The reason is first my composer.json file has "hasCpSettings": false which added the same in plugin.php file. But now I have "hasCpSettings": true, so I guess just updating the plugin or doing an uninstall/install from plugin setting doesn't update the plugin.php file. Is composer remove and then composer require the only way of getting setting page ? As this would be hard doing on a server with no terminal access.


texts:
I'am building a website (craftcms 3.4+) where I'll need frontend entry editing. Therefore I'll need the fieldlayout of an entry. This is what I'll have:

{% for tab in entry.fieldLayout.tabs %}

{{ tab.name }}

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

                {% if field.type == 'plainText' %}
                    {{ field.name }}
                    <input type="text" name="fields[{{ field.handle }}]" value="{{ attribute(entry, field.handle)}}">
                {% endif %}

        {% endfor %}
{% endfor %}

The problem of this is that field.type not excist. I'll need that because of the different field types I'm using. How I'll get the th


texts: Disabled product variant still shows in {% for %} loop

texts:
Disabling a product variant doesn't remove it from a {% for purchasable in product.variants %} loop I have set up. It still renders an image associated with it, as well as a color swatch. Essentially not disabling it at all.

{% for purchasable in product.variants if purchasable.status('live') %} isn't working either, which I assume is only applicable to the product model.

Any ideas?


texts: Outputting siteUrl consumes next closing tag

texts:
I'm running Craft Pro 2.3.2640.

Here is the code:

<span>{{ siteUrl }}</span>

Here is the output:

//localhost:3001/%3C/span%3E

The opening tag stays intact.

I am also struggling to use this variable with functions like "replace" when I need to parse the referral url.


texts: Is it possible to provide an option to pick up an order from the physical store in Craft Commerce?

texts:
We're setting up a Craft Commerce site and the merchant wants to give the option to the customer to pickup the order from their physical store instead of shipping it to a specified address.

If the customer selects that option then they shouldn't have to provide a shipping address or billing address.

Is this possible in Craft Commerce? If not is there a plugin or a suggested way to do this?


texts: Running Craft CMS 2 on MySQL 8.0+ (Any major considerations?)

texts:
Yes, that's not a typo. This is for a Craft 2 site (long story). Because MySQL 5.6 is EOL in a few weeks, I am validating how feasible it can be to run under MySQL 8.0, there's not really any option to go 5.7, as our upstream provider provisions MySQL 8 by default now.
I'm asking mainly for anyone else who may have looked at this in addition to validating my own testing and what I have found. I provisioned a NGINX, PHP 7.3 FPM, MySQL 8.0 environment and did initially find several problems with MySQL 8 and Craft 2 that mean you couldn't get past the "cannot connect to DB error" even though the DB credentials were fine. Confirming that it wasn't me being dumb with wrong .env credentials I downgraded my DB container back to MySQL 5.7 and everything immediately worked, so it confirmed that MySQL 8 was the issue.
I eventually wrote a simple PDO MySQL test outside of Craft and found some errors being thrown which we not visible when going to /admin/install (I may have got more clues looking at the logs, but sometimes, you need to sanity check yourself!). Which thankfully did then explain why things were failing and there were several issues in the end.
Default authentication plugin changes
I found Craft 2 couldn't even connect with PDO because of the default authentication plugin change for new MySQL 8 servers. Because this environment was provisioned with docker the default setting was caching_sha2_password. Older databases probably won't hit this.
https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_default_authentication_plugin
This required the following change on the DB user however:
ALTER USER 'db_user' IDENTIFIED WITH mysql_native_password BY 'password';
FLUSH PRIVILEGES;

db_user - MySQL database user
password - MySQL database user password

SQL mode
SQL mode requires the following modification, because it references a removed option in MySQL 8 which will break the DB connection as well. From the original topic on Craft 2 on MySQL 5.7.5+: Getting this SQL Error: GROUP BY incompatible with sql_mode=only_full_group_by
SQL mode needs to be set to:
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

NO_AUTO_CREATE_USER needs to be removed from initSQLs or any .cnf configuration for MySQL 8.0+.
After that, this appears to allow Craft 2 to connect properly.
General issues/problems?
So once I'd figured out why Craft 2 was having a hard time connecting to the DB backend, I pulled a DB export from our currently live environment using MySQL 5.6 and imported it into MySQL, aside from a minor issue with row sizes on the craft_content table (not MySQL 8 specific another issue) the DB seems to be OK and running under MySQL 8 fine. I haven't extensively tested all functionality yet, but for the most part it does seem to be running OK, no server errors when performing some save actions and such.
Are there any major considerations or issues specifically for Craft 2 and MySQL 8 that should be monitored?


texts:
I am currently using spoeken's gulp workflow (https://github.com/spoeken/gulp-craftcms). Everything works well in development, however, when it comes to production, I can't seem to concat/minify my bower_components dependencies, into one file.

I currently have a public/resources/js/app.min.js, however, my bower_component dependencies are sitting in app/resources/bower_components.

How do you go about minifying my dependencies into one file?

Here's what I have in my package.json file:

{
  "name": "craftgulp",
  "version": "0.0.0",
  "authors": [
    ""
  ],
  "license": "MIT",
  "private": true,
  "dependencies": {
    "jquery": "~2.2.0",
    "tether": "^1.4.0",
    "bootstrap": "v4.0.0-alpha.2",
    "gsap": "^1.19.1",
    "scrollmagic": "^2.0.5",
    "slick-carousel": "^1.6.0",
    "waypoints": "^4.0.1"
  },
  "overrides": {
    "bootstrap-sass": {
      "main": [
        "assets/stylesheets/_bootstrap.scss",
        "assets/fonts/bootstrap/*",
        "assets/javascripts/bootstrap.js"
      ]
    },
    "scrollmagic": {
      "main": [
        "./scrollmagic/uncompressed/ScrollMagic.js",
        "./scrollmagic/uncompressed/plugins/animation.gsap.js",
        "./scrollmagic/uncompressed/plugins/debug.addIndicators.js",
        "./scrollmagic/uncompressed/plugins/jquery.ScrollMagic.js"
      ]
    },
    "gsap": {
      "main": [
        "./src/uncompressed/TweenMax.js",
        "./src/uncompressed/TimelineLite.js",
        "./src/uncompressed/jquery.gsap.js"
      ]
    },
    "slick-carousel": {
      "main": [
        "./slick/slick.min.js",
        "./slick/slick.css",
        "./slick/slick-theme.css"
      ]
    },
    "waypoints": {
      "main": [
        "./lib/jquery.waypoints.min.js"
      ]
    }
  }
}


texts: Ajax - Create tag with custom ID programatically

texts:
I'm trying to create an jQuery/Ajax script to import data from a Wordpress API service and want to import the WP tags into my database.

Everything works as expected when I loop through the data and send it to /actions/tags/createTag but I'd like to keep the original tag IDs in order to be able to import the posts later and keep the relationship with their tags (Craft automatically assigns a length+1 ID to new tags).

Any way I can do this?


texts: Test Craft Plugin without the use of a database

texts:
We'd like to add Unit Tests to our Craft Plugin. I have used the Plugin Factory generator to generate the files and the basic setup seems to work.

I am however struggling getting the tests to work without the need to use a database. This because our CI/CD is not set-up to work with a database at the moment. And the part we'd like to add test for doesn't require a database.

Within the codeception.yml file, I have set dbSetup: {clean: false, setupCraft: false}. But this still asks for valid database credentials. Then I was seeking into fullMock: false. But I can't seem to access Cacheable::getInstance(). It returns a NULL. Also adding the below to the Cacheable.php file in the src folder is never called.

public function getComponentMap()
{
    return [
        [ContentService::class, ['getContentService', 'contentService']]
    ];
}

What am I missing here? Or is using a database a hard requirement?


texts:
Is it possible to change core elements index pages -like entry index page- by plugin in PHP way, like extending their twig, using events, hooks and not manipulating DOM with Javascript?

Currently only way i know is to register a JS file for those pages and add HTML via Javascript.


texts: PHP warning with composer on MacOS Mojave: Failed to open stream: No such file or directory

texts:
I am working on a plugin in Craft:3.4. I get this error while trying to install the plugin in the CP.
yii\base\ErrorException: include(/app/vendor/composer/../wittsstratts/craft-company/src/Company.php): failed to open stream: No such file or directory in /app/vendor/composer/ClassLoader.php:444
Stack trace:
#0 /app/vendor/craftcms/cms/src/web/ErrorHandler.php(74): yii\base\ErrorHandler->handleError(2, 'include(/app/ve...', '/app/vendor/com...', 444)
#1 /app/vendor/composer/ClassLoader.php(444): craft\web\ErrorHandler->handleError(2, 'include(/app/ve...', '/app/vendor/com...', 444, Array)
#2 /app/vendor/composer/ClassLoader.php(444): include()
#3 /app/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/app/vendor/com...')
#4 [internal function]: Composer\Autoload\ClassLoader->loadClass('wittsstratts\\co...')
#5 [internal function]: spl_autoload_call('wittsstratts\\co...')
#6 /app/vendor/craftcms/cms/src/services/Plugins.php(873): is_subclass_of('wittsstratts\\co...', 'craft\\base\\Plug...')
#7 /app/vendor/craftcms/cms/src/services/Plugins.php(478): craft\services\Plugins->createPlugin('company')
#8 /app/vendor/craftcms/cms/src/controllers/PluginsController.php(50): craft\services\Plugins->installPlugin('company', NULL)
#9 [internal function]: craft\controllers\PluginsController->actionInstallPlugin()
#10 /app/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#11 /app/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#12 /app/vendor/craftcms/cms/src/web/Controller.php(178): yii\base\Controller->runAction('install-plugin', Array)
#13 /app/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('install-plugin', Array)
#14 /app/vendor/craftcms/cms/src/web/Application.php(290): yii\base\Module->runAction('plugins/install...', Array)
#15 /app/vendor/craftcms/cms/src/web/Application.php(558): craft\web\Application->runAction('plugins/install...', Array)
#16 /app/vendor/craftcms/cms/src/web/Application.php(269): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#17 /app/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#18 /app/web/index.php(21): yii\base\Application->run()
#19 {main}

This question is related to this but with a different setup.
Tools:

Docker:19.03.5
Composer:1.10-dev

This might help anyone facing this same issue.
I found the reason for the error was because I was using docker. Composer symlinks the plugin from its physical directory into craft's vendor directory. The plugin directory as a result of this was not mounted into docker container. Thus, craft was not able to locate the plugin directory. All I did to fix this was move the project(plugin) into craft's vendor director.


texts: How to change the display of asset fields in the control panel via plugin?

texts:
I would like to modify how assets are displayed within asset fields in the control panel's edit entry page, so that thumbnails are larger and the name is not displayed.

After some investigation I found that when assets are added to an entry the following line is called {% hook "cp.elements.element" %}. This is calling the template service generating the html that displays the thumbnails and the name. ( _getCpElementHtml() is the function that is associated with the hook ) Is there a way to modify this without directly changing the core files?


texts: Check if cart contains valid products for discount code

texts:
I am trying to setup some error trapping on the discount code to output an error message if there are no products that qualify for the discount code the user enters. Here is the code I have;

    {% set currentDiscount = craft.commerce.getDiscountByCode(cart.couponCode)%}

    {% for item in cart.lineItems %}
        {% set cartProductIds = item.purchasable.product.id %}

        {% if currentDiscount %}
            {% if not cartProductIds in currentDiscount.productIds %}You have no products in the cart that meet this discount{% endif %}
        {% endif %}
    {% endfor %}

Currently this doesn't give me anything back. Can anyone point me further in the right direction...?

Edit: I have since found the code I pasted as an answer no longer works or never fully worked. I am struggling to loop through an array and check against the other array and if no id's match then set an error. I want to check if any of the cart Id's match against any of the discount code id's.

Here is my revised code, but it just doesn't match fully. I don;t think it is a bug, but more likely a failing of my code. Can anyone shed any light?

{# THIS CHECKS THE DICOUNT CODE FOR IF THERE ARE ANY VALID/ELIGABLE PRODUCTS IN THE CART #}
        {% set currentDiscount = craft.commerce.getDiscountByCode(cart.couponCode) %}
        {% set codeError = null %}

        {% if currentDiscount %}
            {% set cartProductIds = [] %}
            {% set discountProductsIds = [] %}

            {% for item in cart.lineItems %}
                {% set cartProductIds = cartProductIds|merge([item.purchasable.product.id]) %}
            {% endfor %}

            {% set cartProductIds = cartProductIds|join('|') %}

            {% for product in currentDiscount.products %}
                {% set discountProductsIds = discountProductsIds|merge([product.id]) %}
            {% endfor %}

            {% set discountProductsIds = discountProductsIds|join('|') %}

            Products in Cart = {{cartProductIds}}
            Products in Discount = {{discountProductsIds}}

            {% if cartProductIds not in discountProductsIds %}
                {% set codeError = 'Sorry there are no products in your cart that are eligiable for the code ' ~ cart.couponCode %}
            {% endif %}

        {% endif %}


texts: Craft strips out parenthesis in file names.

texts:
Is there any way to allow () in asset file names (ex. file(1).txt)? Craft strips it out when it saves. The only way I've found is to change it via ftp and update asset indexes.

I've set convertFilenamesToAscii => false but that didn't help.


texts: Get a specific product with Element API, Commerce and Craft 2

texts:
How do I get a specific product via Element API?

Here's what i have so far

'api/product' => function() {
    $productId = craft()->request->getRequiredQuery( 'productId' );

    return [
        'elementType' => Product::class,
        // This provides Element API the fully qualified Element namespace + class.
        'pretty'      => true,
        'criteria'    => [
            'relatedTo' => [ 'targetElement' => $categoryIds ],
        ],
        'transformer' => function( Product $product ) {
            return [
                'title' => $product->title,
                'url'   => $product->url
            ];
        }

    ];
}


texts: Applying the activation link to linked text in the notification email

texts:
Whether I use an HTML email template or not, there are a few problems with the activation email link that appears as follows:

http://localhost.dev/actions/users/verifyemail?code=lzxmSVbLE~scHE5KPuL7Rk2oZqJbafyD&id=c3b6d053-2d69-43a8-9b1a-3210df88993c

Links output as URLs in emails unfortunately tend to trigger spam filters. It's best practice to ensure that you're always wrapping links around real text, not the same URL, linked.
More importantly, that link consistently breaks on the /verifyemail... portion (I'm viewing it in the Fastmail web client) and is not clickable. This occurs with the basic notification formatting, and within my HTML email template.

I tried wrapping the link in HTML markup under Email Settings -> Messages, and included autoescape false in my HTML email template (around {{body}}), but I get escaped HTML in the email. (I'm assuming that's because you're using the same message text for multipart HTML & text emails.)

My question is: Is there any way available presently to apply the activation link to linked text rather than outputting it directly in the email?

(This is a subscription site allowing users to self-register, so a non-clickable link in an email is one more hurdle I'd like to avoid.)

Thanks!


texts: Prevent to upload any kind of file on Asset menu

texts:
I made two different types of Assets: one for images and one for PDF.
They works in 2 differents folder to avoid to mix them.

Using them inside entries it works good, if I try to upload something different I receive an error message.

If I click Assets on the main Menu (not inside entries) I'd like limit the upload to the asset I choose.

It means that I would like prevent to upload a pdf on asset images and vice versa and I'd like also to prevent uploading of any different file types.

Not sure if Im doing something wrong or its the natural behaviour of CRAFT.


texts: Bypass Varnish cache if user is logged in

texts: Is it possible to bypass the Varnish cache when the user is logged in? I've tried using the "CraftSessionId" cookie, but it seems that it is also set for non logged in users.


texts:
Good afternoon. It would appear that i've lost all my entries! I still have the headings, but where I would have entries added (the pages i would edit on my site), i have nothing!

It is all still on my site thank goodness. Is there anyway I can recover this, Or revert back to a previous "backup" point as you would in windows?


texts:
I created matrix field, put it in the user field. In the front-end page as usually write

{% for block in user.myMatrixfield.type('myType') %}
   ................
{% endfor %}

but there is no output!
try to write {% user.myMatrixfield|length %} - outputs 0

In administration panel everything works.
How to get matrix field in user-profile front-end page?


texts: Sprout forms entries saving on staging but not live environment

texts:
We have a sprout form at staging.efficiencyforaccess.org/concept-note that successfully submits and saves data to Craft, but when pushed to the live environment (efficiencyforaccess.org/concept-note) the form data will submit but not save, and often causes the site to timeout.

The code is exactly the same on both environments, so why would the live version not work if the staging version does?


texts: Venti Events causing failed DeleteStaleTemplateCaches task

texts:
As you can see from the craft.log, venti is causing an issue with template refresh:

2016/01/19 10:59:27 [info] [application] [Forced] Starting step 242 of 828 total steps.

2016/01/19 10:59:27 [info] [application] [Forced] Starting step 243 of 828 total steps.

2016/01/19 10:59:27 [error] [system.db.CDbCommand] CDbCommand::fetchAll() failed: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'venti.startDate' in 'order clause'. The SQL statement executed was: SELECT `elements`.`id`, `entries`.`sectionId`, `entries`.`typeId`, `entries`.`authorId`, `entries`.`postDate`, `entries`.`expiryDate`

FROM `craft_elements` `elements`

JOIN `craft_elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id

JOIN `craft_content` `content` ON content.elementId = elements.id

JOIN `craft_entries` `entries` ON entries.id = elements.id

JOIN `craft_sections` `sections` ON sections.id = entries.sectionId

LEFT JOIN `craft_structures` `structures` ON structures.id = sections.structureId

WHERE (((elements_i18n.locale = :locale) AND (content.locale = :locale)) AND (elements.archived = 0)) AND (elements_i18n.enabled = 1)

GROUP BY `elements`.`id`

ORDER BY `venti`.`startDate` ASC LIMIT 5.

2016/01/19 10:59:27 [error] [application] Encountered an error running task 5 (DeleteStaleTemplateCaches), step 243 of 828: An exception was thrown: CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'venti.startDate' in 'order clause'

Has anybody else had this issue? Frustrating as it means my cache isn't working properly, causing 'Failed Task' to show up in the Admin for the client and I'm not sure but may be affecting other areas of the site.

Thanks in advance.


texts: Getting Price and Add to Cart Button. Any thoughts on what I am doing wrong

texts:
I am trying to get the price and add to cart link for a product

This is what I am testing at the moment, is it completely wrong?

========== Setting Variables ===========

{% set giftDepositID = 6901 %}
{% set giftDepositPrices = 0 %}

{% if craft.commerce.products.id(giftDepositID)|length %}
    {% set giftDepositproduct = craft.commerce.products.id(giftDepositID).find() %}
    {% set giftDepositvariant = giftDepositproduct.defaultVariant %}
    {% set giftDepositpurchasableId = giftDepositvariant.purchasableId %}
    {% set giftDepositPrices = craft.childsown.getVariantPrice(giftDepositpurchasableId) %}
{%endif%}

========== Example HTML ===========

{{"Deposit"|t}}

${{giftDepositPrices}}

                        <form method="POST">
                            <input type="hidden" name="action" value="commerce/cart/updateCart">
                            <input type="hidden" name="redirect" value="commerce/cart">
                            <input type="hidden" name="qty" value="1">
                            <input type="hidden" name="purchasableId" value="{{giftDepositpurchasableId}}">
                            <button class="form-control btn btn-yellow text-white" type="submit" data-click=".softie-form .red .btn">{{"BUY NOW"|t}} </button>
                        </form>

Any help/guidance is appreciated.

======= EDIT ========

New Variable set, I have updated the following:

{% set giftDepositID = 6901 %}
{% set giftDepositPrices = 0 %}
{% set giftStandardID = 6899 %}
{% set giftStandardPrices = 0 %}
{% set giftLargeID = 6897 %}
{% set giftLargePrices = 0 %}

{% if craft.commerce.products.id(giftDepositID)|length %}
    {% set giftDepositproduct = craft.commerce.products.id(giftDepositID).find() %}
    {% set giftDepositvariant = giftDepositproduct.defaultVariant %}
    {% set giftDepositpurchasableId = giftDepositvariant.purchasableId %}
    {% set giftDepositPrices = giftDepositvariant.getVariantPrice(giftDepositpurchasableId) %}
{%endif%}

This is the output of the HTML

Deposit

$

<form method="POST">
<input type="hidden" name="action" value="commerce/cart/updateCart">
<input type="hidden" name="redirect" value="commerce/cart">
<input type="hidden" name="qty" value="1">
<input type="hidden" name="purchasableId" value="">
<button class="form-control btn btn-red text-white" type="submit" data-click=".softie-form .red .btn">BUY NOW </button>
</form>


texts: Combine image assets widths to get total width

texts:
How can I check if multiple asset image widths combined are wider than X?
So how do i get X?

Like this:

File 1 = 300px wide
File 2 = 200px wide
File 3 = 250px wide

x >= 750px than

  Do This

else

  Do that


texts: Using {% cache %} tags around {% template %} includes (or in Header)

texts:
I was wondering if it makes sense to wrap these {% cache %} around {% include %} tags that call a separate file with params. Is it better to just include them in the actual file itself?

For example, I was using cache tags around includes that call main navigation HTML in the header, like so:

{% cache globally %}
  {% include '_partials/navigation/config.twig' with {
     menuLinks: menuNavLinks,
     direction: "right",
     type: "header"
   }%}
{% endcache %}

This was causing an allocated memory error that took me forever to debug. FYI I am running locally on XAMPP and my memory_limit is set to 128M; when I increased this, it caused even more issues, related to Database Exception "MySQL error 2006: mysql server has gone away."

Is this not advised and against proper {% cache %} practices?


texts: MySQL Collation: utf8mb4_unicode_ci (emojis)

texts:
The Craft docs call for using utf8_unicode_ci for MySQL collation. MySQL 5.5.3 introduced support for utf8mb4_unicode_ci, which, I believe, is required to support the storage of emojis.

Does anyone have experience running Craft with the utf8mb4_unicode_ci collation? Any issues to watch out for?


texts: Dynamic link to same entry but in alternate language

texts:
I'm working on a multilingual website (Spanish and English, default is Spanish). I'm using the SEOmatic plugin, and I see that it generates this code:

<link rel="alternate" hreflang="es" href="http://localhost:8888/cmml/contacto" />
<link rel="alternate" hreflang="en" href="http://localhost:8888/cmml/en/contact-us" />

And I'm wondering if, instead of linking to the home page in an alternate language is there a way to link to the same resource in the alternate language?

Is there an easy way to achieve this? Thanks folks.


texts: How to get a Super Table relation in PHP?

texts:
The following code works great in a template.

{% set priceProduct = currentUser.priceTable.relatedTo({
    targetElement: product.id,
    field: 'product'
}).one() %}

{{ priceProduct.price }}

Where priceTable is a Super Table, product.id is from an entry element (we're in loop).

'product' is an entry field in the Super Table row and 'price' is a plaintext field in the Super Table row.

How might we go about replicating this functionality in a plugin?

Craft Pro 3.0.29

Super Table 2.0.11


texts: How can I update all the packages under craft/app/vendor for Craft CMS 3 (Yii 2)?


texts: How can I show 3 entries at random from within the next 10

texts:
{% for entry in craft.entries.section('entertainmentEvents').status('live','pending').search('entertainmentBanner:*').order('RAND()').limit(3) %}

This is working to show 3 random entries from the full list of all entries with the entertainmentBanner field populated. How would I limit it to the first ten entries by entry date and then 3 at random from within them?


texts:
Is there a possibility to ad a 'superscript' button to redactor?

Edit: I found an explanation here: How can I use <small> <sub> <sub> within a redactor/rich-text field?

But I can't get it to work.

I copy this snippet form: http://imperavi.com/redactor/examples/buttons-sup-and-sub/ to  craft/app/resources/lib/redactor/plugins/subsup.js

if (!RedactorPlugins) var RedactorPlugins = {};

RedactorPlugins.scriptbuttons = function()
{
    return {
        init: function()
        {
            var sup = this.button.add('superscript', 'Superscript');
            var sub = this.button.add('subscript', 'Subscript');

            // make your added buttons as Font Awesome's icon
            this.button.setAwesome('superscript', 'fa-superscript');
            this.button.setAwesome('subscript', 'fa-subscript');

            this.button.addCallback(sup, this.scriptbuttons.formatSup);
            this.button.addCallback(sub, this.scriptbuttons.formatSub);
        },
        formatSup: function()
        {
            this.inline.format('sup');
        },
        formatSub: function()
        {
            this.inline.format('sub');
        }
    };
};

Then I call the plugin in a custom.json file like this:

{
    buttons: ['link','bold', 'italic','unorderedlist','orderedlist','image','html'],
    plugins: ['fullscreen', 'subsup'],
    toolbarFixedBox: true
}

But that results in nothing. What do I miss?


texts: Error when trying to send HTML email on event onActivateUser

texts:
Background:

I'm working on a site that has frontend registration with some custom fields. The client would like to have a notification email whenever someone activates their account, containing the info on that user (so name, email and the custom fields).

Issue at hand:

For some reason, I'm getting the following error when I try to send an HTML email on the 'onActivateUser':

  Unable to find the template “_emails/customer-service-notification”.

If however I try to send a plain text email, it all goes without problem.

I'd prefer to send out an HTML email so I'd like to resolve this.

What I already tried:

Triggering the service function in another way (via custom controller action) sends the html email just fine
Sending the mail by just setting the content as string in the function works just fine

Code:

Main plugin file - init function

craft()->on('users.onActivateUser', function (Event $event){
    $user = $event->params['user'];
    craft()->plugin_customerServiceNotification->sendNotificationMail($user);
});

customerServiceNotification

public function sendNotificationMail(UserModel $user){
    $mailer = craft()->email;
    $mailToBeSent = new EmailModel();

    $mailToBeSent->subject = Craft::t('Nieuwe gebruiker geregistreerd');
    $mailToBeSent->fromName = 'xyz';
    $mailToBeSent->sender = 'noreply@xyz.be';

    $mailToBeSent->toEmail = 'xyz@xyz.be';

    $content = craft()->templates->render(
        '_emails/customer-service-notification',
        [
            'userInfo' => [
                'email' => $user->email,
                'name' => $user->fullName,
            ],
        ]
    );
    $mailToBeSent->htmlBody = $content;

    $mailer->sendEmail($mailToBeSent);
}

Folder structure:


texts:
I have entries that contain a single graphic asset. I'm trying to use the graphic as a background image in my template. However, I'm unable to output the URI for the asset. I'm using entry.graphic.first().url but I get an error that the property is null. I'm using the dbug plugin to look at the properties and can see that the asset is being returned, however the URI property is null.

I am looping through entries and am unable to return the URI for any of the graphics. Any ideas?

Thanks!

EDIT: Sorry for the lack of code, guys! Below is my whole content block for the page so far.

Video Archives

  {% for entry in craft.entries.section('watch').order('seriesStart desc').type('series') %}
    {% set thumb = entry.graphic.first() %}

  {% endfor %}

Thanks for the help!


texts:
Can the Entry URL Format of a Channel intersect with the Entry URL Format of a Structure? For example I have a Structure like this-

Top-Level Entries: products/{slug}

Nested Entries: {parent.uri}/{slug}

Can a Channel Entry URL Format be set so that the scenario below is possible?

products/shirts/reviews <-- review list page
products/shirts/reviews/{slug} <-- individual review


texts:
I have a cool upcoming project which its content will heavily depend on external images. Although I'd like to get rid of WordPress for this project and would love to use Craft, WP has a great plugin called Grab & Save, that allows you to grab and save images from remote urls into your own WP media library.

I was wondering if Craft has a similar plugin or functionality, which it would be a huge time saver for these kind of projects.

-Edit

Without wanting to sound cheeky, would anyone with a bit of free time care to help me out a noobie and write it for me? I can't make head or tail of programming :/ heh.


texts: Craft CMS hangs when deleting a field then throws 504

texts:
We have an instance of Craft CMS running that has a lot of content entries and a lot of fields, using Neo and SuperTable. At some point, something changed and now when we try to delete one of the fields the CMS will just hang until it eventually throws a 504 error and sometimes seeing an error like sql timeout exceeded error. Any idea how to track this down?
Some additional info, I keep seeing this error in the logs yii\web\NotFoundHttpException: axios.min.map does not exist.
Also getting a failed POST request for /index.php?p=admin/actions/fields/delete-field
-- NEO 2.7.25
-- Asset Rev 6.0.2
-- DigitalOcean Spaces Volume 1.1.2
-- Redactor 2.6.1
-- Sprout Forms 3.12.2
-- Super table 2.5.4
-- Craft Ajaxinate 2.0.1
-- Field Manager 2.1.8


texts: Eager loading category data from a Matrix block

texts:
How might I eager load category data in a plugin? I can't seem to figure out why I can't access a category in this way:

locationOffers is a matrix block name, category is the handle of a related category field inside of the matrix block

// this adds an empty category array to each related offer
$relatedOffers = $entry->locationOffers->with(['category'])->all();
print_R($relatedOffers->category); // is empty

// this regular way works, where I can access category->title, and more,
// but is not eager loaded
$relatedOffers = $entry->locationOffers->all();


texts:
Is there a way to add an nofollow option to the rich text editor? Just like new window option.
The only thing I found is a Redactor config to make all links nofollow. But I need it optional per link.


texts: Incomplete localization of `{{ entry.postDate.diff(now)|duration }}`

texts:
In a Dutch site, when I output {{ entry.postDate.diff(now)|duration }}, the result is something like 5 dagen, 3 uren, 43 minuten, and 42 seconden. Why is the English "and" not localized? My understanding (I don't speak Dutch) is that "and" should be "en" in Dutch...

Am I missing some crucial step here? Thanks!


texts: Can a plugin manually raise another plugin's Event?

texts:
I have created an Adjuster which is attached to commerce_lineItems.onPopulateLineItem.

The discount criteria is based on validation of a completely separate coupon API, so I created a permission-less user group in order to allow my client to continue using the Commerce Discounts UI. In my adjuster, I had to override the the matchLineItem() method in order to bypass the $discount->allGroups check. I'm using Craft's httpSession to persist the criteria through the checkout process.

Everything works fine, however if the user adds a product to the cart and THEN authenticates, the discount doesn't get applied until they either a.) update the cart or b.) raise the commerce_lineItems.onPopulateLineItem event again.

I've tried adding craft()->commerce_orders->saveOrder($cart) at the end of a successful API call, however that doesn't seem to trigger the event.
Is there another event I can use that will also update the cart or can I somehow raise an already declared CEvent? I've tried everything I know including hitting actionUpdateCart() with Guzzle!

I know this is a very edge case situation, so just to (briefly) illustrate I've added a portion of my base plugin below.

public function init()
{
    require_once __DIR__ .'/vendor/autoload.php';
    $this->check_membership();
    /*
     Load Premium Member Adjusters if $is_premium_member is true
    */
    craft()->on('commerce_lineItems.onPopulateLineItem', function($event){

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

        if ($lineItem->purchasable instanceof Commerce_VariantModel){
            if ($this->is_premium_member) {
                $this->adjusters = [
                  599 => new WorkshopAdjuster
                ];
            }
        }
    });
}


texts: Best way to provide navigation similar to wordpress

texts:
What is the recommended way to setup navigation, in a similar way to Wordpress?
So that certain pages or channels can be added, and some may be excluded from the navigation.

Also, what if I want to add a sub-navigation menu on a page to show the child pages?


texts: Figuring out why my image is not working in the template

texts:
Possibly a very easy question. Let me explain my flow:

I created an asset folder (images)
I added the folder in the assets
I created in image transforms 'square' which is an image of 500 by 500px.
I added a custom field to my homepage called 'hoofdafbeelding' and added an image to it.

I call the image like so:

{{ entry.hoofdafbeelding.getUrl('square') }}

I get the following error:

Object of class Craft\ElementCriteriaModel could not be converted to string

What am I missing?! How can it be so hard to show an image?


texts: Is there any way to group Matrix blocks in the control panel (see image)?

texts:
Sorry if my question seems incomprehensible, it's my first question here so please go easy on me :) !!

I'd like to group the fields in the image in one drop-down menu where, if possible, I can add some description to each block.  So is it possible or do I need to learn plugin dev and create one of my own?


texts:
How can I loop from col2 to col4 ? Or loop by column heading handle?
Remplace {{ row.col2 }}

  {% for row in block.tableHandle %}

{{ row.col2 }}

  {% endfor %}


texts:
From within a plugin/module using PHP; is there a way to query all element types being used, including custom elements?
I know in the elements database table there is a type column that I could potentially query. But I wasn't sure if there is a native Craft method I could take advantage of instead?
In an ideal world I just need an array of all the element types:
Example:
['asset', 'category', 'entry', 'globalset', 'matrixblock', 'tag', 'user', 'single', 'event', 'product']```


texts:
I would like to reduce the size of a site's database. The reasons are as follows:

To speed up the syncing process from live to local
To hopefully speed up sql query execution time (an experiment)

I have many sections and hundreds upon hundreds of entries, all with versioning enabled. My question is, is there a way to 'trim the fat', or to put it better perhaps remove stale old version types (perhaps just keep the 5 most revisions for each entry)?

Thanks in advance for you help!


texts: Installation error - Craft.uppercaseFirst is not a function

texts:
I get two errors upon installing the latest build 2.3.2641. The first is a slide function for the "Create Your Account" window and the second is a more severe error of TypeError:Craft.uppercaseFirst is not a function which prevents installation and causes the busy gif to work continuosly as if something was about to occur.

php version 5.4.39
MySQL Version   10.0.17-MariaDB


texts:
I've tested the regex and seems to work perfectly, but when placing it within Craft it seems to throw the following error:

  preg_replace(): Unknown modifier '/'

  {% set ig = user.instagram|raw|replace('/(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_\.]+)/im') %}
  {{ ig }}


texts: Create new users with front end form and put them in a group, need help with start-elevated-session

texts:
This has been a long process that I set aside to resolve "later". Well, it's "later" and the clients wants to launch asap.

Only registered users can use this site. There are 2 groups: Manager and Employee. Users in Manager group have permission to create new users and put them in Employee group. It all works in the back end.

Using the craft front end User Registration template I added a hidden field for the group id <input type="hidden" name="groups[]" value="2"> and when I submit I get "HTTP 403 – Forbidden, This action may only be performed with an elevated session."

Some googling lead me to this craftcms github comment. I get what it's saying about the elevated session and needing to send the password again but am having issues doing it. First step is testing with hard coded values on my form submit:

$.ajax({
    method: 'POST',
    url: 'https://www.myurl.ca/',
    data: { action: 'users/start-elevated-session', password: 'xxx'}
})
.done(function( msg ) {
    alert( "Data: " + msg );
});

But nothing is alerted. So something is failing.

When I try https://www.myurl.ca/?action=users/start-elevated-session&password=xxx in a new browser tab I get "TypeError, Argument 1 passed to craft\web\User::startElevatedSession() must be of the type string, null given, called in /.../vendor/craftcms/cms/src/controllers/UsersController.php on line 234".

So it can't find password value. It's just getting null. I feel like maybe I don't know what "body params" means in the github comment. Can someone explain it like I'm 5?

Thanks
Amanda


texts: Whats the best way to save a new entry in my plugin?

texts: I have a channel section by the name of order. What I need is that every time a user clicks a button on the front end the data of the form is sent to my plugin which then uses the data to create a new entry of type order and saved in the back end. The data in the form only represents the content of the entry and the only other information we have is that the entry is of type channel and that it belongs to the order channel. What would be the best way to create the entry with the publishing date, title, id, etc all set appropriately? Can I use saveEntry of the entries service in some way?


texts: How could I go about fetching all assets that are not currently beeing used anywhere?


texts: Element API SearchQuery to search for value inside child-entries

texts:
I currently try to use the Element API to build a search. Unfortunately I'm kind of stuck.

I have a baseEntry, that has a field that references entries (let's call them subEntries) of the section subEntries, where subEntries have a field that references other entries (let's call those categoryEntries), where categoryEntries (for simplicity) only have a title.

Now I'm trying to output all baseEntrys that contain one ore more subEntrys which have one or more categoryEntrys with the title of my query... I tried to do this via endpoint.json?section=baseEntry&q=subEntryHandleFromBaseEntry:*:categoryEntryHandleFromSubEntry:mySearchTerm but that didn't work using

'endpoint.json' => function() {
    return [
        'elementType' => Entry::class,
        'paginate' => false,
        'one' => true,
        'transformer' => function(Entry $entry) {

            $items = [];
            $section = Craft::$app->getRequest()->getParam('section');
            $param = Craft::$app->getRequest()->getParam('q');
            if ($param && $section) {

                $entries = \craft\elements\Entry::find()
                ->search($param)
                ->section($section)
                ->all();

                foreach ($entries as $entry) {
                    $items[] = UrlHelper::url("{$entry->type->handle}/{$entry->id}.json");
                }
            }

            return [
                $items
            ];
        },
    ];
},

as endpoint.

Also tried narrowing it down like:

$entries = \craft\elements\Entry::find()
->section($section)
->all();

foreach ($entries as $entry) {
    $items = \craft\elements\Entry::find()
    ->search($param)
    ->relatedTo($entry)
    ->all();

    foreach ($items as $item) {
        $items[] = UrlHelper::url("{$item->type->handle}/{$item->id}.json");
    }
}

didnt work either. I'm kind of lost. I'm looking into the docs but can't seem to get it working.


texts: Using a virtual host result in internal error

texts:
I'm trying to setup a virtual host to access my craft project through ontherocks.dev, without any success yet.

www.ontherocks.dev : correct response
www.ontherocks.dev/admin : Apache 404
www.ontherocks.dev/index.php/admin : redirected to www.ontherocks.dev/admin/install with an Apache 404

I didnt "install" craft yet, which explains the redirect. Here are my config files for the virtual host :

httpd-vhosts.conf

<VirtualHost *:80>
  ServerName ontherocks.dev
  DocumentRoot "C:\wamp\www\y-lynx"
  ServerAlias www.ontherocks.dev
 DirectoryIndex index.php
</VirtualHost>

hosts file in system32/drivers/etc

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost
127.0.0.1       ontherocks.dev

Thanks for your help !


texts: Updating Asset Indexes Fails with TemplatesController Not Found Error in Craft Logs

texts:
Client wants to be able to upload a 90MB .mp4 file to a local asset folder, that understandably throws a 'General error: 2006 MySQL server has gone away'.

I uploaded the file directly to the server via FTP and attempting to re-index the assets throws an unknown error in the CP for each individual asset and crashes the server.

Craft Log reads this error for each asset in the index:

2019-07-10 13:20:43 [-][-][-][error][yii\web\HttpException:404] yii\web\NotFoundHttpException: Template not found: 403.shtml in "path"/craftcms/cms/src/controllers/TemplatesController.php:87

With either 403.shtml or 500.shtml being the only difference between errors.

There are ~60 assets, all under 8MB, except one other 200MB .mp4 file.

My suspicion is that the server only has 512MB of RAM and it's crashing while attempting to process 300MB worth of data from just two of the 60 assets, as the entire site goes down in the attempt.

PHP Options max_upload memory_limit are 256MB, post_max_size is 128MB, and max_execution and max_input_time time are 240s.


texts: Sprout Forms: creating additional text inputs in radio and checkbox labels

texts:
In a customized Sprout Form field, is it possible to have radio buttons and checkboxes with a value of other have an additional text input in the label? This text input would presumably need to be tied to a separate text field in Sprout Forms which would not render with the other normal plaintext fields.

Is there some way to create a custom field that would make it possible to add the boolean radio/checkbox and input together with something like a matrix? We have multiple "other" + text input fields on the page we're trying to create. No set of options will ever have more than one other option.

The resulting markup might look something like this:

{% if type == 'radiobuttons' %} {# Or 'mycustomradiobuttontype' #}

    {%- for key, option in options %}
      {%- set label = (option.label is defined ? option.label : option) %}
      {%- set value = (option.value is defined ? option.value : key) %}
      {%- set checked = (value == selectedValue) %}

        <input type="radio"
          {%- if id %} id="{{ id }}-{{ loop.index }}"{% endif %}
          {%- if name %} name="{{ name }}"{% endif %}
          {%- if value %} value="{{ value }}"{% endif %}
          {%- if checked is defined and checked %} checked{% endif %}
          {{- dataAttributes -}}>

          {%- if label is defined %}{{ label|raw }}{% endif -%}
          {% if value == 'other' %}
            <input type="text" name="TODO" value="TODO">
          {% endif %}

    {% endfor %}

{% endif %}


texts:
We are implementing fast CGI cache (not not the proxy version) but it seems that our upstream cache hit is always MISS. If we hijack public/index.php by not running require_once($craftPath."/vendor/autoload.php"); and simply echo time the cache gets created and hit. We noticed that Craft adds cache control, pragma and expires headers by default. We tell FastCGI to ignore the headers with no luck.

Does Craft do anything to not allow FastCGI caching?

Thanks!

location ~ \.php$ {
    fastcgi_ignore_headers X-Accel-Expires Expires Cache-Control;
    fastcgi_cache cacher;
    fastcgi_cache_valid 200 60m;
    fastcgi_cache_methods GET HEAD;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}


texts: In the front-end, I create a form and submit the data to backend. In the controller, if got some errors, I would like to redirect to the previous page with some information.


texts:
Some of my entries have the same entry.title. At the frontend, I would like to display these entries only once. This works with the following code:

{% set entries = craft.entries().section('produkte').relatedTo(category) %}
{% set existingtitle = [] %}
 {% for entry in entries %}
  {% if entry.title not in existingtitle %}
    {{ Display the Results }}
  {% endif %}
  {% set existingtitle = existingtitle|merge([entry.title]) %}
 {% endfor %}

My question is: How can I then paginate these results? For example 9 entries per page?
If I paginate before the "if" condition gives me not the required result.
Any help or tips are highly appreciated!


texts: How to determine source of Elements save event

texts:
We need to send notification emails when entries of a particular type are created, updated, or enabled/disabled. The entrypoint for this happens in a module's init() method:

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function (Event $event) {
    // do stuff
}

We recently updated to Craft 3.3.0, which resulted in many many many emails being sent. I think these have something to do with queue tasks that are generated as a result of system updates. During the update, the craft_queue table contains many rows. The first row's description is "Updating entry drafts and revisions" and the many subsequent rows show a description value of "Updating element slugs and URIs".

First, is it correct to assume that some system updates trigger queued resaves of all entries?

Second, we need to prevent the notification emails from being sent unless the save event is triggered as the result of a user action. I see the sender property of ElementEvent, but it seems that that has to do with the current method and doesn't bubble up the event chain.

We've thought about disabling versions on these entries, but that feels more like a bandaid.

Is there a way to determine the originating source of an ElementEvent's save event? If so, is that the best way to gain more control over when these notification emails are sent? In general, I'm wondering if we can detect whether an element is being saved as the result of a system update/queue task vs a manual user action.


texts: How to deal with too many folders in asset source?

texts:
I've got a channel with over 1,000 pages, and the entries for this channel have an asset field (for images). I set the asset field to use {slug} as the folder name (because otherwise the content author would have to wade through thousands of photos to find the ones for a certain entry), and so now I have thousands of folders in the asset source's folder in the filesystem. (Just using the server filesystem here, not S3/rackspace/etc).

Problem is, now when you try to expand that asset source in the asset manager sidebar, the page just crashes. Running latest version of Craft (2.6.something), PHP 7, on a beefy VPS server... client is most recent version of Chrome on a modern MacBook with plenty of RAM, etc... so this is not a problem of too few server or browser resources.

My question is: assuming there is some practical limit to the number of folders that the asset manager UI can deal with (which is what, by the way?)... what's a good strategy for me to handle this situation? Each of these thousand+entries will have at least one image, some up to a dozen (this is a fairly large product catalog site). Is there a better way to organize the folder structure, or perhaps a better way to dynamically generate the sub-folders (as opposed to {slug})?


texts: Using Global Variable as Price for Variant

texts:
I'm trying to set the price of the item being added to the cart by a global variable, which is a number field. Here's what I have:

craft()->on('commerce_lineItems.onPopulateLineItem', function($event)
{
    $lineItem = $event->params['lineItem'];
    $globalPrices = craft()->globals->getSetByHandle('defaultPrices');
    $itemPrice = var_dump($globalPrices->fontStylePrice);
    $lineItem->price = $itemPrice;

This just results in a $0 price being set, and not the value from the Global Variable. But again, $lineItem->price = 25 works fine. Any suggestions?


texts: Why does a cart get added with no Order Number?

texts:
Sometimes, the cart gets added without the id as below.

Any ideas, please?
(Craft Commerce version is 2.2.19)


texts: Is it safe to delete unused matrix field tables from the DB?

texts:
During design/dev I created a bunch of matrix fields that I have since decided not to use. I have deleted the fields, however, I notice that the matrix tables are still in the database. Is it safe to delete these manually, or is there some other cleanup that needs to happen as well (i.e. references within another table, etc.)?

Update: The problem is caused when changing the fieldtype from a matrix field to another field type, rather than deleting the field altogether, and creating a new one. Even if the field is subsequently deleted, the matrix tables will still remain, which results in orphaned data in the DB.