texts: Sprout Forms + Email - internal server error

texts:
Sprout Forms 2.5.1
Sprout Email 3.0.3

I am getting the error "Internal Server Error - Illegal string offset 'template'"

I have updated the template file to use email variable instead of entry for the html and text content respectively.

Stack trace:

******************************************************************************************************
    2017/11/06 20:38:21 [error] [php] Illegal string offset 'template' (/home/forge/www.sitename.co.uk/craft/plugins/sproutemail/services/SproutEmailService.php:212)
    Stack trace:
    #0 /home/forge/www.sitename.co.uk/craft/plugins/sproutemail/services/SproutEmailService.php(69): Craft\SproutEmailService->error()
    #1 /home/forge/www.sitename.co.uk/craft/plugins/sproutemail/services/SproutEmailService.php(468): Craft\SproutEmailService->renderObjectTemplateSafely()
    #2 /home/forge/www.sitename.co.uk/craft/plugins/sproutemail/integrations/sproutemail/mailers/SproutEmail_DefaultMailer.php(99): Craft\SproutEmailService->renderEmailTemplates()
    #3 /home/forge/www.sitename.co.uk/craft/plugins/sproutemail/services/SproutEmail_NotificationEmailsService.php(487): Craft\SproutEmail_DefaultMailer->sendNotificationEmail()
    #4 /home/forge/www.sitename.co.uk/craft/plugins/sproutemail/services/SproutEmail_NotificationEmailsService.php(383): Craft\SproutEmail_NotificationEmailsService->relayNotificationThroughAssignedMailer()
    #5 /home/forge/www.sitename.co.uk/craft/plugins/sproutemail/services/SproutEmail_NotificationEmailsService.php(359): Craft\SproutEmail_NotificationEmailsService->handleDynamicEvent()
    #6 unknown(0): Craft\SproutEmail_NotificationEmailsService->Craft\{closure}()
    #7 /home/forge/www.sitename.co.uk/craft/plugins/sproutemail/services/SproutEmail_NotificationEmailsService.php(298): call_user_func_array()
    #8 /home/forge/www.sitename.co.uk/craft/app/framework/base/CComponent.php(567): Craft\SproutEmail_NotificationEmailsService->Craft\{closure}()
    #9 /home/forge/www.sitename.co.uk/craft/plugins/sproutforms/services/SproutFormsService.php(79): Craft\SproutFormsService->raiseEvent()
    #10 /home/forge/www.sitename.co.uk/craft/plugins/sproutforms/services/SproutForms_EntriesService.php(246): Craft\SproutFormsService->onSaveEntry()
    #11 /home/forge/www.sitename.co.uk/craft/plugins/sproutforms/services/SproutForms_EntriesService.php(195): Craft\SproutForms_EntriesService->callOnSaveEntryEvent()
    #12 /home/forge/www.sitename.co.uk/craft/plugins/sproutforms/controllers/SproutForms_EntriesController.php(162): Craft\SproutForms_EntriesService->saveEntry()
    #13 /home/forge/www.sitename.co.uk/craft/app/framework/web/actions/CInlineAction.php(49): Craft\SproutForms_EntriesController->actionSaveEntry()
    #14 /home/forge/www.sitename.co.uk/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams()
    #15 /home/forge/www.sitename.co.uk/craft/app/framework/web/CController.php(286): Craft\SproutForms_EntriesController->runAction()
    #16 /home/forge/www.sitename.co.uk/craft/app/framework/web/CController.php(265): Craft\SproutForms_EntriesController->runActionWithFilters()
    #17 /home/forge/www.sitename.co.uk/craft/app/framework/web/CWebApplication.php(282): Craft\SproutForms_EntriesController->run()
    #18 /home/forge/www.sitename.co.uk/craft/app/etc/web/WebApp.php(823): Craft\WebApp->runController()
    #19 /home/forge/www.sitename.co.uk/craft/app/etc/web/WebApp.php(287): Craft\WebApp->_processActionRequest()
    #20 /home/forge/www.sitename.co.uk/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
    #21 /home/forge/www.sitename.co.uk/craft/app/index.php(62): Craft\WebApp->run()
    #22 /home/forge/www.sitename.co.uk/public/index.php(19): require_once()
    REQUEST_URI=/contact-us


texts: Search/return entries with custom field length less than 200

texts:
So I'm not sure this is possible with the entries search param but I'm trying to return entries where a field (rich text) has fewer than 200 characters. This is obviously horribly wrong but something like...

{% set params = {
    limit: 3, order: 'RAND()', search: 'quote:|length < 200', section: 'quotes'
} %}

Any help much appreciated!


texts: Did a crtitical update now getting errors

texts:
My customer clicked the update button and updated number 2.6.2791

now we are getting errors trying to save new images to the site.

Internal Server Error

Could not resolve the subpath “project-images/{slug}”.

I wonder if this is a permissions thing?

regards

Hugh


texts: What are my caching options when using CraftQL and React?

texts:
I’m experimenting with the CraftQL plugin and React with Craft 3, and I’m really liking the similar syntax to standard Twig element queries, and the fact I don't need to manually configure API endpoints as I would if I was to set up a REST API using the ElementAPI plugin.

However, I'm not certain how I can cache data using this approach to prevent unnecessary database calls, and the scalability of such a solution.

Using a REST API I'd be able to cache the endpoints using Nginx or Varnish, but this doesn't seem to be an option using GraphQL. There seem to be several options for GraphQL application-level caching in the Node ecosystem (e.g. https://github.com/apollographql/apollo-cache-control).

Are there any options for caching database queries using the Yii Query Caching functionality (http://www.yiiframework.com/doc-2.0/guide-caching-data.html)?

Or any other techniques that may help an implementation like this scale?


texts: Craft and AJAX page transitions - how to exclude local hash links from executing AJAX?

texts:
I've got a website in development with new pages loaded via AJAX instead of traditional page loads. Most links on the site will use AJAX to load a new page, however there are some links I need to exclude from this behaviour. For example, local hash links that simply scroll you down to an anchor on the same page. Or, links to PDF files that are hosted locally but should obviously not be loaded via AJAX. I have enough control over the HTML that I can simply add a class to these links that I want to exclude, such as .local-anchor, or .pdf. The code I have effectively excludes these links if you directly load the page the first time, however any time the page is loaded via AJAX my exclusion no longer works. The .local-anchor links and any others that should be excluded are still somehow executing the AJAX functions. Example of the relevant JS code:

$(document).on("click", "a:not('.local-anchor, .pdf')", function(e) {
    var href = $(this).attr("href");

    // check that it points to this domain
    if ( href.indexOf(document.domain) > -1 || href.indexOf(':') === -1 ) {
      history.pushState({}, '', href);
      loadPage(href);
      e.stopPropagation();
      e.preventDefault();
    }
  });

You can see this live page (in development) here: http://dma.nz/practice/

The links:

Our approach to design
The architectural process
Awards + Publications
Contact

Scroll you to anchors further down the same page and should be excluded. Yet if this page is loaded via AJAX (test by navigating to one of the other main nav links on top right and then return to Practice) then these links are triggering AJAX to reload this same page which screws things up.

How do I need to amend this JS to make sure they are ALWAYS excluded?

----------- UPDATE -----------

As per August's suggestion I tried removing the single quotes around the :not, as well as adding an extra if statement to double check. Neither of these solutions work. My current JS is looking like this:

$(document).on("click", "a:not(.local-anchor, .pdf)", function(e) {
    var href = $(this).attr("href");

    if ( !$(e.target).is('.local-anchor, .pdf') ) {
      // check that it points to this domain
      if ( href.indexOf(document.domain) > -1 || href.indexOf(':') === -1 ) {
        history.pushState({}, '', href);
        loadPage(href);
        e.stopPropagation();
        e.preventDefault();
      }
    }
  });

The :not exclusion is working. If the page is first loaded directly (not via AJAX) then those local anchor links do as they should. However if the page is loaded via AJAX then the exclusion stops working. Whether it's in the form of :not on the selector and/or an if statement to catch those classes.

I'm baffled here. Can't understand why that exclusion would work in one case but not the other. Any other ideas?


texts: Error when trying to access 'variables' inside the PDF template in Craft Commerce

texts:
I'm trying to include the custom image field inside the PDF file of Craft Commerce.
I added the following code to the module:
use craft\commerce\events\PdfEvent;
use craft\commerce\services\Pdfs;

  Event::on(
            Pdfs::class,
            Pdfs::EVENT_BEFORE_RENDER_PDF,
            function(PdfEvent $event) {
                // Modify `$event->order`, `$event->option`, `$event->template`,
                // and `$event->variables` to customize what gets rendered into a PDF;
                // or render your own PDF and set its string on `$event->pdf`
                // ...

                $event->variables['productImages'] = array_map(function ($value) {

                    $variant = Plugin::getInstance()->variants->getVariantById($value['purchasableId']);

                    $variantImage = $variant->getFieldValue('productImage')->one();

                    return $variantImage ? $variantImage->getUrl() : null;
                }, $event->order->lineItems);
            }
        );

Dumping the variable actually gives me the result, so it should be accessible:

But when I'm trying to access the field 'variables' inside the template, it downloads the pdf file with an error text inside the file:

Can you tell me please what can be the cause of the issue here, or I'm doing something wrong? Thank you


texts: How do you route an entry or category URI to a plugin controller?

texts: Craft's documentation states: "If the URI matches an entry’s or category’s URI, the section’s/category group’s template will get loaded".  Instead of loading the template, how can I set the route to run an action instead?  In config/routes.php, I set 'entryurl' => array('action' => 'action/path'), but this does not work.


texts: Transitioning local Craft site to AWS EC2

texts:
First post here and I am a complete newbie when it comes to Craft and any kind of server config but I am trying to learn.

I am trying get my Craft site that I built locally up to a server today.

I followed a pretty detailed guide about setting up EC2 for craft here:
https://solspace.com/blog/spinning-up-a-craft-cms-development-site-on-amazon-ec2

The issue I'm running into is that when I go to my EC2 URL I'm getting a

  "Service Unavailable

  Our site is temporarily unavailable. Please try again later."

Then trying to login, I get a

  "Craft can’t connect to the database with the credentials in
  craft/config/db.php."

With devmode on and looking at the console, its throwing me this error:

  "install:82 [16:36:40.799][error][exception.Craft\DbConnectException]
  exception 'Craft\DbConnectException' with message 'Craft can’t connect
  to the database with the credentials in craft/config/db.php.' in
  /var/www/craft/app/etc/behaviors/AppBehavior.php:855"

So clearly Craft is unable to find the database that I created locally but I'm not really sure how to fix this.

My db.php

// The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
'server' => 'localhost',

// The name of the database to select.
'database' => 'mydatabasename',

// The database username to connect with.
'user' => 'root',

// The database password to connect with.
'password' => 'root',

// The prefix to use when naming tables. This can be no more than 5 characters.
'tablePrefix' => 'craft',

Any help would be greatly appreciated!


texts: Charge plugin not showing errors on payment fail

texts:
I am using the Charge plugin.  They payment process happens in a modal.  If I enter in a bad number from one of the stripe test numbers and submit, when the payment fails the modal goes away and no errors are shown.  The errors are not getting loaded into the div set for payment errors.  I do get the errors before form submit but that doesn't help with a bad card or something.

I am getting the error in the cp and can see it but I cannot find anything in their documentation to log this to the view.

I have read here quite a bit and also viewed thier example and I am not doing anything different.  But for some reason I cannot get the declined error to show on the entry page once it returns.

this is the script

<script>
  (function () {
    Stripe.setPublishableKey('{{ craft.charge.getPublicKey() }}');
    $(this).charge('#charge-form', '#payment-errors', '.charge-indicator');
  })();
</script>

Form is almost exactly the same as their example except that I have a few custom fields (those are not the fields with errors in them).

If anyone has any experience with this plugin that can shed some light on how to return a declined card error or any errors that occur after form submission it would be greatly appreciated.

I see this in the cp


texts: Upgraded to Craft 3 and lost my Commerce Gateways

texts: I upgraded to Craft 3 and I went to my payment gateways and I have the old ones in there with no details such as keys. And my only gateway options are Dummy and Manual. I know there were changes such as .commerce being deprecated in some instances, so was this another change that I missed?  Do I have to buy a plugin for Commerce or make my own now?


texts:
I'm trying to setup some Global fields in a migration.

I'm using the SuperTable Field from verbb which is similar to a matrix field.

I'd like to add several rows during migration but can't seem to get the combination right in order to set the field values.  Can someone help me out, what I've got so far is the following:

   $globalSet = Craft::$app->globals->getSetByHandle("myGlobals");

   $globalSet->setFieldValues([
            'siteName' => "The Website",
            'siteCustom' => [
                'new1' => [
                    'type' => 'superTableBlockType',
                    'fields' => [
                        'firstField' => "some value",
                        'secondField' => "some other value"
                    ]
                ]
            ]
        ]
   );

   Craft::$app->globals->saveSet($globalSet);


texts: How can I programmatically add a tab to entry type?

texts:
I'm trying to create a plugin that adds a tab full of fields to entry types but I can't seem to get it working. I tried assembleLayout but that replaced all the fields with my new fields rather than adding a new tab to them.

I'm trying different combinations of FieldLayoutTabModel->setFields() but that throws an error about a fieldId property which leads me to believe I don't quite have the data types right. Any help would be appreciated.


texts:
Is there a max image file resolution set up in Craft CMS that can be uploaded?

I'm trying to upload a series of .jpg images in a Matrix to create a gallery, and I've noticed I'm not able to upload any file that is over somewhere around 4000px in width.

At first I believed it was something to do with the PHP file upload limit, but I'm able to upload .jpg files that were over 5mb with a 2880px width.


texts: Site will not load. Asking me to save "login" as a file

texts:
What would make a site want me to download the index.php when viewed?  I downloaded the database and all files from a staging server where site was fine.  When I go to any site URL on local machine it prompts me to save "login".  The contents of the saved file are the public index.php.  Is there some setting or cache I need to clear?  I have 10 other sites working local with no issue.

Running latest version of Craft 2.6.2789 on cPanel EasyApache4 server running the new PHP Handler with PHP7 selected for the site..

It actually is asking me to save the file using whatever the last segment is.  Here are contents from my htaccess file:

    RewriteEngine On

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

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php70” package as the default “PHP” programming language.

  AddType application/x-httpd-ea-php70 .php .php7 .phtml

# php -- END cPanel-generated handler, do not edit


texts:
We use an automated deploy system when developing with Craft.

We have a deploy user "deploy" and a web server user "www-data"

Deploy is a member of the www-data group.

Our first few deployments went fine but when we hit the point where the system started deleting old version (15 or so in) we started getting errors where it couldn't delete the old files properly.

On examination folders created here - /craft/storage/runtime/compiled_templates have the permission drwxr-xr-x so only www-data can edit/write to them.  Is there anyway we can make this group writable when created rather than having to do a manual clean up?


texts: Is there a logarithm function in Craft or Twig?

texts:
I searched the Craft and Twig documentation, although I did not find any information about a logarithm function (http://php.net/manual/en/function.log.php ). I am trying to calculate the loan amortization formula below in Craft / Twig:

{% set payoffTime  = -(ln(1 - ((128000 * '.05') / 1260)) / ln(1 + '.05')) %}

The numbers will be replaced with field handles once I can get the 'ln' function working. I'm not even sure if the formula is 'exactly' the way it should be yet - just trying to find a way to get logarithms working in Craft, and then go from there with testing, etc. :)

To give some background on the goal of this: it will calculate the amount of time it will take to pay off an amoritized loan, (mortgage, etc) based on the amounts the user has already submitted (loan amount, interest rate, extra payments, etc.) Also, this can't be done in Javascript - it needs to be in Craft since it's calculated from user data.

Thank you in advance for any info you can give about the logarithm function in Craft / Twig.

Thanks!


texts:
Does anyone have an idea how I can add columns in the entries overview? Columns with the title of the fields that exist in the page and are filled with content.
Thank you


texts:
In my general config I have enabled URLS to have trailing slashes.

'addTrailingSlashesToUrls' => true,

This is working for products and entries. But it is not working on Categories. Category links are not adding trailing slashes.

Is there some additional config I need to add/setup or is this a bug?


texts: Search then loop through files that were uploaded via FTP

texts:
Is it possible to search a server folder containing image and video files that were previously uploaded via ftp and then loop through those files in the entry template?

Each entry has a unique Log ID number field which is also part of the image or video filename.

Example:

Log ID: 12345
Image filename: 12345-[8374]-img-01.jpg
Image filename: 12345-[8374]-img-02.jpg
Video filename: 12345-[8374]-vid-01.mp4
etc...

Conceptually on the template page...

Grab the entry LogID field (ex. "12345")
Search the media server folder for all filenames that begin with the LogID
Display all of the found images and videos

I found this question which is very similar but I don't have the skills to write a plugin.


texts: What is CDbException Error: SQLSTATE[42000]: Syntax error or access violation while moving a site to remote?

texts:
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #28 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'site.structureelements.root' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by.

The site is working locally through MAMP, and on a remote apache dev server. I have an nginx server built for shared hosting through Laravel Forge. All of the PHP settings are identical, and I used the database backup from the dev site.

I removed all of the tables and the standard craft install worked fine.


texts: Is it possible to write a custom GraphQL resolver for Craft?

texts:
I am currently editing a headless VueJS + Craft + GraphQL website and the client asks me to add a Recipe section. I found https://plugins.craftcms.com/recipe which is great, but when I add the field to my section and I write my GraphQL query, it doesn't seem to be able to resolve the field type of Recipe.
Here's what I get in "debugMessage" from the GraphQL api.
Expected a value of type \"String\" but received: instance of nystudio107\\recipe\\models\\Recipe
Now, if I understand right, the problem either that I'm not specifying the type correctly when I query my content or that I would need to write a custom resolver to "unpack" the plugin's class into scalar types. So that brings me to the question: is it possible to hook into Craft's resolving mecanism and unpack custom fields?
I also am already using the elements api for some other endpoints and that might be what I end up doing to solve the problem, but I'd love to stay in GraphQL for consistency if possible.
Thank you everyone for your time!
--
For reference, here's my query and the "recetteContenu" field is the recipe field.
let query = `
  query FetchEntries($lang: [String], $slug: [String]) {
    entry (section: "recette", site: $lang, slug: $slug) {
      title,
      ... on recette_recette_Entry {
        category: recetteCategory { id, ... on recettes_Category { title } },
        recetteContenu
      }
    }
  }
`;


texts: Is there a way to specify a different template directory from the general config?


texts: Discount Code applies to cart successfully but doesn't do anything. Am I missing something?

texts: Standard 10 dollars off discount setup.  Although it says it is applied, it doesn't give me any kind of a discount.  None of the discounts work, I've made multiple and tried different options but it still doesn't work.  Any ideas?


texts:
I am using docker for my local webdev and am new to Craft CMS.

Currently I have a simple setup running, however, my Live-Preview does not seem to work and throws the "Template not found" error.
Yet, when I surf to the same location in my browser all seems dandy and fine.

I'm sure I'm overlooking something simple, but can't seem to find it.


texts: Is it possible to make Craft/Twig throw 404 if a template can't be found?

texts:
Attempting to include a template that doesn't exist throws HttpStatus 500 – Craft\TemplateLoaderException – Unable to find the template “{template}”.

This is usually fine and what you want, but is it possible to override this behaviour somehow, and make Craft throw a plain' old 404 instead?


texts: Display entries which share tags (2 or more)

texts:
I need to be able to display entries (within one section) that share keywords. I don't care what the keywords are, just want to display the entries based on 2 or more shared keywords.

Anyone know how to go about this?


texts: My `for` loop has fallen...and it can't get up

texts:
I want my
 to show a single tag representing all "active" entries ( "active" using a custom lightswitch field in the entry: fellowStatus.

Each tag is a year (e.g. 2014, 2010, etc)

E.g. if there are no "active" entries with the tag 2017, it should not display.

The code block below spits out only tags where entries are "active"
BUT...
It spits out duplicates of each tag depending on how many entries are using it. (e.g. It displays 8 instances of 2015 instead of 1)

{% for entry in craft.entries.section('fellows').limit(null) %}

  {% set tags = craft.tags.relatedTo(entry).limit(1).find() %}
  {% set active = entry.fellowStatus %}

    {% if entry.fellowStatus == 0 %}

      {% for tag in tags %}

            {{ tag.title }}

      {% endfor %}

    {% endif %}

{% endfor %}


texts:
I have two menus.
One with countries, one with navigation.

Navigation menu must to have a index link of a active locale.
So if I'm at example.com/uk/section and I go to navigation menu and click at index link, I get index of /uk

My countries menu code is:

{% set locales = ['en', 'en_gb', 'sk'] %}
    {# Check if locale equals the requested page locale #}
    {% if locale == craft.locale %}
        {% set current = true %}
    {% else %}
        {% set current = false %}
    {% endif %}
    {% set locale = craft.i18n.getCurrentLocale() %}
      {% for locale in locales %}

           {{ craft.i18n.getLocaleById(locale).name }}

When I try to copy

{{ craft.i18n.getLocaleById(locale).name }}

and put it to my navigation menu I get

Internal Server Error    array_key_exists(): The first argument should be either a string or an integer

Is it fixable or any other way around?


texts: How to include and use native imagemagick on server in Craft?

texts:
Craft v2.6.x

I want to write a plugin to grab thumbnails of PDFs.

I have my stand alone php code with imagemagick on server working like this:

$im = new Imagick();
$pdf = 'assets/documents/resources/after-release-impact-seafarers.pdf';

$im->setResolution(300,300);
//$im->setCompressionQuality(95);
//$im->scaleImage(200,0);
$im->readimage($pdf . '[0]');
$im->setImageFormat('jpeg');
//$im->resizeImage( 640, 905, imagick::FILTER_POINT, 1 );
//$im->resizeImage( 400, 565, imagick::FILTER_POINT, 1 );
$im->resizeImage( 180, 232, imagick::FILTER_POINT, 1 );

$im->writeImage('1a2w12thumb.jpg');
$im->clear();
$im->destroy();

However, how can I load imagemagick - which works on the server in my PDF thumbnail plugin class function?
I have tried:

    $im = new \Imagick();

    $im->setResolution(300,300);
    $im->readimage($pdfAsset . '[0]');
    $im->setImageFormat('jpeg');
    $im->resizeImage( 640, 905, imagick::FILTER_POINT, 1 );
    $im->writeImage($pdfAsset->writepath.$pdfAsset->filename . '.jpg');
    $im->clear();
    $im->destroy();

But none of the functions for imagemagick work:
Eg. error i get is Class 'Craft\imagick' not found

Is this a namespace issue with the imagine library? (I sound like I know what I am talking about but I am not sure I do!)

How to include/ use native imagemagick on server in Craft?


texts: Why are gif transform file sizes very large?

texts:
Our site makes use of gifs to enable the client to upload basic animating images. Any asset field on the site can be jpg, png or gif, and the site makes significant use of transforms for responsive imagery.

Transforms for jpgs and pngs are working fine, but the gif transforms are coming out huge (significantly bigger than the original file size), and at the point of transform generation, the server is grinding almost to a halt, with most of the Generating pending image transforms tasks eventually stalling.

Image 1

Natural: 2.4MB
400px Constrain: 4.3MB
800px Constrain: 19.2MB
1200px / 1600px / 2400px Constrain: Failed

Image 2

Natural: 5.4MB
None of the transforms for this seem to be being created now (I previously had to remove it because of the detrimental effect of the transform process on the server but have just tried re-uploading and visiting the page), but one of these was something like 37MB!

Technical Details:

Craft 2.6.2967
imageDriver is set to imagick (which is reported to be available under Utilities / Server Info)
defaultImageQuality is set to 70
PHP Memory Limit is set to 256MB (had previously been 512MB, which may explain why none of the transforms for Image 2 are being created any more)
PHP Max Execution Time is set to 90 seconds


texts: How do I set Redactor formatting button to wrap selected text in two tags? ...

texts:
Is it possible to set Redactor button to wrap my code snippets inside two tags?

...

This is what I have so right now.

formattingAdd: [
    {
        tag: 'code',
        title: 'Code Inline'
    },
    {
        tag: 'pre',
        title: 'Code Well'
    },
    {
        tag: 'mark',
        title: 'Marked'
    }
]

But some scripts and Bootstrap wants it wrapped in both of the tags.


texts: Query entries with latest video field containing a URL

texts:
I would like to set up a query to find the latest news article that has a video attached to it ('video' is a matrix field with a block type that is also called 'video' and a field called 'videoUrl').
I know I can use the following query, but I get stuck defining searchQuery. Or is there another method?
{% set results = craft.entries()
.search(searchQuery)
.one() %}


texts: How to override filename saved in Sprout Forms?

texts:
After a form is saved I need to concatenate together the {{proposalCompanyName}} handle with the {{proposalFileUpload}} handle so that the saved filename in the Assets folder is proposalCompanyName.proposalFileUpload.extension.  This is the event code in my module/plugin I've figured so far:
Event::on(Entry::class, Entry::EVENT_AFTER_SAVE, function(Event $event) {

            if (Craft::$app->request->isSiteRequest)
            {
                $formEntryElement = $event->sender;
                $userSubmittedName = Craft::$app->fields->getFieldByHandle('proposalCompanyName');
                $userSubmittedFilename = Craft::$app->fields->getFieldByHandle('proposalFileUpload');
                $concatFilename = $userSubmittedName.$userSubmittedFilename;

                $formEntryElement->set($concatFilename => $userSubmittedFilename);
            }

        });

Thank you for any input or criticisms.


texts:
I have created a Craft CMS site on a VPS Server running CentOS 7. I have a file setup on the public_html like this: -

cms

craft
public

app (this is running a Symfony Framework Web App and runs from app.example.com perfectly)

Now I have the site working from www.example.com but when I login to the back office all of the links say... https://www.example.com/cms/public/admin/dashboard. I want to remove cms/public from the URL links in the back office.


texts: Craft Commerce: Calculating (Product + Shipping) + Tax?

texts:
There is an option when setting up Tax Rates to apply the tax to "both (item + shipping costs)" however when testing on the front end the shipping cost is added after tax is applied to the product and no tax percentage is applied to the shipping cost.

The total amount payable is (Product + Tax) + Shipping. I want (Product + Shipping) + Tax.

Is there more configuration needed so that the adjustments show correctly at checkout and the customer is charged the right amount?


texts: Let admin create price offers/quotes for customers in Commerce

texts:
Does anyone know of a plugin (or coming functionality in Commerce 3 or 4) that allows admin to create price offers/quotes for a customer and then send it to the customer's email for review?
Scenario
I am talking to a customer on the phone. He wants a price on a specific product/configuration. I add the desired products to the customer's basket, save it as a price offer/quote. I am allowed to adjust prices. I send the quote to the user. The user can access the quote and easily accept or reject it.
Feature request
I added this as a feature request here: https://github.com/craftcms/commerce/issues/1156


texts: Display entries tagged with specific tag(s) before other entries

texts:
What I'm trying to accomplish is looping through a collection of entries and have them display (with pagination) in the following order:

entries tagged as Featured in alphabetical (title) order
entries tagged as New in alphabetical (title) order
all remaining entries in alphabetical (title) order

The following worked:

craft.entries({ order: 'featuredLightswitchField desc, title asc' })

However it fails to work if you try to use two lightswitch fields (e.g. featured and new) in addition to the title ordering, and I'd prefer to keep things tag-based instead of needing to add lightswitch fields.

I also attempted at creating a custom array of entry IDs in the proper order and passing it to craft.entries.id(), however I can't find a way of keeping the entries in the order of the array passed to craft.entries.id().

craft.entries({ id: [3, 1, 2] })
// can't find a way to keep entries in [3, 1, 2] order.

If there was a way to order the entries based off the id array that would solve the problem, unless there's a better solution.

Can provide additional information if my explanation is insufficient.


texts: Internal Server Error when updating slug

texts: I'm getting an internal server error when I try to update the my entry's slug on prod, but not on dev or locally. It's happening across entries, it doesn't seem to be specific to a certain entry. Any ideas why this might be happening?


texts:
How can I find entries with at least 1 image?

{% set category = craft.categories.group('storyCategories').slug(catSlug).first() %}

{% set params = {
  section : 'stories',
  order : 'postDate desc',
  relatedTo: category,
  limit : '4'
} %}
{% set stories = craft.entries(params).find() %}

I have this, but am not sure how to only get stories entries when the story has an image.


texts: Way for clients to edit translation file(s) in control panel?

texts:
We have some navigation links being translated via the /translations folder but the client needs the ability to change them too...

Is there a way to make the translations editable from the control panel?


texts:
I've looked everywhere for this functionality and am very surprised that I can't find it...

Is there a plugin that allows auto posting of entry content to Facebook/Twitter/Other social media channel when the user hits Save?

If there isn't, then I'll build one.


texts:
I'd like to set a user defined order for a Categories field. For example, categories are:

Cat A
Cat B
Cat C

I'd like to give the ability for users to drag and drop the order, to say:

Cat B
Cat A
Cat C

What is the best way to handle this?


texts: Get Commerce 2's Stripe subscription planData as object

texts:
How do I access a subscription plan's planData? Maybe as an object? I'm using Commerce 2 with the Stripe gateway.

For example:

{% set plans = craft.commerce.getPlans().getAllPlans() %}
{% for plan in plans %}
    {{ dump(plan.planData) }}
{% endfor %}

planData looks like JSON stored as a string. How do I access its data (amount, trial_period_days etc.) on the front end?

Does this need to be handled by a custom plugin? Seems like something that should be available out of the box. Hopefully I just over looked it.


texts: Can you store cropped cloud assets locally?

texts:
Currently I'm seeing them cropped and stored on the remote bucket.

Is there a way to force them to be stored locally and retrievable via an Asset URL method?


texts:
I am getting duplicate content issues because both www and non-www are being loaded.
My htaccess has the standard force https as all my other sites but it isn't working.
# START Force https
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{HTTP_HOST} ^(www\.)?geniusesforhire\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.geniusesforhire.com/$1 [R=301,L]
# END Force https

Could anything in Craft be causing this or is anything in Craft able to fix this?


texts: map values from checkbox field into category field using SQL

texts:
In a project I have a checkbox field called gradeLevels with 3 options (k-5,6-8, and 9-12).

Due to design changes, I need to convert this field into a category field. I've made a new category with the same names (k-5,6-8, and 9-12), but I already have data in all of the entries that uses the old checkbox field.

I poked around in mysql and listed all the columns in craft_fields table, but I don't see the newly created categories field in the list, or any categories/entries field for that matter. I'm guessing associations are stored in a different manner?

Is there a possible way using mysql to map all the string values in the check box fields into the corresponding category in the categories field?


texts: Home page won't load without 'index.php'

texts:
On a fresh install of Craft 2.3.2644, using the hostname alone, example.com returns an error, "The page cannot be displayed because an internal server error has occurred".

If I include /index.php (example.com/index.php), then the expected index template is returned, displaying the "Welcome to..." entry.

However, example.com/news returns the news template correctly, even without index.php in the URI.

Craft 2.3.2644
Windows Server 2008 R2
IIS 7.5

The web.config file included with the Craft install is present at web root.

What am I missing?


texts:
I have an archive of exhibitions with entries grouped by year. The order of the groups should be descending, the order of the entries within the group should be ascending.

For example: The order of the years should be 2018, 2017, 2016, …
The entries within the group 2018 should start with the first exhibition of the year and end with the last one.

Here is my code:

{% set archive = craft.entries.section("exhibitions").order('dateStart desc').dateEnd('<' ~ now).limit(null)  %}
{% set archiveGrouped = archive|group('dateStart.year') %}
{% for year, entriesInYear in archiveGrouped %}

{{ year }}

    {% for entry in entriesInYear %}

And the link to the Website: https://kunsthausbaselland.ch/en/ausstellungen

I guess there is an easy solution for this. But I couldn’t figure it out and found nothing in the docs.


texts: Migrating to Matrix using Feed Me and Element API

texts:
How can I use Element API to move my entry fields into a matrix-based content builder? I'm going off the docs found at https://docs.craftcms.com/feed-me/v4/guides/importing-into-matrix.html#setup-your-feed but I can't return a key for matrixBlock multiple times, as it overwrites it with the last instance.

'export/departments.json' => function () {
  return [
    'elementType' => Entry::class,
    'criteria' => [
      'section' => 'departments',
      'type' => 'departments'
    ],
    'transformer' => function (Entry $entry) {
      return [
        'title' => $entry->title,
        'id' => $entry->id,
        'matrix' => [
          'serviceBlock' => !empty($entry->pageServices->all()) ? [
            'title' => "Services",
            cbEntries("pageServices", $entry)
          ] : null,
          'resourceBlock' => !empty($entry->pageResources->all()) ? [
            'title' => "Resources",
            cbEntries("pageResources", $entry)
          ] : null,
          'documentBlock' => !empty($entry->pageDocuments->all()) ? [
            'title' => "Documents",
            cbEntries("pageDocuments", $entry)
          ] : null,
        ]
      ];
    },
  ];
},

Right now this is where I'm at with my elements. I tried naming them all matrixBlock but as a result, the last element, or documentBlock as its called here would render.

For reference, here’s the cbEntries function I’m using, as well:

function cbEntries($section, $element)
{
  $sectionArray = [];
  if (!empty($element->$section)) {
    foreach ($element->$section as $value) {
      $sectionArray[] = $value->id;
    }
  }
  return [$sectionArray];
}


texts:
I have this form, there's no errors getting thrown and the User photo field is not updating via this form.

      <form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
        {{ csrfInput() }}
        <input type="hidden" name="action" value="users/save-user">
        <input type="hidden" name="redirect" value="users/{{ currentUser.username }}">
        <input type="hidden" name="userId" value="{{ currentUser.id }}">

          {% if currentUser.photoUrl|length %}

          {% else %}

          {% endif %}
          Profile Picture
          <input type="file" name="fields[photo]" class="form-control-file upload">

        <input type="submit" value="Save Profile">

      </form>

I'm unsure why it's not working, as it's fairly identical to some questions on SO.


texts: How do I access an asset field in the 'onSaveEntry' event?

texts:
I'm listening on an entries save event with:

craft()->on('entries.saveEntry', function(Event $event) {
  //$event->params['entry']); -> passes to function
});

How can I assess assets that are also part of that saved entry?

$event->params['entry']->getContent()->{fieldname} doesn't give me the array with information I was hoping for.


texts: Form field as 'Upload Location Subfolder'

texts:
Question concerning the Freeform plugin:
Is it possible to set the contents of a text field as my 'Upload Location Subfolder' of a file upload field?
I tried stuff like {{ form.customerName }} and {{ craft.request.getPost('customerName') }}, but neither will let me submit the form.
Is there even a way to achieve this using Freeform?


texts:
When I install the Craft Commerce plugin on Craft CMS, I found an error "unknown error occurred".  Please tell me about this error and how to fix it. I will be very thankful.

I have a lot of google search on it but nothing useful.

Thanks again.


texts: Limit/offset output of Matrix field by 50%

texts: Is it possible to limit and offset the output of a Matrix field by 50%? I wanted to split the data across two columns.


texts: Can't get current entry's ID - Impossible to access an attribute ("id") on a null variable

texts:
I'm trying to upgrade my website to Craft 3 and can't resolve one issue with this piece of code:

{% for category in craft.categories.group('blogCategories').order('title') %}

{{ category.title }}

{% endfor %}

I get the following error:

  Twig Runtime Error – Twig\Error\RuntimeError
  Impossible to access an attribute ("id") on a null variable.

I can't find any information in Changes in Craft 3, but I bet there's a new way of getting the category ID of the current post and the entry.blogCategory.one().id won't work anymore?

Any ideas?


texts:
I'm importing Real Estate properties every 30 minutes into my website.
I have a controller action that triggers this but the import is extremely slow and blocks the entire site.

Right now I'm triggering the imports with this code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);
curl_close($ch);

Where the url is the cron url of the feed.


texts:
I'm trying to add some custom routes for my plugin, but it's throwing a 400 CHttpException for invalidActionParams when accessing largeupload/folders/2 as an example.

public function registerCpRoutes ()
{
return array(
    'largeupload'                           => array( 'action' => 'largeUpload/index' ),
    'largeupload/folders'                   => array( 'action' => 'largeUpload/folder/index' ),
    'largeupload/folders/new'               => array( 'action' => 'largeUpload/folder/edit' ),
    'largeupload/folders/(?P<folderId>\d+)' => array( 'action' => 'largeUpload/folder/edit' ),
);
}

My controller is called LargeUpload_Folder, and my action actionEdit().

public function actionEdit ($variables = [ ])
{
    /* Simplified */
    if ( isset($variables['folderId']) ) {
    }
    else {
    }

    $this->renderTemplate('largeupload/LargeUpload_Edit', [
    ]);
}

If I remove $variables = [ ] from the action parameters, it doesn't return an error anymore.

Any ideas?


texts: I am a craft newbie and was wondering what General Settings > Logo does, as I can't find anything about it (how to use it with twig etc.) in the documentation or elsewhere.


texts: Child categories appear as their parent when selected

texts:
In an entry, when selecting a child category, the parent is shown as the selected item. This prevents the use of any child categories. Any help would be appreciated.

Use Case:

Selection Modal:

Selection within the Entry


texts: Custom field plugin: Unable to find template / General custom field plugin information

texts:
I am still relatively new to Craft CMS.
I am trying to make a custom field plugin for Craft 3 but I am struggling to understand why I can't render my form template.
The fieldtype should render a map with markers in an entry, depending on which checkbox is clicked before map creation.
I have the following code in my Field.php file:
public function getInputHtml($value, ElementInterface $element = null): string
{
...

Craft::$app->getView()->setTemplateMode(View::TEMPLATE_MODE_SITE);
$input = Craft::$app->getView()->renderTemplate('locations-map/_includes/forms/mapElement', $variables);
}

And I get the following error:

This is the result from all the vague(in my opinion) information in the internet about making custom field types in Craft 3 CMS.
If you have an idea how to access this template or just any information about custom fields, please feel free to share. (Yes, I have read the official documentation)


texts: How to get the unique categories from a list

texts:
I have a set of FAQ entries. Each entry has one or more categories attached. To be able to filter entries related to a category I need a list with unique categories.

Using my solution I'm getting all (some double) categories.

   {% set entries = craft.entries.section('faqs') %}
   {% for entry in entries %}
        {% for category in entry.faqCategory %}

{{ category.title }}&nbsp;

        {% endfor %}
    {% endfor %}


texts:
I want to control what users are able to do. For example, prevent access to the CP when the system is off.

How can I prevent users for assigning extra permissions but still allow them to assign users to User Groups?

At present, it would appear that anyone able to assign User Groups is also able to assign whatever permissions they want.


texts: Is it possible to output the name of a Matrix Block?

texts:
I'd like to output the Names of Matrix Blocks. I know you can filter by block types e.g.

{% for block in entry.myMatrixField.type('text, heading') %}
{% if block.type == "heading" %}
    <h3>{{ block.heading }}</h3>
{% else %}
    {{ block.text | markdown }}
{% endif %}
{% endfor %}

I know I could use {{ block.type }} and get the block type's handle but, I want to included the actual Name of the block type itself too.

For example, something like this:

{{ block.type.name }}

Is this currently possible?


texts: Fallbacks for assets not avilable in a locale

texts:
I have a site with a lot of asset fields, the assets are translatable. The client has added lots into the English fields but many of the Welsh ones haven't been populated. I want to have things fall back to the English assets in cases where there aren't any in the Welsh.

For the sake of example, lets say we're on an entry page where an image has been uploaded in the English locale but one has not been uploaded in the Welsh locale...

I thought this would work:

{% if entry.assetField | length %}
    {# output whichever the current locale is, if it's populated #}

{% elseif entry.assetField.locale('en_gb') | length %}
    {# fallback to the UK English asset if it exists #}

{% endif %}

It doesn't. It will pull English assets if I'm viewing the English version of the page, but it does not fall back when we're on the Welsh version of the page. Furthermore, if I am on the Welsh page and change the code to only reference English, like so:

Then it doesn't output an image at all. It's like Craft is ignoring the .locale parameter I'm setting.

I'm certain the local values are correct because those are what are in the Locale setting in the CMS.

What am I doing wrong?


texts: multi language - each in its own folder?

texts:
Craft looks VERY promising to me! Still try to figure out if it could be perfect for our new project, though.

Our website will be in English and German (accessible under ONE domain - see below). I understand that there is a plugin with which I can switch the language while staying on the very same page - PERFEKT!

Here's my questions. Can those requirements be fulfilled by Craft?

We want the English content to be placed in the folder "website.com/en" and the German in "website.com/de". We would manually put an index.php with a redirect to our default language (not decided yet) in the root folder.
Can we completely build up the site in one language first - and then kinda "import/duplicate" it to the second language and translate it? language-switch links should still work afterwards. Means: Craft should know which articles of each language belong together.
There is no 'tab' above an WYSIWYG field under the very same article where I can switch between languages and fill in the corresponding content on the very same admin-page, right?

I'll open another question for my questions concerning my other topics...

Thanks for your help and greetings!


texts: Is it possible to allow logging at LEVEL_INFO without logging all the SQL queries?

texts:
We're currently logging our site at LEVEL_INFO to have a good idea of what's happening on the site. We find it useful, and appropriate, to log informational messages at that level rather than at ERROR or WARNING. However most of these INFO messages are drowned out by the sheer volume of SQL query logging. I did some digging and found that Yii DB Connections can be configured to not log all the queries.

https://github.com/yiisoft/yii2/blob/ec089fea5a684de1e358995bf36522ec6834e71b/framework/db/Connection.php#L410

This setting is then checked here:
https://github.com/yiisoft/yii2/blob/bdb7c6491061b48c16b0fdbcba791ccd514a91d9/framework/db/Command.php#L1112

Ideally we'd like to be able to log queries at the TRACE or DEBUG level but it doesn't look to be possible.

Is there a simple way to disable the logging in the craft config? If not Would it be possible by extending an existing Craft class?

Any pointers or help would be appreciated. Thanks in advance!


texts: Craft Commerce: How to manage different prices with one product?

texts:
I am looking for a solution that would allow me to sell events tickets within Craft. I'm am currently making a prototype with Craft Commerce plugin for this project, but I am already facing a major problem.

When creating a new product, I can set a ticket price + a total number of tickets available at this price. When using variants, I can define multiple tickets + a total of available tickets under each price. But it does not seems possible to synchronize a total number of available tickets with different price options (full price and other at reduced fare).

How can I do ? Is it possible to set the total number of tickets available outside of variants, such as the variants would be only used to set the price ?


texts: I have a Product Type where every product has the same price. What are some good ways to avoid having to enter this same price for every product?


texts: Craft Commerce: send notification emails when setting status dynamically?

texts:
How would I get a status notification to send when setting the status of an order dynamically via a plugin?

I've got a few different order 'types' that need a different default status (for different notifications), so I created a plugin that sets the status at onBeforeOrderComplete, which sets the status for the order just as expected, but no notifications are sent. There are no issues with the notification emails sending (when changing the status via the cp, they send out as normal).

My Code:

craft()->on('commerce_orders.onBeforeOrderComplete', function($event)
{
    $order = $event->params['order'];
    if ($order->orderType == 'blah') {
        $order->orderStatusId = 1;
    } else {
        $order->orderStatusId = 3;
    }
});


texts:
I can install plug-ins from the command line, but when I do so from within Craft, I get this:
Composer was unable to install the updates.
Error: Could not delete /var/www/craft-dev/vendor/yiisoft/yii2-shell/ShellController.php: unlink(/var/www/craft-dev/vendor/yiisoft/yii2-shell/ShellController.php): Permission denied
Composer output: Package "craftcms/vue-asset" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies
Package operations: 8 installs, 2 updates, 4 removals

Removing yiisoft/yii2-shell (2.0.4)

Any suggestions? Permission error?


texts:
I would like to output a field from a variable like this:

{% set foo = "entry.title" %}
{{ foo }}

In this example it outputs "entry.title".

Other Example like this:

{% set prefixVar = "en_" %}
{% set foo = "entry."~ prefixVar ~"title" %}
{{ foo }}

In this example it outputs "entry.en_title". Is it possible in Twig to get the content of the entry field instead of the string?


texts:
I'm wondering if there's some build in function in Craft that can "translate" a URL the same as a string?

For example when I want to translate a static string I'll use the "t" Twig filer like so:

{{ "String"|t }}

Let's say I want to do the same, but with my localized URL's. Imaging this:

{{ url('a-url-slug')|t }}

Then in my translation file I can add different URL's that's localized (but loading the same template, I'm solving this using Routes).


texts: Is there a way to detect if a action is triggered from a control panel form?

texts:
We're building a content platform for a bank for a client of us. One required feature lets relationship managers add clients (members) to the platform which get assigned a specific group.

We listen to the users.onSaveUser event and when the specific group is chosen and the user gets added via the CP there should be sent out a specific email to that client. This is the code I have so far:

public function initRmAddsClient()
{
    craft()->on('users.onSaveUser', function(Event $event) {

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

        if ($event->params['isNewUser'])
        {
            //get new user group from form post
            $groups = craft()->request->getPost('groups');
            if ($groups)
            {
                if (count($groups) > 0)
                {
                    $userGroup = craft()->userGroups->getGroupById($groups[0]);

                    if ($userGroup->handle == 'premium' || $userGroup->handle == 'private')
                    {
                        craft()->email->sendEmailByKey($user, 'rm_adds_client', array(
                            'user' => $user,
                            'link' => TemplateHelper::getRaw(craft()->users->getPasswordResetUrl($user)),
                            'rm' => craft()->userSession->getUser(),
                        ));
                    }
                }

            }
        }
    });
}

I just want to add one extra check if the submission is done via the control panel since public registration is enabled as well.

Is there an easy check for that?
Thanks


texts: Where should a plugin create temporary files

texts: I have a plugin which needs to create a temporary file. Where should I put it?


texts: How do I setup my Element Types Sources for deep linking?

texts:
In the Entries tab in the Control Panel, I see a list of Sources on the left hand side:

All Entries
Singles
News

When I click on each of these sources the page filters the appropriate results in the body and the URL gets updated appropriately:

All Entries => /admin/entries
Singles => /admin/entries/singles
News => /admin/entries/news

This is nice as I can now send links to other people to a specific sub-section in the sources, with the contents already filtered.

I've compared my code in the source nav to the code on the Entries Element Index page, and they are comparable, including passing the data-handle value to each source. But it's still not working in my Custom Element type. I must be missing something but I haven't yet figured out what.

How do we get this behavior working for custom Element Types?


texts: How to store json data in a custom fieldtype so that it's data can be referenced as attribute values?

texts:
I would like to store a json object in a custom fieldtype, and be able to traverse the object's attributes using twig dot syntax in my template. I am currently storing the raw json object as a string, but I'm not sure what I need to do to be able to reference the stored string as an object.

Here is a shortened example of the raw json string that is being stored:

"Stripe_Customer JSON: {
    "id": "cus_4v68MrZu3za8XT",
    "object": "customer",
    "cards": { "object": "list", "total_count": 0, "has_more": false, "url": "/v1/customers/cus_4v68MrZu3za8XT/cards", "data": [ ] },
    "subscriptions": { "object": "list", "total_count": 0, "has_more": false, "url": "/v1/customers/cus_4v68MrZu3za8XT/subscriptions", "data": [ ] },
    "etc": "etcetcetc"
}"

In my template I would like to be able to reference the objects properties in some way (i.e. {{ fieldHandle.id }}) for display only; and on the back-end within a service, I would like to set object properties before saving back to the DB (i.e fieldhandle->id = value).

I am not sure whether defineContentAttribute should return AttributeType String or Mixed in this case.

public function defineContentAttribute()
{
    return AttributeType::String;
    //return AttributeType::Mixed;
}

And if it should be a string, how would one define the column type as "Text" vs the default VARCHAR(255)?

Update: I see that there is a similar question regarding custom fieldtype with multiple values, however, in this case, the end-user will not be manipulating the data directly in any way — they will be filling in dummy fields that will be send to a third party service via javascript/ajax, a result object returned, and then forwarded (again via ajax) to a back-end service method to be processed and saved to the DB.


texts: Append a string to the end of all rich text links

texts: I'm trying to append a string to the end of all rich text links. Is there an already existing plugin for this?


texts: Controller action throws a 500 error in some environments

texts:
We have a plugin. Locally, it's working as expected.

When we push to dev, one of the actions begins to throw a 500 error.

The action is taking place via an ajax call, and the error in the console is:

POST http://website.com/admin/pluginName/controller/method 500 (Internal Server Error)

If I expand that error in the console, I see the following:

k.cors.a.crossDomain.send jquery-2.1.1.min.js?d=1421398025:4
n.extend.ajax             jquery-2.1.1.min.js?d=1421398025:4
n.(anonymous function)    controller:474
(anonymous function)      jquery-2.1.1.min.js?d=1421398025:3
n.event.dispatch          jquery-2.1.1.min.js?d=1421398025:3
r.handle                  jquery-2.1.1.min.js?x=Q4rOzOLw2:3

Checking the Craft Error Logs I see:

Level: error
Category: exception.Guzzle\Http\Exception\ClientErrorResponseException
Message exception: 'Guzzle\Http\Exception\ClientErrorResponseException' with message 'Client error response

Any ideas on what is different about our dev environment vs. the local environment?

Any steps I can take to better diagnose how to solve this issue?


texts: Craft internal error exposing sensitive data

texts:
I have a craft installation and recently my server had issues and on the page rendering mysql and other errors were shown.
Of course this creates security implications. Is there a way to restrict these errors? My guess it that i just need to change the devMode to false in general.php. Is there anything else i need to do? I am asking because I cannot really reproduce the error anymore.


texts: Looking to build a hybrid news service that publishes to a website but also sends an entry to a mailing list. Has anyone done anything similar?


texts: How to allow browsers to cache Craft's admin static files?

texts:
I notice that the Craft admin pages append random query parameters to their static files, i.e. jquery-2.2.1.min.js?x=AKVKl03So:

This prevents those static files being cached in browsers, which can make the admin views unreliable in less-than-optimal network conditions.

I see the logic to make this happen is in Craft's app/helpers/UrlHelper.php

Is there a sane way to deactivate that behavior, and allow browsers to cache Craft's static files?


texts: I'm just a beginner in Craft CMS but i'm wondering why there's no Add New Entry button in my dashboard. What should be the problem with it?


texts: Has anywhere users successfully run Craft 3 on CyberPanel / OpenLiteSpeed?

texts:
I've been trying to get a Craft CMS 3 project running on CyberPanel 2.x (with OpenLiteSpeed v1.6.14).
For the most part everything has gone well. Where I get stuck is with the LiteSpeed caching.
The reason is that LS stores all LSCache files in a shared directory, that the hosts have no permissions to access. There is an OpenLiteSpeed Cache plug-in for Craft, but it requires the user to provide the absolute path to the cache. Doing that will crash the site (due to permissions error).
If anyone here has successfully got Craft CMS 3 running on OpenLiteSpeed (especially in a CyberPanel system), I'd be grateful to learn how you went about it.


texts: Override max-length on the Title format field

texts:
We're using entry properties in the Title format field to automate titles for some channels. However we've ran into the issue of this field having a max-length set on it. I understand why this exists when you create an entry. But when you're setting up the code to auto generate titles you can easily run longer than the allowed 255 characters.

Is there a way to change the max length or some way to get around this issue?

We've looked but haven't found any plugins to deal with this issue nor any clever ways to get around the current limitation. I've seen some posts about the max length but they relate to when you add entries. This is just about when you setup automated titles.


texts: Can't get Craft running on a remote server

texts:
I have a Craft site that works great locally, but I can't get it running on a staging server. The virtual host is working and when I remove code from index.php in html it runs perfectly. Here is the error...

  Could not find your craft/ folder. Please ensure that $craftPath is set correctly in /var/www/vhosts/testsite/staging/html/index.php

I've seen the error reported online but no solutions, any ideas?


texts:
Have to update an order afterwards cause the client can choose a retail partner.

<form method="post" name="submitOrder" style="width: 100%" onkeypress="return event.keyCode != 13;">
  <input type="hidden" name="action" value="commerce/cart/update-cart">
    {{ redirectInput('s/partner?number=' ~ number) }}
    {{ csrfInput() }}

    <input type="text" id="retailPartner"
           name="fields[orderCommercePartner][]"
           value="0">

    <input type="submit"
           class="a-button  a-button--black  a-button--bold js-chooseThisPartner"
           style="margin-bottom: 40px;"
           value="{{ 'Choose this partner' | t }}">
</form>

That's my form I fill the value fields[orderCommercePartner][] via JS and it's filled.

But the order is not updated. Any Ideas what goes wrong here.


texts:
I have a listing of entries at /events that loads events/index

I also have a custom route setup to be able to list 'live' entries by week

'events/(?P<year>\d{4})/(?P<week>\d{2})' => 'events/_weekindex',

I also have a page events/past that should load past entries by loading the template events/past

That all works exactly how it should. UNTIL i set a route for events/{slug} to use the template events/_entry where i have this defined at the top of the template to allow for entries expired or live to be shown without a 404.

{% set entry = craft.entries.section('events').slug(slug).status('live', 'expired') %}

Once that route is set, going to events/past no longer loads the events/past template it now attempts to load the events/_entry template. This obviously throws errors as there is no slug defined given /past is suppose to be a listing page not a single-entry page.

Also if i do load an expired entry i get an error "Variable "slug" does not exist". Do i need to specify which segment the slug is in instead of just doing (slug) have a pre set defining slug as craft.request.getSegment(2) ?

So at the end of the day i have 2 problems here. 1 the slug is not defined based on that set. And 2 the route is causing events/past to be re-directed even though it should not be.

I should note i tried also setting a route for events/past to route to events/past template but that did not do anything. I should also note the other route i set for the year/week still works after setting the other route for events/_entry, that route is not effected at all and continues to function properly.

Posted this in the slack but I think everybody is sleeping, holding my breath people are still awake on the stackexchange. :-)

UPDATE:: I set the route for events/past BEFORE the route for events/{slug} and now the events/{slug} route does not interfere with the events/past route (that i did not even think should be necessary in the first place, nor did i know that the order mattered, is this intentional or a bug?

Update 2 I've resolved the issue by wrapping everything in a for loop instead of using set like so:

{% for entry in craft.entries.section('events').slug(slug).status('live', 'expired') %}

Doing the set as listed above did not work. So my pages are now working but i'd still like some clarification on the routing, the set, and the slug issues i was having regardless. Although everything is working it almost feels like i'm doing a work-around rather than how it's SUPPOSE to be done.


texts: Require password from current user on front-end form?

texts: I have a controller that handles some font-end form validation. From that controller I’d like to require the current (already logged in) user’s password to update any field. How can I do that?


texts:
I am new to Craft CMS and struggling to figure out how to display my logo in my template.

The error message is:

Variable "siteLogo" does not exist

This is the code I am using:

{% for asset in siteLogo.siteLogo %}
    <img width="180px" src="{{ asset.url }}" alt="ICW Logo">
{% endfor %}

Any advice would be greatly appreciated!

Thanks in advance.


texts: Set status 'pending' on Guest Entry form

texts:
I'm using P&T's Guest Entries plugin along with my front end entry forms. All working fine except I want front end entries submitted with status 'pending'. Thought this would be pretty straightforward but something's not right. Atop my form I have:

<input type="hidden" name="action" value="guestEntries/saveEntry">
<input type="hidden" name="redirect" value="success">
<input type="hidden" name="enabled" value="1">
<input type="hidden" name="status" value="pending">

Anyone got statuses working in entry forms?


texts: Trouble getting the CP url to work correctly with a proxy server

texts:
Background: My client is using a proxy server to point to the production environment of the project. So for example their deployment is at https://messyurl.com, but their proxy server is routed to display at https://niceurl.com.
What I did: I set the siteUrl config field to https://niceurl.com, which successfully rendered niceurl.com links throughout all the templates. Cool. But when going to niceurl.com/admin, it redirects me to messyurl.com/admin. I thought I could solve it by adding the baseCpUrl config variable to be set to https://niceurl.com, but that made it so that I got a 404 when visiting https://niceurl.com/admin.
Any ideas why my cp is refusing to cooperate here? The client actually doesn't mind that the CP is at messyurl.com, but the thing they don't like is the entry preview is broken because of cross-domain stuff due to the url conflict.


texts: Use Same Email Address On Multiple User Accounts

texts:
I am needing to set up two distinct users (one for each of two LDAP log ins) and I need for them both to use the same admin email address.  However, Craft 2 will not let me do this.  Is there a way to do this for this type of special admin/ldap user?

Thanks


texts: Hook calls within a loop always get the Entry, not the loop context?

texts:
According to the docs, if I call a hook from within my template:

  The $context argument will be the current Twig context array, which you’re free to manipulate.

So I have a loop in my template where summary is a model I've created:

{% for summary in bookings %}
    {% hook 'microsGetBooking' %}
{% endfor %}

If I understand correctly, the $context variable passed to my hook should be a reference to that summary object. However it always appears to be an EntryModel (in this case the template I'm calling this on has a URL that matches an entry in the CMS).

What am I missing here?


texts: Rendering templates from plugin controller

texts:
Right now I'm trying to accomplish routing users through a controller action before rendering the plugin's CP template...

[Plugin]Plugin.php

// ...
public function registerCpRoutes()
  {
    return [
      'plugin/controller' => ['action' => 'plugin/controller/action']
    ];
  }
// ...

The idea here is that I want to perform validation checks in the controller before I serve up the view.

I'm running into two issues when it comes to rendering the template from the controller:

The template path is set to the core template directory (which makes plugin templates inaccessible)
If I reset the template path to, say, the plugin's directory then I can no-longer extend core layouts (like _layouts/cp) within my template.

My solution was to then just fetch the plugin's template as a string and then render it using the renderString method so that way I can use the template without modifying any path variables...

[Plugin]Controller.php

// ...
protected function renderPluginTemplate($template, $variables = array())
  {
    $oldPath = craft()->path->getTemplatesPath();
    $newPath = craft()->path->getPluginsPath() . 'plugin/templates';

    craft()->path->setTemplatesPath($newPath);

    if(!$templatePath = craft()->templates->findTemplate($template)) {
      throw new Exception(Craft::t('Could not find template with path: ' . $template));
    } else {
      $templateContent = file_get_contents($templatePath);
    }

    craft()->path->setTemplatesPath($oldPath);

    echo craft()->templates->renderString($templateContent, $variables);
  }
// ...

This works for the most part. Now the layout isn't pulling in the right Javascript dependencies – no JS gets fired – so the panel content is hidden and the dropdown menus don't work.

There must be a better way to do this. I'd be super grateful if anyone could provide any insight.

Jon


texts: Check which pagination page to display code outside of pagination loop

texts:
I have some Featured news entries which appear at the top of the rest of the news entries.

How do I set this so they are only on page 1 (before any pagination pages)?

{# Only show on page 1 of pagination #}

   {% for entry in craft.entries.section('newsEvents').highlightNews('1').limit(2) %}

     {% if entry.listingImage|length %}
    {% for image in entry.listingImage %}

    {% endfor %}

    {% endif %}

{# End only show on page 1 of pagination #}

{% paginate craft.entries.section('newsEvents').limit(12) as entriesOnPage %}

  {% for entry in entriesOnPage %}

    ...

  {% endfor %}

{% if paginate.totalPages > 1 %}

{% set pagination = true %}

    {% if paginate.prevUrl %}
&#171;
{% endif %}

    {% for page, url in paginate.getPrevUrls(5) %}

{{ page }}

    {% endfor %}

{{ paginate.currentPage }}

    {% for page, url in paginate.getNextUrls(5) %}

{{ page }}

    {% endfor %}

    {% if paginate.nextUrl %}
&#187;
{% endif %}

{% endif %}


texts: I have a plugin using the onBeforeSaveEntry event. Is there a simple way to check if the entry being saved is a brand new entry i.e. Add New Entry or if it currently exists and is just being updated?


texts: Best way to implement my own statuses on my custom element type?

texts:
I'm working on a plugin with its own element type, I'm trying to add custom statuses to the element type. What is the best way to proceed? I have hasStatuses set to true and getStatuses is where I would set them.. But what should the array look like thats returned?

UserElementType returns this:

/**
 * Returns all of the possible statuses that elements of this type may have.
 *
 * @return array|null
 */
public function getStatuses()
{
    return array(
        UserStatus::Active    => Craft::t('Active'),
        UserStatus::Pending   => Craft::t('Pending'),
        UserStatus::Locked    => Craft::t('Locked'),
        UserStatus::Suspended => Craft::t('Suspended'),
        UserStatus::Archived  => Craft::t('Archived')
    );
}


texts: Is it possible to setRouteVariables when redirecting after a successful form submission?

texts:
I have a form.  It submits.  It saves.

I'd like to pass the newly-created, complete form object back to the 'thank you' page template so that I can display the values that were submitted.

I do not want to pass the ID or any identifiable information in the URL.  Ideally, I'd like behavior just like using setRouteVariables

craft()->urlManager->setRouteVariables(array(
    'form' => $form
));

However, setRouteVariables does not work when using $this->redirect() or $this->redirectToPostedUrl().

I can successfully pass query string parameters back using the redirect method in the following way:

$this->redirect(array($redirectUrl,'dog'=>'cat'), true);

Is there any way to do this with posted variables that are not visible to the user?


texts: Commerce 1 find if Discount object is valid based on start/end dates (Twig)

texts:
In Twig, I want to find out if a discount is valid based on start/end date.  startDate and endDate don't seem to exist and I can't inspect the discount object by using the json_encode filter (returns {}).

How can we do this?

This is the code used to grab the discount object:

{% set discount = null %}
{% for d in craft.commerce.discounts %}
    {% if d.id == 1 %}{% set discount = d %}{% endif %}
{% endfor %}

name, description and enabled variables are available but no startDate/endDate.


texts: Multiple contact forms different receiver(s)

texts:
The current site that im building has multiple contact forms. The forms are page specific and should send this to a different user (depends on which page the user sends the form).

My question: is there a way to define per form (page) to which receiver the form should be sent?

Thanks in advance,


texts: Sprout Forms: gather data from the page a form is on

texts:
I want to gather data from the page a form is on and submit this information to the form entry.

Use case:

On an 'Events' entry page (the form is in the sidebar)
When the user fills in the basic form and submits, I want to get the entry's title and some custom fields in addition to what the user has filled out

In short what I want the form entry to submit is: Name, Email, Tel No, Message IN ADDITION to Event Entry Title, Date, Excerpt.

I think this is possible with hidden and invisible fields, but I may misunderstand their purpose.

-

After this form has been submitted I would like Sprout Email to get a hold of this data - so I need to know how to output this data when setting up the template in the back end text area for the email as well.

Could anyone offer any assistance on this please? I would greatly appreciate it. Thanks!


texts:
I'm looking to show the users that have an entry relating to the currentUser, it is currently working but is obviously showing duplicates e.g. admin, admin as admin has 2x posts associated. Is there a better way of doing this and removing the duplicates? I just can't think of it.

{% set submissions = craft.entries.section('submissions').relatedTo({
  targetElement: currentUser,
  field: 'submissionBrand',
}) %}

{% for entry in submissions %}
    <li>{{ entry.author.username }}
{%  endfor %}


texts:
Does querying composer packages via the Craftnet API need authentication?
Ref https://docs.api.craftcms.com/packages.html
Querying the Craft CMS package itself is fine, eg https://api.craftcms.com/v1/package/craftcms/cms. However trying to query any plugins is throwing a 404, eg https://api.craftcms.com/v1/package/craftcms/contact-form


texts:
I tried to use reduce function in template, but got error. It seems twig/craftcms can not work with such functions.
Reduce function docs: https://docs.craftcms.com/v3/dev/filters.html#reduce

My example:

{% set data = craft.entries.section("faqChannel").orderBy('faqOrder').all() %}
{% set types = data|reduce((acc, v) => v.faqType is not in acc ? acc|merge([v.faqType]) : acc, []) %}

Error:
Twig Syntax Error – Twig_Error_Syntax
An opened parenthesis is not properly closed. Unexpected token "punctuation" of value "," ("punctuation" expected with value ")").


texts:
I have 2 sites within 1 Craft 3 installation, they are both the same language and generally have nothing to to with each other.

I would like both to have individual startpages at the URL "/".

Is this possible?
With 1 or 2 sections (structures in my case)?

Thanks,
Matthias


texts: Using Embedded Assets Plugin With Element API

texts:
When using the Element API, how do you go about using the Embedded Assets plugin?

With a regular asset, in the API transformer you can pull out assets and include them like this:

'transformer' => function(craft\elements\Entry $entry) {
    // Create an array of all the photo URLs
    $photos = [];
    foreach ($entry->photos->all() as $photo) {
        $photos[] = $photo->url;
    }

    return [
        'title' => $entry->title,
        'url' => $entry->url,
        'description' => (string)$entry->description,
        'photos' => $photos
    ];
},

This approach however gives me the URL to the json file that Embedded Assets uses to store some information about the video.

Is there a better way than parsing that file as json in php and pulling the iframe from that? Is there some plugin code that can be used to handle this more elegantly?


texts: How to load components into Craft 3 plugin?

texts:
what is the correct way to load third-party components into Craft 3 plugin I'm developing?

I tried adding

$this->setComponents([
    'authClientCollection' => [
        'class' => '\yii\authclient\Collection',
        'clients' => [
            'twitter' => [
                'class' => '\yii\authclient\clients\Twitter'
            ],
            // etc.
        ],
    ]
]);`

to plugin's init() function, as well as parent::setComponents, but both produced same error:

  Unknown component ID: authClientCollection

What am I doing wrong here?


texts: Console command runing from Cron job failing after Craft update

texts:
I have had a custom console command running fine for several months now which sent out reminder emails to users when there accounts are about to expire.

After the latest Craft update (I believe) it stopped working. Here is the error:

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054
Unknown column 'users.locked' in 'field list'
exception 'CDbException' with message 'CDbCommand failed to execute the SQL statement:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.locked' in 'field list'' in CDbCommand.php:543

The lines of code from the plugin service which cause the error are:

$user_criteria = craft()->elements->getCriteria(ElementType::User);

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

$users = $user_criteria->find();

Basically it fails when running the find() method.

Strangely I haven't managed to replicate the error on my local machine.

Does anyone have any idea what might be causing this?


texts: How can I select channel index/root pages from an Entries Field Type?

texts:
This seems like a somewhat overlooked feature. When I use an "Entries" field type with "All" sources selected. I don't have the option to select the root link for any of the channels. I can select the individual entries for the channels, just not the actual channel itself.

Is this intentional? Or is there a way to include channel index pages as a selectable option too?


texts: How can I remove all text content and assets from a duplicated site?

texts: I duplicated a site.  What is the easiest way to delete all assets and text data but keep fields and sections in place?


texts: Set a dynamic `activateAccountSuccessPath`

texts: How to set a dynamic path for activateAccountSuccessPath that contains the username (or any other field from the user profile)?


texts:
I've written a simple plugin that attaches to the onSaveEntry event. I'd like to access the image, extract the colours from the image using https://github.com/brianmcdo/ImagePalette and then save these colours to a field. I've managed to access the entry, but can't seem to find how to get the path and filename of the image?

Any help would be greatly appreciated!

Thanks


texts: How do I set up PhpStorm for plugin development

texts:
Can someone explain how to set up PhpStorm so that I can use it to develop/debug a plugin? I have

local webserver set up
craft files in the usual place above the webroot

The new project wizard gives me a choice between "Web server is installed locally, source files are located under its document root" and "Web server is installed locally, source files are located elsewhere locally. (Source files are copied to project root, then synchronized with server when necessary.)" Neither of which seems quite right.

Directory structure:

craft

app
plugins

myplugin

public <== this is webroot

.htaccess
index.php


texts: How to truncate auto-generated entry titles?

texts:
I am auto-generating entry titles based on a plain text field. Now, I would like to limit the characters the title contains of (e.g. 50 chars while the plain text field has 500 chars). How could I do that?

Thank you very much for your help.


texts: Model public method throws CMapIterator warning

texts:
I have a strange problem with the following public method on a model.

public function getAttributes()
{
    return $this->getId() . $this->getStyle() . $this->getDataAttributes();
}

CMapIterator warns with the following array_keys() expects parameter 1 to be array, string given

But if I alter it to

public function getAttributes()
{
    return array($this->getId() . $this->getStyle() . $this->getDataAttributes())[0];
}

Everybody is happy. It's late and I'm probably shouldn't be coding but any thoughts on the issue would be much appreciated.

Here is the complete model for reference...

namespace Craft;

class Core_CodeModel extends BaseModel
{
    /**
     * @return array
     */
    protected function defineAttributes()
    {
        return array_merge(parent::defineAttributes(), array(
            'cssId' => array(AttributeType::String),
            'cssClass' => array(AttributeType::String),
            'style' => array(AttributeType::String),
            'dataAttributes' => array(AttributeType::Mixed),
        ));
    }

    public function getDataAttributes()
    {
        return is_array($this->dataAttributes) ? ' ' . craft()->core_code->joinDataAttributes($this->dataAttributes) : '';
    }

    public function getId()
    {
        return !empty($this->cssId) ? ' id="' . $this->cssId . '"' : '';
    }

    public function getStyle()
    {
        return !empty($this->style) ? ' style="' . str_replace(array("\r", "\n"), '', $this->style) . '"' : '';
    }

    public function getAttributes()
    {
        return $this->getId() . $this->getStyle() . $this->getDataAttributes();
    }

}


texts:
I get an error message when trying to add an asset through a matrix field when I try to save the entry

Internal Server Error
Cannot find the target folder.

I am able to upload images through assets just can't get the entry to save. Any ideas. It was working before without issues?

Thank you for any help
Josh


texts:
How do I create a dropdown menu that filters all the posts into month and year, and then link to a template that has the entries of that month and year displayed?

This is as far as I've gotten:

<fieldset>
    {# Use the `group` filter to get the years, entries were posted in #}
    {% set entries = craft.entries.section('blog') %}
    {% set entriesByYear = entries|group('postDate|date("F Y")') %}
    <select name="year">
        {# Go through the `year` groups #}
        {% for year, entries in entriesByYear %}
            <option value="{{ year }}">{{ year }}</option>
        {% endfor %}
    </select>
</fieldset>

I can get the month and year to display in a dropdown using the code I found above, now I just need to get those elements to link to the corresponding template file. I have my Route setup as 'blog/year/month' and a template setup as well.


texts: Tag to fetch URL and Title of a entry when supplied it's ID

texts:
I have a number of places in my templates where a link to a particular entry is needed to be hardcoded into the template, but we still want that links URL and title to be dynamic, so if the URL or Title of the entry is updated, this is reflected.

Is there a nice lightweight simple snipped of code we can use to fetch the URL and Title of an entry when supplied with a valid entry ID? I've checked through the documentation but can't see anything obvious.

Particularly after something lightweight that isn't going to add significant numbers of DB queries to a page load.


texts:
My main config is Apache/Centos 7/WHM/Redis/OPCache/PHP7.1/MariaDb/PHP-fpm/Http2 and have optimized my server to a great degree.  It's a 32GB dedicated HexaCore.  I have worked really diligent to get the server optimized over the last few weeks and the state it currently is in, it's pretty dang fast.  Now so you know I am not tooting my own horn, I will preface by saying this, I am the furthest away from a server admin as anyone can be, but I get by.

My question is: When serving up an local asset like CSS (/style.css) over HTTPS it takes about 2 seconds longer to load. A big part is the time of 800+ms for the style.css to load over https, ugh. So I am asking how can I use http2 to my advantage with Craft? I want to run in HTTPS all the time but not with the handshaking lag. Any suggestions or examples would be greatly appreciated.

In case you are tempted to say go Nginx, I would love too but unless you are volunteering, at this time I cannot put myself through an Nginx install.

Thanks!


texts: Turning off a site in multi-site/multi-environment config

texts:
Given a multi site setup (domain1.com, domain2.com) that also uses multiple environments (dev, staging, production) - how would one configure one of the sites to be turned off in the production environment?

I'm currently trying the following.

return [
    // Global settings
    '*' => [
        // removed for clarity
    ],

    'dev' => [
        'devMode' => true,
        'isSystemLive' => [
            'domain1.com' => true,
            'domain2.com' => false
        ]
    ],

    // Staging environment settings
    'staging' => [
        'devMode' => true,
        'isSystemLive' => [
            'domain1.com' => true,
            'domain2.com' => false
        ]
    ],

    // Production environment settings
    'production' => [
        'devMode' => false,
        'isSystemLive' => [
            'domain1.com' => true,
            'domain2.com' => false
        ]
    ]
];

Which I would have expected to have domain2.com turned off but domain1.com remains on. However, both sites are on.

I have also tried rearranging the config using the following structure (stripped back for brevity)

return [
    'domain1.com' => [
        '*' => [
            // default for domain1
        ],

        'dev' => [
            'isSystemLive' => true
        ],

        'staging' => [
            'isSystemLive' => true
        ],

        'production' => [
            'isSystemLive' => true
        ]
    ],

    'domain2.com' => [
        '*' => [
            // default for domain2
        ],

        'dev' => [
            'isSystemLive' => false
        ],

        'staging' => [
            'isSystemLive' => false
        ],

        'production' => [
            'isSystemLive' => false
        ]
    ],
]

But this also doesn't work.

So how should I specify different multi-environment configs for each site?


texts:
Looking at the possibility of sending the link in account activation emails to a set page rather than the homepage which {{link}} does so we have:

http://domain.net but they go to http://domain.net/welcome

Thanks
Simon


texts: Commerce Discount: spend $X, get product free

texts:
I want to make a promotion where at a certain cart total threshold, if a particular product is in the cart, it would be free. (e.g. spend $50 and get a free mug).

Trying to sketch out the best way to achieve this.

It seems like if a discount had a a "Cart total" condition, I could pull it off w/o a custom adjuster. It has "Purchase Total", but that says only applies to the matching products, not the entire cart. In this case I would want to select the mug in the "products" condition, and set the percent discount to 100% (I think).

Any ideas where to start?


texts: Login - Bad Request: The CSRF token could not be verified

texts:
I have just deployed an existing site to a new server. As the DNS is not pointing there yet, I have simply edited my /etc/hosts file on my Mac to point to the IP address for testing. Whilst checking through everything, it seems the site is functioning well, assets have been copied over etc. The only problem is that I am getting an error when trying to log in.

From the front end I get the message: Bad Request: The CSRF token could not be verified.

    2017/07/17 13:52:33 [error] [exception.Craft\HttpException.400] Craft\HttpException: The CSRF token could not be verified. in /home/forge/www.domain.co.uk/craft/app/services/HttpRequestService.php:1337
Stack trace:
#0 /home/forge/www.domain.co.uk/craft/app/framework/base/CComponent.php(561): Craft\HttpRequestService->validateCsrfToken(Object(CEvent))
#1 /home/forge/www.domain.co.uk/craft/app/framework/base/CApplication.php(212): CComponent->raiseEvent('onbeginrequest', Object(CEvent))
#2 /home/forge/www.domain.co.uk/craft/app/framework/base/CApplication.php(183): CApplication->onBeginRequest(Object(CEvent))
#3 /home/forge/www.domain.co.uk/craft/app/index.php(62): CApplication->run()
#4 /home/forge/www.domain.co.uk/public/index.php(19): require_once('/home/forge/www...')
#5 {main}
REQUEST_URI=/members/login
HTTP_REFERER=http://www.domain.co.uk/members/login
---

And from the craft admin login form, this comes up on the console after clicking Login

VM43:1 POST http://www.domain.co.uk/index.php?p=admin/actions/users/login 400 (Bad Request)

One point to note is that the original website was SSL encrypted but the new server hasn't had an SSL cert installed yet, because DNS is not pointing to it yet. However I have altered the /craft/config/general.php config file to reflect the http:// domain.

Any help would be appreciated.
Running latest craft 2.6.2987


texts: How many entries could the Craft database hold before it slows down?

texts:
I'm pulling in some RSS feeds using Feed Me (https://github.com/engram-design/FeedMe) and turning those in entries automatically using a cron job.

You can imagine that producing a lot of entries over time ;) Is there a known limit for entries in the Craft database?

And is there perhaps a way to automatically delete entries after x amount of time?

Thanks, Bob


texts: craft.entryRevisions.getDraftsByEntryId(entry.id) is returning an empty array

texts:
I'm trying to get the drafts for the entry on the front end to populate my plugin on the sidebar but cannot get the drafts returned with this code in a Twig template.

entry is an EntryModel here.

The entry ID is {{entry.id}}

{% set drafts = craft.entryRevisions.getDraftsByEntryId(entry.id) %}

{{ dump(drafts) }}

drafts is an array of 0 elements

Even trying it in a PHP plugin class and hard-coding the entry ID like

$drafts = craft()->entryRevisions->getDraftsByEntryId(995);

$drafts is empty.

Everywhere I've looked says to do like the above; however, this doesn't return any drafts that belong to the entry as expected.

In the dropdown by the entry name, it has the 2 Drafts' names and when clicking them it takes me to the draft, so it seems like the drafts are correctly mapped to this entry.

What am I missing?


texts: ImageOptomize and SEOmatic - Is Image Variant Required for Social and SEO images?

texts:
Do ImageOptomize and SEOmatic work together - or to be more specific do I need an image variant for the social and SEO images defined in SEOmatic?

I have been importing content into a News entry.
I am defining my image variations using imageOptimize on the News Volume.
I have a "meta image" asset field which is being used to serve the SEO and Social Media images to SEOmatic's SEO settings for the entry.

Before installing and using imageOptimize the meta image previews were working fine with SEOmatic in the entry editor. Now they are not getting picked up... do I need to define an image variant that matches the SEO and Meta image sizes?

Also... SEOmatic is such a time saver, I estimate I have saved at least two weeks dev time with this plugin. Thank you Andrew!


texts: Next and Previous Entries that match condition?

texts:
Not sure if what I am looking is possible, but basically I have a section ('portfolio').  At the bottom of each entry I have links to the previous and next entry. Simple.

My trouble is that the body field in my entries is not always populated, and because of this I would like to by-pass these ones in my nav at the bottom of an entry page.

See my code below which is not working, I have a feeling that my logic is not going in the right direction at all with this...

{% set params = craft.entries.section('portfolio') %}

{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}

{% if prevEntry and prevEntry.body | length %}
    {% set image = prevEntry.portfolioImages.first() %}
    Previous
{% endif %}

{% if nextEntry and nextEntry.body | length %}
    {% set image = nextEntry.portfolioImages.first() %}
    Next
{% endif %}


texts: Get categories with number of hits (entries, products)

texts:
Is there a way to get a list of categories with the number of entries associated with each particular category?
I want to output something like this:

It would make sense to fetch the number of hits in the same DB query. But currently I get the hits by running a craft.products(itemParams).total() per category iteration.
Or is this not a real performance problem?


texts: Formatting Slug {postDate.month} to 2 characters

texts:
We are migrating our site into Craft, which is by and far easy and pleasant. But I'm trying to match our old CMS's permalink structure, which used 2-character months in the URI.

When defining the structure to contain our old content, I'm unable to format the postDate.month as I'd like. I thought the Twig below would work, but it's giving me the wrong digit for the month (or example it should be '07' but consistently gives me '12'):

{postDate.year}/{postDate.month|date('m') }/{slug}

I'm sure this is pretty simple, but I can't pin down the syntax. Could someone please give me a hand?

I need a URI like this:

2015/07/here-is-my-slug


texts:
I've moved my site to the staging server but now I'm getting a craft can't connect to the database with credentials in craft/config/db.php

Thing is I uploaded this script with the same credentials and it connects just fine. Any idea what I could be doing wrong

<?php
# Fill our vars and run on cli
# $ php -f db-connect-test.php
$dbname = 'name';
$dbuser = 'user';
$dbpass = 'pass';
$dbhost = 'localhost';
$connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
mysql_select_db($dbname) or die("Could not open the db '$dbname'");

echo "connected to the database";

My full db.php file with actual db creds removed - updated to include domain from live site.

<?php

/**
 * Database Configuration
 *
 * All of your system's database configuration settings go in here.
 * You can see a list of the default settings in craft/app/etc/config/defaults/db.php
 */

return array(
    '*' => array(
        'tablePrefix' => 'craft',
    ),
    'nec.dev' => array(
        'server' => 'localhost',
        'user' => 'root',
        'password' => 'root',
        'database' => 'nec',
    ),
    'nec.dev.stagingdomain.com' => array(
        'server' => 'localhost',
        'user' => 'staging-user',
        'password' => 'staging-password',
        'database' => 'staging-database',
    ),
    'nec-inc.com' => array(
        'server' => 'localhost',
        'user' => '',
        'password' => '',
        'database' => '',
    ),
);

I can't figure out why this doesn't work on staging when the same credentials work with the connection testing script.


texts: Displaying image from related CraftCommerce entry

texts:
Folks:

I'm using CraftCommerce. I have a main product and several accessories related to that product. Accessories have a title, description, price, and image.

Now, I have no problem pulling the title and description for the related accessories using this:

    {% for relatedProducts in product.relatedAccessories %}
       {{ relatedProducts.title }} - {{ relatedProducts.accessoryDescription }}
    {% endfor %}

Where I've got a problem is pulling the related image. If I use {{ asset.getUrl }} it pulls the first image from the main product entry rather than the image in the related entry. I have tried Get image from related entries asset field and How do I pull related entries and assets? without success.

Any assistance would be great.


texts: Redactor plugin not found: imagePosition Craft 3

texts:
I just updated a Craft 2 site to Craft 3, everything pretty much works except for this error:

Redactor plugin not found: imagePosition

Since Redactor is now installed via the plugin store, how do I go about rectifying this issue?


texts: Refreshing meta data when using AJAX page transitions

texts:
I have created AJAX page transitions based on:

https://designbycosmic.com/journal/craft-cms-ajax-page-transitions-with-history-pushstate

It's all working nicely, the main content of the site (everything except the header) is loaded through ajax with a page transition using velocity.js.

My question is how would I go about getting all the metadata (or intact any of the information stored in  to refresh for each page. At the moment the meta data is stuck with whatever is there when the browser loads.

I know this isn't specifically craft but any help would be appreciated.

Scott


texts: Element API: how can I return entries via username?

texts:
Struggling to get this feed work with Element API. I'm trying to return all entries created by a specific username. I've tried several different methods, but none of them work.

Here is the latest version of what I've tried:

'dealers/<username:{username}>.json' => function($username) {
  return [
    'elementType' => 'Entry',
    'criteria' => [
      'section' => 'listings',
      'username' => $username
    ],
    'paginate' => false,
    'transformer' => function(EntryModel $entry) {
      ...