texts: Use pure PHP and HTML instead of Templates

texts:
This is probably a very naive question but I am brand new to Craft and as such, have no idea what to research and where...

I have a static website that is built with my own bespoke framework. We have recently decided to add a 'blog' page to this website and resultantly, I am exploring using Craft in order to save me time writing a bespoke solution from scratch.

From what I can see, Craft is extremely flexible and brilliant for professional developers like myself who refuse to work with the likes of WordPress. However, implementing into my framework may just be a step too far in regards to flexibility. Quite simply, I would like to know the following:

Does craft allow me to make calls to get the stored data and then I manually handle the inserting of this data? e.g. Something like: $blog_posts = $craft->getBlogPosts()
If not, is there a way to include certain files at the beginning and end of templates that are outside the craft directory?

Basically, one of the key features of my framework is to handle the generation of all of the JavaScript and CSS links, along with the head section of each of the pages throughout my site. Based on what I have tested, I have managed to get the header working by just adding a PHP 'include' above the craft code in my file, however, the footer (including javascript) does not work because the Craft obviously has some sort of 'exit' call to prevent the code from executing further.

This is what I currently have:

// Define any custom javascript files and css files to be included in the cache
//...

// Generate the document header
include($_PATHS['CURRENT'].'/_includes/_content/header.php');

/*
 * Craft CMS Code to load the blog template
 */

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

// Do not edit below this line
$path = rtrim($craftPath, '/').'/app/index.php';

if (!is_file($path))
{
    if (function_exists('http_response_code'))
    {
        http_response_code(503);
    }

    exit('Could not find your craft/ folder. Please ensure that $craftPath is set correctly in '.__FILE__);
}

require_once $path;

/*
 * End of Craft CMS Code
 */

// THIS DOES NOT WORK
// Generate the document footer
include($_PATHS['CURRENT'].'/_includes/_content/footer.php');


texts: Is it possible to change the default feed widget settings?

texts: Until you can override widgets on per user group basis, does anyone know if it's possible to change the feed settings to not display the Pixel & Tonic feed in the dashboard and either set it to be blank or another feed? Maybe using a config setting?


texts: Headless mode/ElementAPI: how to set the frontend's baseUrl in the backend endpoint?

texts:
I am having an ongoing confusion in headless mode.

Imagine a site with 2 servers:

Backend (Craft with element API) on https://backend.site
Frontend (vue.js) on https://frontend.site

Editors pick internal links in the craft cp. In the source of redactor field, they are saved as something like {entry:xxx@1:url}.

In the Backend's endpoint, they are rendered out using the domain specified in baseUrl.

So let's say we have an endpoint on backend.site/en/api/pages/somepage.json which is consumed by the vue frontend.

In the backend's JSON output, we have an internal link that should be rendered as such:

Go to our other terrific
Other Page
# Using https://frontend.site as baseURL.

So the logical consequence is to set baseUrl to https://frontend.site. Naturally, because the website's baseUrl is frontend.site – not the craft backend. But, but.

In my case, this has worked for the default language. But not for any other language – element API returned a 404 when I set the baseUrl to frontend.site

backend.site/en/api/pages/somepage.json ✅
backend.site/de/api/pages/somepage.json

When I reset baseUrl to backend.site, element API will again render all endpoints. But the links look like this:

Go to our other terrific
Other Page
# This link doesn't exist

What do you think?

A misconfiguration, a bug in element api, or a misunderstanding on my side?
Asked differently: which baseUrl do you have to set in headless mode?


texts:
In Craft we have the table field type and each column can have a type. This field type is restricted to only text, number and checkboxes. Is there a plugin to add entries field type to the column types?

And if there isn't, can someone guide me to the proper files which I should look into to modify and add the field types myself by making a new plugin.


texts: How to insert data with the querybuilder?

texts:
Is it possible to insert data with the query builder if so how?
I want to make (backend) fields by queries. What is the easiest way to do this? Or do I have to use regular mysql queries?


texts: Loop through both category group and tag group in single loop

texts:
Is is possible to loop through both a category group and tag group in a for loop?

Categories: blue, red, orange
Tags: basketball

Loop displays: basketball, blue, orange, red.


texts: How to display entries filtered from more than one category

texts:
I want to try to learn how I can filter entries by multiple categories. I realise similar questions have been asked in the past, but all the answers are for specific use cases. All I want to do is filter entries by categories from more than one group. I've found code to set up a form that returns the URL with a string, but I understand that the string needs to be converted into an array. That's the part I can't work out how to do.
So the form is like this:

        {# Get the relevant entries #}
    {% set categoryQuery = craft.app.request.getParam('category') %}
    {% set categories = craft.categories.group('candidate').slug(categoryQuery) %}

    {# Set the search parameters #}
    {% set searchParams = {
        relatedTo: categories,
        section: 'candidate'
    } %}

    {# Get the relevant entries #}
    {% set relevantEntries = craft.entries(searchParams) %}

    <form action="{{ craft.app.request.absoluteUrl }}">

Eye colour

        {% for category in craft.categories.group('eyeColour').all() %}
            <input id="{{category.slug}}" type="checkbox" name="category[]"  value="{{ category.slug }}" {{ category.slug in categoryQuery or categoryQuery == null  ? 'checked'}}>
            {{ category.title }}
        {% endfor %}

Hair colour

        {% for category in craft.categories.group('hairColour').all() %}
            <input id="{{category.slug}}" type="checkbox" name="category[]"  value="{{ category.slug }}" {{ category.slug in categoryQuery or categoryQuery == null  ? 'checked'}}>
            {{ category.title }}
        {% endfor %}

<button type="submit">
                Search
        </button>

    </form>

Which gives me a URL like this

/?category%5B%5D=blue&category%5B%5D=black


texts: Easily update the query string with a link

texts:
I'm working on a site with some filters that result in a page with a URL similar to this:
domain.com/led-products?series=67&efficacy=1000to5000&lumens=over150

That results page contains buttons/links like so:

[Series Name x]
 [1,000 to 5,000 Efficacy x]
 [Over 150 Lumens x]

Clicking on one of those would remove that filter. Let's say a user clicks on Series Name to remove that filter, the resulting URL would then be: domain.com/led-products?efficacy=1000to5000&lumens=over150

My problem is that I have no idea how to get that filter/parameter removal functionality in Craft. Does this require a JS solution?

I've played around with something like this and can't seem to get it to work for my needs.

Help?


texts: Setting up Craft 3 database backup command for a remote database server

texts:
I have my Craft 3 database on a separate server than my Craft webserver (load balancing) and when I use the download database backup function in Craft 3, it doesn't know where to look.

I haven't worked with a setup with separate locations for the DB and the site before so it's something new for me to work with.

From this answer, I think it's where I'd setup a custom backupCommand config, but I don't know where to start.

It's on an nginx setup if that helps?

Cheers.


texts: How do I print a value from Craft/Twig into a Javascript function?

texts:
I just want to print a value from Craft into a JavaScript function to filter a dashboard.

The function is this:

showOnly(filterName, values);

I tried this:

showOnly('Short Names','{{ entry.title }}');

But that did not work.  And yes, the filter does work If I hard wire the value that Craft/Twig should print.  But, I need it to match the title of the page as one navigates from entry to entry.

UPDATE

Here is the actual showOnly function in its entirety:

function showOnly(filterName, values) {
    // Think a single select filter.
    sheet = mainViz.getWorkbook().getActiveSheet();
    if(sheet.getSheetType() === 'worksheet') {
        sheet.applyFilterAsync(filterName, values, 'REPLACE');
    } else {
        // for dashboards
        worksheetArray = sheet.getWorksheets();
        for(var i = 0; i < worksheetArray.length; i++) {
            worksheetArray[i].applyFilterAsync(filterName, values, 'REPLACE');
        }
    }
};


texts: Merging Entries - Craft 2 worked but not Craft 3

texts:
I have this code which merged entries when in Craft 2

{% set entriesOne = craft.entries.section('publications').search('nonMembers:0').ids() %}
{% set entriesTwo = craft.entries.section('improveYourClub').search('membersExclusive:1').ids() %}

{% set entriesIds = entriesOne|merge(entriesTwo) %}

{% set entries = craft.entries.id(entriesIds) %}

However when I updated the site to Craft 3 I'm no longer seeing entries merged. I only get results for the entriesOne. not a list of combined entries as expected.


texts: I'm trying to set a max amount on the quantity in the cart. My problem is I want a customer to be able to update their quantity while in the cart, but I can't seem to figure out how to set the max quantity according to the stock on hand. I've done this with variant.stock in the items page, but can't seem to find anything that allows me to pull that information according to the lineItem in the cart page.


texts: "Template Not Found" error when trying to access a module controller action

texts:
I'm a total Craft newbie, so I hope this question isn't ridiculous.

I just want to see a controller / action work in my new module.

I have src/controllers/ScrapeController.php as such:

<?php

namespace mycompany\mymodule\controllers;

use craft\web\Controller;

class ScrapeController extends Controller {

    public function actionPush()
    {
        return $this->asJson([
            'success' => TRUE,
        ]);
    }
}

And I just want to see this URL work: http://localhost/my-module/scrape/push

But instead I get: HTTP 404 - Template not found

I'm sure I'm missing something really dumb here. Any ideas?


texts: Craft CMS 3 - I have used the CLI ./craft setup script to set the database connection on my local machine. I setup a MySQL connection, but when it attempts to validate my credentials, I get "failed: could not find driver". However, when I make a direct MySQL CLI connection using the same credentials, it works just fine. Why can Craft CMS not connect to my local database?


texts: Is it possible to combine information from two blocks from a matrix to an if function?

texts:
I have a check box field called requiredPrograms, in it it has a selection of programs you can choose from. This is within a matrix field called Work shop Instructor which is for my workshop channel.

On my outside workshop page I'd like to display what programs are required for all the teachers at the workshop in the one spot. On the inner page they would be broken into separate programs per instructor.

I've done the inner page with no issue but I cannot figure out a way to do the outer one.

{% for block in entry.workshopInstructor[0] and entry.workshopInstructor[1] %}
   {% if block.requiredPrograms.contains('Photoshop')%}

Foo

   {% endif %}
{% endfor %}

That is my current attempt but this results in nothing being displayed and other attempts have only produced the output twice.

Any suggestions?


texts:
Below is my paginate code and it's working fine.

{% paginate craft.entries.section('products').limit(9) as entriesOnPage %}

{% for entry in entriesOnPage %}

                {{ entry.category.first().title }}

{% endfor %}

{% if paginate.nextUrl %}
    Next
{% endif %}

{% endpaginate %}

Below is my code to display specific category data with pagination. and it's not working.

{% set requestCategory = craft.request.getLastSegment() %}

{% paginate craft.entries.section('products').find({
    search: 'categories:' ~ requestCategory,
  }).limit(9) as entriesOnPage %}

{% for entry in entriesOnPage %}

                {{ entry.category.first().title }}

{% endfor %}

{% if paginate.nextUrl %}
    Next
{% endif %}

{% endpaginate %}

i want to add category filter on that but not working how can i add a category filter?


texts:
I need to get the content of a field in the Matrix of the English localization in my template. I already have the handle of that field for the current language, but I don't know how to get the English version for that field...

I found this for getting a field of a Matrix:

{% set fields = craft.sections.getSectionByHandle('news').getEntryTypes()[0].getFieldLayout().getFields() %}

But that works of course again only for the field in the current localization... which I already have.


texts: Can't Backup Database - "Failed with exit code 1" (WAMP Server)

texts:
I'm running Craft 3 on a local windows machine, but every time I try to update certain plugins (or Craft itself) I get a message "Couldn't back up the database. How would you like to proceed".

The logs give the following:

[error][craft\controllers\UpdaterController::actionBackup] Error backing up the database: The shell command "mysqldump ..." failed with exit code 1.

(I've removed most of the error code for the actual query, let me know if that would be useful).

I'm aware there are well documented hurdles with mysqldump and localhost, but I've already tried the proposed solutions here, here and here.

The global (not local, though I've tried both) PATH env has been set with the root of my MySQL folder ("C:\wamp64\bin\mysql\mysql5.7.26\bin") and I've restarted my machine, server etc. but still get the same error. I've also confirmed mysqldump is running and available in a normal terminal.

I've also tried the official guide to get MAMP working, tweaked as best I could for Windows (though I'm far from experienced so could have done something wrong) and that did nothing either.

I'm running Windows 10 (if that helps).

Any idea what exit code 1 means?

EDIT: See the comments below, but I've almost cracked this. My remaining issue is that I can't find any examples of the my.cnf file. Doesn't seem to be present on any Craft installs I have access to (though only this one has this issue), which means I can't manually generate it and Craft seems to be failing to do so. Any ideas?


texts:
We are developing over multiple environments and production stages, and we would like to be able to track the SQL changes that happen when we make a change to entries etc. on the CP. The changes don't seem to be very easily transferable between productions e.g. Development and Staging through something like an mysql_delta.

Is this possible already? If not, what would the process be to record the SQL?


texts: Entries Field Type showing all entries instead of entries selected

texts:
I am new to craft and twig and need some help showing only added entries to matrix block. What I have now is showing all entries from the section. I may be going about this all wrong, I don't know. I have 11 entries but only want to show the 6 I have added to the block.

    {% for block in entry.sessionsContent.all() %}

{% switch block.type %}

    {% case "sessionsHeader" %}

{{ block.headerTitle }}

    {% case "sessionsIntro" %}

{{ block.introTitle }}

{{ block.introDescription }}

    {% case "sideBlock" %}
    {% if block.isWhiteBackground %}
        {% set divColor = 'white-background' %}
    {% endif %}
    {% if block.isBlockOnTheRight %}
        {% set divPosition = 'float-right' %}
    {% endif %}

{{ block.blockTitle }}

{{ block.blockTeaser }}

{{ block.blockDescription }}

    {% case "backgroundImageDivider" %}

{{ block.dividerTitle }}

{{ block.dividerDescription }}

{{ block.button }}

    {% case "blockTiles" %}

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

{{ entry.sessionTileTitle }}

{{ entry.sessionTileDescription }}

    {% endfor %}

    {% default %}

{% endswitch %}
{% endfor %}


texts:
I am using a similar approach with the code provided here.

I am able to get an initial block to save, but when I go back to the form and try to add another a new block is not created. My application is basically to add notes to an entry. The notes contain an editorName, reviewNotes and a datetime stamp.  What am I doing wrong?

<input type="hidden" name="fields[editorialHistory][new43][type]" value="block">
<input type="hidden" name="fields[editorialHistory][new43][fields][editorName]" value="{{currentUser.getFriendlyName()}}">
<input type="hidden" name="fields[editorialHistory][new43][fields][reviewDate]" value="{{"now"|date("F j, Y, g:i a")}}">


texts: Using a Lightswitch to insert a class on a body's tag

texts:
I'm trying to use a Lightswitch field to insert a class on my body tag if the field is turned on.

What would be a good Twig template code to do this?

Edit 1:

Thanks for answering, guys. I still couldn't manage to do it, though. My lightswitch field handle is named whiteText. If I do this:

<body class='{% if whiteText('1') %}white{% endif %}'>

it'll just say:

  The function "whiteText" does not exist

(which I assume seems logical for you guys, but not for me).

And if I use entry.whiteText it'll say:

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

I should also have some kind of "else" in the code, to output a clean -tag if the lightswitch is not switched on.

Edit 2:

I have now set up a global field. If I do {{ globalfieldhandle.lightswitchfieldhandle }} it outputs 0, even on the craft entry section I have it switched on (a single).

I need a way to make it say "1" if the lightswitch is turned on on the entry, and some help with the code to add a class on the body tag, and also the code for doing nothing if its not turned on.

Anyone?

The first answer to my question:

<body class='{% if lightswitch_field_handle %}class_name{% endif %}'>

seems like the right direction, but is it missing something?


texts:
I'm building a search form with filters. This is one of the filters.
I would like to use the parameter "agent" and have it search a text field called "listingAgent" and "coListingAgent" to check for a match either place.  I tried the code below, but can't seem to get it to work.

    {% set getAgent = craft.request.getParam('agent') %}
    {% if getAgent %}
        {% set params = params|merge({ 'listingAgent':getAgent, 'coListingAgent':getAgent }) %}
    {% endif %}

additional info:
I noticed that setting the params twice (like below) is looking for a match in both fields. I am looking for a match in either field. Does anyone know how to go about doing this?

{% set getAgent = craft.request.getParam('agent') %}
    {% if getAgent %}
        {% set params = params|merge({'listingAgent':getAgent}) %}
        {% set params = params|merge({'coListingAgent':getAgent}) %}
    {% endif %}

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


texts: How can I prevent "spam" user registrations?

texts:
We recently launched our first site with front end user registration and we are getting a lot (not a ton, like 5 a day) spam registrations. See here:

Im trying to find a way to cut down on these without doing something like a captcha but maybe thats my only option?


texts:
I am fairly new to Craft CMS but have a good understanding of it. I have a page that has a Matrix field to display staff photos and their roles.

On the initial load of this page, it is slow, it takes nearly 22 seconds. It is only 1meg of data.

Some stats on the initial load:
• DB queries 200
• 22 seconds to load

Once it has been loaded into the cache it is much better:
• DB queries 165
• 1.6 seconds to load

I have tried eager loading the image field and image transform with no speed increase:

{% set teamMembers = entry.teamMembers.with([
        ['blockType:image', {
            withTransforms: ['teamMemberSmall']
        }]
    ]).all()
%}

It's not a huge amount of data so I would have thought this could be much faster. Based on the profiling it looks like it is the asset transform generation that is killing the page. Any tips or tricks I can do to get that initial page load faster? Can the assets be pre-generated?

Server stats:

PHP 7.2
MYSQL 5.5
Memory Limit 256mb


texts: Building an accordion with a Matrix field

texts:
I'm trying to build an accordion in my matrix field (that also holds entries for a slideshow, button, image, etc).

Im having trouble with getting each entry to go inside

 and not repeat this accordion div over and over.

{% elseif block.type == "sectionaccordion" %}

      {% for block in entry.sectionaccordion %}

{{ block.accordionTitle }}

          {{ block.accordionText }}

      {% endfor %}

With this setup, I keep getting Craft\EntryModel and its behaviors do not have a method or closure named "sectionaccordion".


texts: When uploading an asset, the asset is not selected after upload

texts:
When uploading an asset through either the assets tab, or within an asset field - the asset uploads successfully but doesn't get automatically selected for insertion.

To get around the issue I have to search for asset filename and then select it.

Ideally the asset should get selected by default ready to be inserted by clicking 'select'.

We have quite a few assets, so there is auto pagination/load more which might be causing the issue?

Any help appreciated.


texts: Rich Text - Redactor doesn't allow iframe even when in allowedTags config setting

texts:
I've updated my craft/config/redactor/UserContent.json settings with allowedTags containing iframe but iframe tags are stripped on save.

Other added allowedTags seem fine and iframe works on paste and initial editing, just not after saving.

Running Craft Pro 2.4.2679

I see there were issues with this for older versions of Redactor but they seem to be resolved. Any ideas about how to fix this?

Here's my UserContent.json:

{
    toolbarFixed: true,
    buttons: ['html', 'formatting', 'bold', 'italic', 'underline', 'deleted', 'horizontalrule',
              'unorderedlist', 'orderedlist', 'alignment', 'indent', 'outdent',
              'link', 'image', 'video', 'table'],
    removeEmpty: ['p','strong','em','span','a'],
    cleanStyleOnEnter: true,
    plugins: ['video', 'table'],
    allowedTags: ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'blockquote', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'map', 'mark', 'menu', 'nav', 'ol', 'optgroup', 'option', 'p', 'picture', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'small', 'source', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr'],
}


texts: Date conversion returning December for every single digit month representation

texts:
I can't figure out what I'm doing wrong, but trying to convert single digit months to their name representations (ex. '4' to 'April' in English) but am just getting December printed out for every single one. I can't compare to month names because the site is in quite a few languages, so need to actually use the date functionality.

{% set groupedEntries = entriesInYear | group("postDate|date('n')") %}

{% for key, eachMonth in groupedEntries %}
    {% set monthName = date(key) | date('F') %}

        <a href="{{ craft.languageLink.url(craft.locale, urlParam) }}"
            {{ monthName }}, {{ eachMonth|length }}

{% endfor %}

'Key' is the month representation with no leading 0's (4, 3, and 2 for posts that exist in April, March and February).

Getting output as:
December, 4
December, 4
December, 2
(following number is number of posts in that month)

WHAT the heck am I doing wrong?


texts: searching assets - using related entry slug

texts:
For a website I'm currently building I have a bunch of photos within an Assets folder (folder id of 5) that I have linked to "Photographer" entries within a "Photographers" structure.

I am now trying to search by the photographer slug in order to show photos for a specific photographer:

{% set searchQuery = "photographer::example-photographer" %}
{% set matchingPhotos = craft.assets.folderId(5).search(searchQuery) %}

Unfortunately however the matchingPhotos data set is always empty, even though I'm very sure that a photographer exists with a slug of example-photographer and there are photos linked to this photographer in the assets folder..

Is the way I'm trying to search correct?

Thanks!


texts:
i think the following code shows the problem:

{% for entry in craft.entries({ section: 'news', limit: 2, **id: not this_id** }) %}

the big one doesn't work in this way. Has anyone an idea?

The content of this_id is a number.

Thank you!


texts:
Is it possible to pull an image from another entry? It seems like it would be simple. I've read a lot of posts and documentation, and feel like I'm close...

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

{% for image in entry.podcastItunesImage %}
    <itunes:image href="{{ siteUrl }}{{ image.getUrl}}" />
{% endfor %}

Basically, I'm trying to put an asset field on the Homepage for a iTunes image.


texts: Is it possible to grant admin permissions via plugins through userPermissions->saveUserPermissions?

texts:
I'd like to add admin privileges to a user I'm creating like so:

  if($user == null)
  {
    $firstName = $_GET['firstName'];

    $lastName = $_GET['lastName'];
    $userName = $firstName . $lastName;
    $user = new UserModel();

    $user->username   = $userName;
    $user->email      = $email;
    $user->firstName  = $firstName;
    $user->lastName   = $lastName;

    craft()->users->saveUser($user);

    $permissions = [HOW DO I SET ADMIN PERMS?]
    craft()->userPermissions->saveUserPermissions($user['id'], $permissions)

}


texts: What is appropriate for a Global field in terms of site speed?

texts:
I'm worried that if I put too much in globals, I will impact the speed of my site by a lot.

For example, I was thinking of putting content in there like matrices for team members (text and image), testimonials, award's (text and images), etc.

Is this content better put somewhere else? I know globals are called on every single site load, so I'm not sure if having that type of content in there is a bad idea.


texts:
What's the best known way to import masses of data into Craft?

Are there tools that support the migration of content/users from say XML, JSON etc.


texts: Missing templates using PHPStorm when using Craft 3

texts:
Following code show a warning "template not found" in PHPStorm:

{% extends '_layout' %}.

When adding .twig this warning dissapears, but I'd like to keep extends and includes filetype agnostic.

What I've tried so far:

Installing the Symfony plugin and enabling Twig support.
Adding the templates folder as a Twig directory, as described here.
Invalidate PHPStorm cache and restart.

Is there a way to fix this? Or should I use {% extends '_layout.twig' %}?

Using PHPStorm 2019.1


texts: Caching in Craft 3 causes out of memory when including grouped for loop

texts:
I have a problem with using {% cache %}in Craft 3, although the code runs fine without caching, and it works in Craft 2.

I have narrowed the problem down to the following code:

{% cache %}
  {% set upcomingShows = craft.entries.section('shows').orderBy('showTime asc').limit(null).all() %}
  {% for date, shows in upcomingShows|group("showTime|date_modify('-3 hours')|date('Y-m-d')") %}
    {% for show in shows %}
      {% set movie = craft.entries.relatedTo({ targetElement: show }).one() %}
    {% endfor %}
  {% endfor %}
{% endcache %}

It gives me the following fatal error:

Allowed memory size of 268435456 bytes exhausted (tried to allocate 71002178 bytes)

If I skip the Twig |groupfilter, the cache works again:

{% cache %}
  {% set upcomingShows = craft.entries.section('shows').orderBy('showTime asc').limit(null).all() %}
  {% for shows in upcomingShows %}
    {% for show in shows %}
      {% set movie = craft.entries.relatedTo({ targetElement: show }).one() %}
    {% endfor %}
  {% endfor %}
{% endcache %}

(I first thought the problem was the relatedTo() function, but it turns out it's the |group is what triggers it, without it it works also with the  relatedTo().)

Is this a bug in the cache, or is there a way around it?

UPDATE: After some more testing, it seems like it works either with the |group filter or the relatedTo() function, but not both at the same time.


texts:
I want to do exactly this: Multi-step & bi-directional relations with relatedTo (#1640)

  Common example: Let’s say you have Books, Authors, and Publishers, and two relationship fields on the Books channel: author and publisher. On a Publisher’s page, you want to list all of the Authors that have published books with them.

Here’s what I’ve tried:

{% set bookIds = craft.entries()
.section('books')
.relatedTo({ targetElement: publisher, field: 'publisher' })
.ids() %}

{% set authors = craft.entries()
.section('authors')
.relatedTo({ sourceElement: bookIds, field: 'books' })
.all() %}

However the code results in an "Undefined offset: 0" error. The error seems to occur in the first block of code.

Additionally, I'm not sure about the field in the penultimate line, shouldn't it be 'authors' rather than 'books'?


texts: "Email" Control Panel Settings page is blank

texts:
I'm currently unable to access my 'Email' control panel settings page. When the page loads it's completely blank, and the body of the response is simply the scripts that log the Application Log and Profiling Summary Report to the console.

Every other settings page works fine.

I've tried disabling all plugins (currently just one), but this did not have any affect.

Craft is up-to-date as of today at 2.6.2967.


texts:
Entries in a particular section have expiration dates of up to one year away. The client would like to receive a notification email two weeks before this expiration date is reached.

Here's a bonus question: These entries are connected to another section of vets. Each vet entry will have an email field. Whatever vet is connected to the original entry in question (the one with the expiration field) also needs to receive this notification email.

Are there any existing plugins that allow this? I haven't found any yet.

Thanks!


texts: Use Matrix to let client add Bootstrap Accordian Items

texts:
I'm creating a careers page on a site I'm working on and the design is for the jobs to go in an accordian that will slide open on click. So I'm thinking that this would need to be a matrix block as the client will need to be able to add as many jobs to the accordian as they want.

The site is built with bootstrap, so I'm using the bootstrap accordian to build it. And for it to work each accordian item needs to have a unique ID, i.e. id="collapseOne" which links to href with the same name in the button in order to get it to expand and close. Here's an example of the code for one accordian line:

          Senior Construction Planner

    ..variable content..

So I need to work out a way to get this to work as a matrix field so that the client can add as many jobs as they need in Craft, and for it to function correctly as an accordian.

Is it possible?


texts: Is there a way to add a button to remove the current styles inside of a Rich Text field? I know there are options for customizing the toolbar, but I haven't found anything about removing styles. Any ideas?


texts: Can you get only fields marked as required via a plugin?

texts:
Is it possible, on a model, to get only the fields that were marked as required?

For example I have an entry which has just been saved and I can get it's content like:

$entry->getContent()->getAttributes()

But I need to filter it out by the only the fields that were required, because it already has a section assigned and is saved I thought this might be possible...I tried $entry->getRequiredFields() but that didn't work.

So then I tried these to no avail

$entry->getContent()->getRequiredAttributes()
$entry->getContent()->getRequiredFields()
$entry->getRequiredAttributes()

Is this actually achievable? any help or pointers would be much appreciated! :)


texts: Can slug and title changes be propagated to multiple sites?

texts: I'm noticing that if I change the title or the slug of an entry after creation, that change isn't propagated to my other Craft sites.  Is there a way to propagate title and slug like other fields?


texts: Commerce: Is there a way to use a countries dropdown with iso codes (US, CH etc) instead of ids?

texts:
Here's some code from Craft Commerce's examples:

<form method="POST" accept-charset="UTF-8" class="ui form validate">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="commerce/cart/updateCart" />

    [...]

    {% set countries = craft.commerce.countries %}
    {% if countries|length > 1 %}

            {{ "Country"|t }}
            <select name="{{ modelName }}[countryId]" class="ui fluid dropdown">
                <option value="">{{ "Choose Country"|t }}</option>
                {% for country in countries %}
                    {% set optionValue = (model ? model.countryId : '') %}
                    <option value="{{ country.id }}"{% if country.id == optionValue %} selected="selected"{% endif %}>{{ country.name }}</option>

{{ country.name }}

                {% endfor %}
            </select>
            {% if model and model.getErrors('countryId') %}
                {{ model.getErrors('countryId')|join }}
            {% endif %}

    {% endif %}

    [...]

</form>

I wonder if it's somehow possible to work with the country code (e.g. US, CH...) instead of the country id of Craft Commerce (1..256). So basically, countryId vs. countryIso?

I can't find any information in the docs.

It might be a small detail, but when using form autofill with programs like 1password, it won't be able to fill in the country automatically when using an id vs. a country code.


texts: Project file changes causing `SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY'`

texts:
I switched over to use project file settings and now I occasionally get a constraint violation when trying to run the craft projectconfig/sync command.

I think this is a bug, because the

UPDATE `info` SET `id`=1, `version`='3.3.0.1', `schemaVersion`='3.3.3', `maintenance`=0, `config`=' ...`

statement seem to be missing a WHERE, which means it tries to set ALL rows in table info to the same values. For some reason, I end up having 2 rows in info where the one with id=2 is basically empty.

This is on version 3.3.0.1.

Invoking a DELETE FROM info WHERE id = 2; resolves the situation in my case, but it is a bit cumbersome that this happens.


texts: Removing /index.php/ from url breaks site

texts:
When I try the solution mentioned here, my site breaks, pages not found. Even the /admin/ pages break, losing all styling. The only page which loads is the homepage.

Any thoughts about why? I was having htaccess issues, but I believe those are all fixed now.

This is the htaccess file in the the top level craft folder

<IfModule mod_rewrite.c>
    RewriteEngine On

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

There is the root:
brianfeeney.us/

Which contains both:
brianfeeney.us/blog (WP)
brianfeeney.us/craft

The index.php in my root points towards /blog/

thanks for the help


texts: AttributeType::Number giving validation error "Must be an integer"

texts:
So I have a model attribute attributeName with an AttributeType::Number

I haven't implemented any personal validation rules yet, however when I run:
model->validate(),
its giving me a "attributeName must be an integer" error.

Is this just the default validation rule of the AttributeType::Number?  and if so, is there anything I can do to make it accept floats?

I am trying to use this attribute for a price, I should note.

CNumberValidator has an integerOnly attribute, so I tried setting 'integerOnly'=>false in the attribute declaration, to no avail. Not sure if its relevant, I think I might be grasping at straws. Any help would be greatly appreciated!


texts: Extending Craft controller classes and using private methods in child class

texts:
I created Controller that exptends Craft AssetsController. Hovewer some of AssetsController methods are private - and I cannot use them using $this context in child module, so i just copied them to child module.

Is there any other way?


texts: How to auto disable "Enabled for Site" for certain sites (or groups) when creating a new entry

texts:
We have a mutli-country/language website with Craft 3 for many countries/languages.

When we create an entry (ecommerce product to be exact) in the English sites we dont want to enable it for other language sites as we would not have the content yet. We only want it enabled for English.

If we disable "Enabled for Site" in the new entry, this does not carry over onto the other sites, the other sites entry are all Enabled for Site.

So we have to go into every languages's entry and disable Enabled for Site to disable it for other languages.

Trouble is we have a lot of languages, its a real pain to have to do this each time.

Ideally when an entry is created we should be able to somehow choose its only enabled for this site OR group the site is in (we group languages by Site groups). Or choose sites or groups to not enable.

Does anyone know how we can auto set it to disabled for all the non-English groups when we create a new entry?

Thanks


texts: How can my plugin use Craft's native dragdrop support

texts:
I am using a generic Garnish modal from Craft like so:

$container = $('.upload-modal');

$modal = new Garnish.Modal($container, {
    autoShow: false
});

I would like to have craft's native drag&drop support in this modal, i tried something like this

$dragDrop = new Garnish.DragDrop({
    dropTargets: ['.upload-modal__drop']
});

Can someone point me in the right direction. I tried to find some answers here:

https://github.com/pixelandtonic/garnishjs/blob/master/src/classes/DragDrop.js

Eventually what i am trying to achieve here, is a basic modal without any link to existing assets or so, for uploading a file with dragdrop and file select functionality. This file when processed by the plugin needs te be deleted afterwards.


texts: Registering events for a specific feed in Feed Me

texts:
I'm working with Feed Me to run several feeds, bringing in multiple Entry types. I need to do some additional preparation work via an EVENT_AFTER_PARSE_FEED handler, which works well when I only have a single feed, but fails when I add a second feed.
I want to run the event handler for Feed A, but not for Feed B: Is there a simple way of specifying the feed when registering the event handler, or querying the event name inside the event handler?


texts:
I am sure this must be answered somewhere and I cannot find it.  I need to grab all images from a section (channel) and display them in a slide show on the index page (index page is a single,so index page of the entries from that section). I just cannot seem to get this correct.  Here is what I am trying

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

so stories is the section where the entries are.

Then

{% for previewImage in storyItem.slideshowImage.offset(1) %}
 ...
{% for previewImage in storyItem.slideshowImage.limit(1) %}
...
{% for previewImage in storyItem.slideshowImage.offset(1) %}

The limit and offset are just to make the slider I have work and that does work on another page so that does not seem to be what is stopping me here.  I am somewhat new to craft and my gut is telling me this is a simple answer but I have been stuck on it for a while now and coming back to it off and on to no avail.


texts:
I've created a new section, with one entry. When I want to live preview the entry, the live preview button isn't there.

I've read this is because my new section doesn't have an active template? How do I resolve this?

I'm very new to this!


texts: Multiple Prices based on User in Craft Commerce

texts:
This is my first time using Craft Commerce.  I have a client which needs to have multiple prices for a product.  Customers are in one of three price level groups.  Each price level group has a price unique to them as a variant.  How do I get only the one variant for the appropriate price?

Here is what I tried, but returned all the variants for each price level instead of just one.

                <select name="purchasableId">
                    {% set purchasable = craft.commerce.products %}
                    {% for purchasable in product.variants %}
                        <option
                            {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %}
                            value="{{ purchasable.purchasableId }}">

                                Product Number: {{ product.stockDescription1 }} |
                                Price:

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

                                    {% set variant = craft.commerce.variants %}
                                    {% for variant in product.variants %}
                                        {% if variant.priceLevel1 == 1 %}
                                            Product Number: {{ product.stockDescription1 }} |
                                            Price:
                                            {{ variant.price|currency(cart.currency) }}
                                        {% endif %}
                                    {% endfor %}

                                {% elseif currentUser.isInGroup( 'priceLevelTwo' ) %}

                                    {% set variant = craft.commerce.variants %}
                                    {% for variant in product.variants %}
                                        {% if variant.priceLevel1 == 2 %}
                                            Product Number: {{ product.stockDescription1 }} |
                                            Price:
                                            {{ variant.price|currency(cart.currency) }}
                                        {% endif %}
                                    {% endfor %}

                                {% elseif currentUser.isInGroup( 'priceLevelThree' ) %}

                                    {% set variant = craft.commerce.variants %}
                                    {% for variant in product.variants %}
                                        {% if variant.priceLevel1 == 3 %}
                                            Product Number: {{ product.stockDescription1 }} |
                                            Price:
                                            {{ variant.price|currency(cart.currency) }}
                                        {% endif %}
                                    {% endfor %}

                                {% endif %}
                        </option>
                    {% endfor %}
                </select>


texts:
I want to fetch a specific block from a Matrix global then pass it through a macro which returns a response based on the block type. However, if I try to use slice the type doesn't appear to be available to the macro. Has anyone experienced something similar?

eg if I set {% set timelineText = timeline.timeline %} (where first timeinline is my global and second timeline is my Matrix field) then fetch a specific block from the Matrix: {% set period = timelineText|slice(0,1) %} should return the first instance/block from the field. I can then pass this to my macro: {{ _self.doPeriod(period) }}

My macro is

{% macro doPeriod(content) %}
{% switch content.type %}
{% case 'quote' %}
    ...
{% case 'period' %}
    ...
{% endswitch %}
{% endmacro %}```

But this returns the following error: Key "type" for array with keys "0" does not exist

Any thoughts?


texts: Assign a user group to a structure entry. Restrict permission front end page to that same group

texts:
I'm working on a website for a school. Each group has a specific page that has video's for that group only. Members of that group do not need access to the CP. First I noticed that I can only assign specific members to an entry, using the Users field. I'm not able to assign a group at once.

How can I make it possible for the teacher to assign a group to a video through the CP (not the code), and that only that group can view the page after login?


texts: Idea for matrix alternative for multisite setup. Feedback needed!

texts:
We have a site that has relied heavily on the use of matrix fields to act as a content builder for several pages on our site. We are now in the process of localizing the content, and have set up language based site groups to utilize group based translation methods for fields in the matrix.

This has worked fine, and would work if the content remained consistent throughout the various sites, but we're now seeing the need to allow for some site specific content in certain places. A product may not be available in a certain region – so promoting it doesn't make sense, or a holiday may only be relevant in the US. Whatever the case may be, matrix fields and their translation methods are proving to be limiting.

We want to reduce the amount of redundant content that needs to be managed (via language based site groups) while allowing content to be flexible enough to target specific regions.

We have an idea on how to solve this, but want to get some feedback and see if there are any good alternatives.

Let's say we have a Homepage single entry. We want the US market to display a unique content block in addition to what other English sites show.

We could create a section called Content Blocks that has an entry type that matches our current matrix blocks.

Each entry in Content Blocks would be pulled into the Homepage entry via an entries field. The entries field would act as our list of components – much like in a matrix field.

The default state of the Content Blocks entry would be disabled for each site, and translations would be based on site groups (language). Entries added to a site's Homepage entries field would display each related entry (assuming it was enabled for a given site), allowing translations to be made before content is published.

This would require some additional planning from content authors, but could prove to be more flexible and resilient. Content Blocks could be reused between various sections, or toggled between as different holidays occur.

I can also see this getting out of control with many unused or poorly named entries living in Content Blocks.

As an added bonus, this setup might allow us to integrate with a 3rd party translation service to import content translations. Something that seemed impossible when dealing with matrix blocks.

Are there any unforeseen issues with a setup like this? Specifically thinking about performance.
Are there better alternatives or something that we're not thinking about?


texts: Best way to include attachments using EmailService [Craft Plugin]?

texts:
I've got Email Service working correctly (http://buildwithcraft.com/docs/apis/emailservice) but what's the best way to include attachments when using this service?

Here's what I've got so far:

    $email = new EmailModel();
    $email->subject = "Thanks!";
    $email->htmlBody = "
Congratulations!
htmlBody .= "
Hello World
";
    $email->fromEmail = "email@domain.com";

I see there is $email->addAttachment but I'm not sure what variables to include to make it pass through the service.

Anyone have any examples?


texts: How do I stop an element from populating?

texts:
I have an event listener on elements.onPopulateElement, what I want is make a last minute decision if I want to populate or not. I have certain customfields on an admin CP user (eg company). All entries (in this case in the section "normalUsers", these are entries not actual users) have that same field company (companiesDropdown). I can detect in the code below that the entries' companiesDropdown field does not match the currentUsers companyDropdown field. But how can I tell the calling piece of code not the populate this element?

The following code it initialised in the plugin init method

private function _initEventPopulateNormalUser() {
    craft()->on('elements.onPopulateElement', function(Event $event) {
        $this->_getNormalUserSection();
        // HERE we check if we actually save a normalUser section entry, may be a bit brute force, we will polish that later
        $lCompanyIdEntry = $event->params['element']->getAttributes(array('sectionId'));
        if (! isset($lCompanyIdEntry['sectionId'])) return;
        if ($lCompanyIdEntry['sectionId'] != $this->mNormalUsersSection) return;

        $lCurrentUser = craft()->userSession->getUser();
        $lCompanyIdUser = $lCurrentUser->companiesDropdown[0]->id;

        $lEntryCompanyId = $event->params['element']->companiesDropdown->first()->id;

        if ($lCompanyIdUser != $lEntryCompanyId) {
            /*
                Somewhere here I want the element to be emptied and
                all functionality calling it, like a elementindex template,
                to not show the element in its listing
            */
        }
    });
}

private function _getNormalUserSection()
{
    if (is_null($this->mNormalUsersSection)) {
        $lSection = craft()->sections->getSectionByHandle('normalUsers');
        $this->mNormalUsersSection = $lSection->id;
    }
}


texts:
I want to put the index of section in order by two fields: featured and startDate. Basically, I want the featured entries to rise to the top of the index, and then within the featured posts I want them to be sorted by startDate field. Below the featured entries, I want the other entries to also be sorted by startDate.

I tried entries.order('featured desc').order('startDate desc') but, as I expected, it simply ordered by startDate because that method executed after ordering by featured.

Is there any way to achieve what I'm tring to do?


texts: Plugin Installation Error in Craft 3 / PHP Version

texts:
I tried to install "Field Manager" Plugin and get following error:

symfony/console v3.4.4 requires php ^5.5.9|>=7.0.8 -> your PHP version (7.2.1) overridden by "config.platform.php" version (7.0) does not satisfy that requirement.

Theres is no config.platform.php anywhere and i have PHP 7.2.1 installed. How can i fix that?

EDIT:
Ok, config.platform.php refers to composer.json entry. I changed it to 7.2 and could install it via command line. Possibly worked via CP too.


texts: Order a list of categories by number of entries, key not being set

texts:
I have modified the code from this question but I'm running into an issue.

{% set allCats = craft.categories.group('blogCategories').level(1).find() %}

{% set catArray = {} %}

{% for cat in allCats %}

    {% set catArray = catArray | merge({(cat.id):craft.entries.relatedTo(cat).total() }) %}

{% endfor %}

{% set catArray = catArray|sort|reverse %}

{% for catId, count in catArray %}

    {% set category = craft.categories.id(catId).first() %}

        {{ category.title }} {{count}}

{% endfor %}

Ive ran a dump on the catArray array and the category id isnt being set as the key, regardless of if I try put brackets around it to protect it, I only get the value in the array.


texts: How to structure this multiple relation?

texts:
So I have these sections and fields that I'm dealing with:

candidates

Name
Pic
Bio

answers

relatedQuestion
Body
relatedCandidate

questions

title
body

candidateGroup

title

I'm outputting a single page using the question:

Question and Info

Candidate Group Name

Candidate

Answer

Candidate

Answer

... Repeats ...

So my current setup looks like this:

{# Get the answers that are related to the question entry #}
{% set relatedAnswers = craft.entries.section('answers').relatedTo(entry) %}

{# Loop through categories #}
{% for category in craft.categories.group('candidateGroup') %}

  {{ category.title }}

  {# Get me the candidates that belong to this category and have an answer related to this question entry #}
  {% set candidateAnswers = craft.entries.section('candidates').relatedTo('and',
    category,
    relatedAnswers
  ) %}
  {% for candidateAnswer in candidateAnswers %}

    {# Output the candidate's info and their answer #}

  {% endfor %}
{% endfor %}

I feel like this is right and it seems to be working locally but when I get it live on the site it's having issues recognizing what "entry" it's a part of. No matter what entry I go to via url, it outputs the same answers.

I tried to do a simple loop to see what relatedAnswers outputs, and it's the right information. It's just getting lost in that inner loop somehow.

Update:
I believe it is working locally just fine. But for some reason, on my Media Temple hosted site, it's not outputting in the same manner. I double and triple checked all the fields and couldn't find any differences?

Update 2:
I can't figure this out for the life of me. It works fine on local, just not on production. I checked the database to see if there anything out of the ordinary and it looked fine to me. I installed the introvert plugin to see if the relations were working properly and they seem to be just fine. Kind of lost at this point.

Updated 3
I tried it another way:

  {% for category in craft.categories.group('candidateGroup') %}

{{ category.title }}

      {% for answerEntry in craft.entries.section('answers').relatedTo('and',category,entry) %}

              {% set relatedCandidate = craft.entries.section('candidates').relatedTo(answerEntry).first() %}
              {% set asset = relatedCandidate.avatar.first() %}

{{ relatedCandidate.title }}

                {% set categoryCandidate = relatedCandidate.group.group('candidateGroup').first() %}
                {{ categoryCandidate.title }}

            {{ answerEntry.body }}

      {% else %}

          There are no answers from candidates in this group yet.

      {% endfor %}

  {% endfor %}

Unlike the other solution, my problem on the server is that it doesn't return any entries at all. I'm assuming it has something to do with that 'relatedTo(entry)'. It's like it doesn't recognize that at all. In the first case it just ignores it and  in this case it's like it can't read it.


texts:
I've looked at several answers on here regarding this one and as far as I can make out this should bring out all entries related to a specific category slug. However it just seems to be returning all entries regardless of whether it's related or not? What am I missing? Also in case it makes a difference there is one category level but an entry can have multiple categories selected.

{% set category = craft.categories.group('markets').slug('marine').first() %}
{% set products = craft.entries.section('products').realtedTo(category).limit(null) %}
{% for product in products %}
    {{ product.title }}
{% endfor %}


texts: Creating a custom, "multiple dates picker" field

texts:
We're migrating* a website that uses http://dubrox.github.io/Multiple-Dates-Picker-for-jQuery-UI/ to store any combination of dates for an entry... (eg not just a single date or date range, can be lots of individual dates which aren't sequential)
What would be the best kind of field/setup to import these into?
I guess we could create a custom field type that implements the same multipicker as above as it's also based on the jQuery datepicker widget... but have never created a custom field type from scratch though... what is the best approach to this?
(*7000 entries to import via FeedMe, looks like every single date is added to an event table as an individual row and looked up via an id :zany_face:)


texts: Why is Craft storing so much temporary files inside the server tmp folder?

texts:
For several websites (Craft CMS 2 & 3), servers ran out ot storage even if these websites were not storing a lot of assets.

After looking for why, I ended up in the temporary (tmp/) folder of these servers (which is at a lower level of these vhosts), where I found there were a lot of Craft-related filed that were not purged.

These are, for example:

Imagick files (some of them have a size of ~500 Mb!)
A lot of Twig PHP folders and files (which content looks very similar as found in /storage/runtime/)

Questions:

When and why these files are generated?
Why they are not automatilcally deleted?
When is it safe to delete them?

To be more specific:

Because I'm using Imgix, front-end image transforms are delegated to this remote service;
In this case, I think that only the CP uses Imagick;


texts:
Craft 2.6.2972

I've created a new redactor config called Basic Config and saved the json in craft/config/redactor based on this Strait Up Craft post. I then created a field and selected the correct config setting and added it to a channel.

However when I go to edit the entry it's not using my config setting as all the formatting options including code etc are there.

the json is:

{
    buttons: ['html','formatting','bold','italic','unorderedlist','orderedlist','link','image','video'],
    plugins: ['fullscreen'],
    formattingTags: ['p', 'blockquote', 'h3', 'h4', 'h5']
}

Not sure why code, h1, and h2 tags are available when clearly they are not in the above formatting options

Please advise.


texts:
we wanted to remove blog categories pages, author pages, blog tag pages from appearing in Google Search results as they were taking unnecessary real estate. To do that, we used 'noindex' option available in Sprout SEO - > Sections -> Category (Blog) -> Robots -> noindex. (Screenshot 1)

We were able to achieve that and now our these categories pages don't appear on Google. That's good. But on checking our Search Console, Google gives us a warning that we have no-indexed pages in our sitemap. The exact error is "Submitted URL marked ‘noindex’". (Screenshot 2).

Any idea why this might be happening? One of the things I tried is to disable the Section itself which in-result disabled the category sitemap and removed the no-index tag from all the category pages. I think the solution might be if we could noindex pages without creating a sitemap. We have been trying to solve this issue and any help would be beneficial. (I also posted this issue on the plugin's Github and didn't get a reply for about 2 weeks so re-posted it here in a hope to get some insight).


texts:
Is it somehow possible to import a dumped database from the admin control panel?

I'm currently dumping my database in the control panel and import the dumped file in the phpmyadmin interface.

I'd prefer dumping and importing in the control panel


texts: Customising the new CKEditor5 in Craft 3

texts: How do you configure the new CKEditor editor to e.g. add images? Do you create a config/CKeditor folder with a .json file and install the @ckeditor/ckeditor5-image package?


texts: Saving related entry in a Matrix block programmaticially

texts:
I'm trying to add entries to a Matrix block with one field type of 'entry' using the following:

$block = new MatrixBlockModel();
$block->fieldId    = 9;             // Matrix field's ID
$block->ownerId    = $collectionID; // ID of entry the block should be added to
$block->typeId     = 2;             // ID of block type
$block->getContent()->setAttributes(array(
    'contentRss' => array($entry->id)
));

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

The code saves the new block and entry, but when I view the entry it has not linked the entry. I notice in the database tables it has not created an entry in the craft_relations table.

Where am I going wrong? :)


texts: Output Only Entries from Entry Field Related to a Category

texts:
I have a section called "lunchMenu" that contains an entries field ("menuItems").  Each entry in "menuItems" is related to a category in the category group ("foodCategory").  I would like to loop through each of the entries only in "lunchMenu" and output them within their respective categories.

When I loop through the entries field alone, everything works just fine.  However, when I add the relatedTo parameter to sort by category, I get entries that are not present in this section's entry field.

Here's the code I'm using - any help would be appreciated.  I think I'm not understanding the use of the relatedTo correctly.

{% set food = craft.categories.group('foodCategory') %}
{% set entries = craft.entries.section('lunchMenu') %}

    {% for entry in entries %}
        {% for category in food %}
        {{ category.title }}
            {% for item in entry.menuItems.relatedTo(category) %}
                    {{ item.title }}
            {% endfor %}
    {% endfor %}
{% endfor %}


texts: Add custom column to Entry Type index page

texts:
I'm creating a plugin and I've been following the Mijingo Craft plugin development videos. I reached the point where a column was added to the entry index page. I was looking to do something similar but on the Entry type index page /admin/settings/sections/{ID}/entrytypes.

I was unable to find anything in the documentation (maybe I missed something). But is there a method I can use to do this? or is it not possible?


texts:
I downloaded a fresh install of Craft 3.3.20.1 and ran it locally with MAMP. Everything works except that the Settings page gives me the error This page isn’t working \n localhost didn’t send any data. \n ERR_EMPTY_RESPONSE. Anything below the Settings page (eg /settings/plugins, /settings/sections etc) works fine. It's literally just Settings that is broken. I tried upgrading to 3.4.10.1 today and it didn't help.

An added weirdness is that if I reload the Settings page repeatedly, sometimes it will partially load. I have no idea what could cause such intermittent/partial loading. I noticed that I was below requirements on memory allocation and execution time, but when I edited my MAMP php.ini to bring them up to spec, it didn't fix the problem.


texts: Can I atttach uploaded file in A&M Forms to notification email

texts:
I have form created with A&M Forms plugin where the user can upload a file.
I would like to attach the file to the notification email itself.

Is this possible? How?


texts: Is there any way to hook into saving a plugins settings?

texts: I'm attempting to create a plugin that is going to create some basic fields/sections as a post-installation setup. I don't really want to create a full-blown CP entry so is there any way of just doing stuff when the user clicks "save" in the settings template?


texts: Matrix field containing asset field blocks entry editing

texts:
I am new to  Craft CMS and am testing it. I encountered a problem.

I have a matrix field, containing an asset field. When I add this matrix field to the page field layout, then visit single entry, put something inside this asset field of the matrix field and save - things break, I can't access this entry in backend later, all that shows is this:

I have local assets source set up, and images do upload there, I can see them in assets explorer later.

When I just fill in other fields of matrix field, omitting asset field or don't use matrix field at all, things are ok.

I work on Windows, on XAMPP server.


texts: I'm trying to test a new plugin in development, is there any easy way to downgrade the version of craft?


texts: links to another website without my own url

texts:
If I want to link another website, I am doing this with a normal text field.

{{ entry.subHeading }}

subHeading is the link.

If I now click on the text on my website, I get something like this: www.example.com/https://www.google.ch

How can I get my own website text out of the link?


texts: Create an alternate Stripe Payment Method

texts:
Instead of taking payment via the Omnipay/Stripe Payment Method, what I'm trying to do is just create a new Customer and Credit Card on Stripe during Checkout, no payment taken at all at this stage.

Looking through the Stripe code it looks as though that functionality already exists. On the Stripe Gateway, this looks like it should do what I want.

public function createCard(array $parameters = array())
{
    return $this->createRequest('\Omnipay\Stripe\Message\CreateCardRequest', $parameters);
}

What I'm struggling with is how/where to call this and finish up the Order by turning the Cart into an Order.

The Checkout / Payment page submits to the following Controller:

Commerce_PaymentsController->actionPay()

I could just duplicate the functionality in here swapping out what I don't need, but this feels really hacky/wrong!

Has anyone any suggestions for a more sensible approach?


texts:
We have received the Craft CMS and design files from our web developer with content already loaded into the Craft backend.

All of the frontend displays correctly but we are able to edit all the textual content in the 'Globals' sections and save it but when we edit any text/fields in the 'Entries' section and save the changes, the page reloads with the old content which hasn't been updated with the changes.

Does anyone know a fix for this?


texts: Check which locales of an Entry are active

texts:
I have a section called News with 2 locales: 'en' and 'nl'. For some News items I have both languages switched on and for some only 1 language. The screenshot shows an example of an entry with only 1 language switched on.

Is there a php method to check the Entry object which languages are switch on?


texts: Copy the Entry Type along with its field layout

texts:
For a current project, I am attempting to automate the creation of a section.

I am using a default_section as the base of all the others. This section will contain a couple of entries, and a couple of entry types.

My goal right now is to copy over the Entry Types in its totality. Right now, I'm struggling with the field layout that I have set for the Entry Type

Let's say that the first Entry Type has the following field layout:

And this is the code that I am using

private function copyEntryTypes($savedSection, $entryTypes)
{
    foreach ($entryTypes as $entryType) {
        $copiedEntryType = $entryType;

        $newEntryType = new EntryTypeModel();
        $copiedEntryType->id = null;
        $copiedEntryType->sectionId = $savedSection->id;
        $values = $copiedEntryType->attributes;
        $newEntryType->setAttributes($values);

        $currentLayout = $copiedEntryType->getFieldLayout();
        $currentTabs = $currentLayout->getTabs();
        $postedFieldLayout = array();

        foreach ($currentTabs as $tab) {
            $fields = $tab->getFields();

            foreach ($fields as $field) {
                echo '<pre>' . var_export($field->attributes) . '</pre>';
                $postedFieldLayout[$tab->name][] = $field->fieldId;
            }
        }

        $requiredFields = array();

        $fieldLayout = craft()->fields->assembleLayout($postedFieldLayout, $requiredFields);
        $fieldLayout->type = ElementType::Entry;
        $newEntryType->setFieldLayout($fieldLayout);

        //TODO: New Entry Types are succesfully being copied. Now all I need is to move over the fieldset

        if (craft()->sections->saveEntryType($entryType))
        {
            var_dump('Successfully appended fields.');
        }
        else
        {
            var_dump('Could not append the fields.');
        }
    }

    return true;
}

//note: this code is WIP, so it's not super clean, sorry.

The result is that the fields are being looped through correctly, I can var_dump them and find the correct ID's. The problem is that the resulting EntryType I have made does not contain the layout I am trying to copy over.

That's looking like this:


texts: How do I assign a language to all datetime outputs

texts: I am building a german calendar and am struggling having one language throughout all datetime outputs. The website is set to lang = de but the outputs of the solspace calendar is still english.


texts: Why is the Algolia index population process with Search Plus timing out?

texts:
I'm at a loss here. Hopefully, someone here can shed some light into a Search Plus plugin and Algolia index population issue I'm having.

I'm able to add an item (page, blog post, product) to the item's respective index by editing the item but when I kick off the Search Plus index population process it quickly times out/fails. I have an index that literally has one item.  It populates the index when I edit it but the same item does not get added to the index when done via the Search Plus index population process. I'm skeptical that this is an Algolia API record size limit because I just described but I could be wrong.

I do see the following errors in the Craft admin console:

2019-03-21 22:38:52
Level   error
Category    application
Message Encountered an error running task 2591 (SearchPlus_Population), step 1 of 2: Trying to get property of non-object on line 519 of /craft/plugins/searchplus/services/SearchPlus_AlgoliaService.php

2019-03-21 22:38:52
Level   error
Category    php
Message Trying to get property of non-object (//craft/plugins/searchplus/services/SearchPlus_AlgoliaService.php:519)

I'm running Craft CMS 2.7.6 and Search Plus 1.5.2 on Nginx with PHP-FPM 7.1.  I checked the the Algolia credentials are correct. I have adjusted the Nginx configuration and PHP's timeout settings and max post size settings.

I reached out to the Search Plus developer and he replied once telling to adjust the PHP configuration and has been unresponsive since the initial exchange.

Hopefully, someone here can shed some light on this issue.

Thanks.
Sal


texts: Transform different image if specific id or order

texts:
I have a masonry type image grid layout and I need to specify a different image transform for just the 2nd and fourth images in this grid.

Does the image ID relate to the order or to the specific image? How could I include a conditional in my code to output the largeIndexHalf image transform for the 2nd and 4th image?

{% set asset = entry.portraits %}
{% if asset | length %}
{% for asset in entry.portraits %}

{% endfor %}
{% endif %}


texts: GraphQL query entries by DateTime field between two dates

texts:
I am trying to query entries in GraphQL by custom DateTime field value.
It works with the base String value like ">=2020-10-01",
However querying between two dates like "['and', '>=2020-10-01', '<2020-11-01']" it gives me an empty result.
What will be the correct query variable here?
Thank you


texts: Multi-site Live Preview not working in Craft 3

texts:
In the multi-site Live Preview in admin panel show error in the console.

  Failed to load http://www.example.local/test: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://www.example.test' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.


texts:
We have a single installation of Craft that is live and with lots of users and lead generation going. Now the client would like to have a staging environment where we can prepare new pages, or add scripts and test them before going live.

I know about staging in PHP, where you modify a file(s) and when it works on the test server, you copy it over and overwrite the file(s) in production.

But can this be done in a cms like craft where the database is also affected?
Like we create in staging a new template, in the craft admin backend we create the article, with the form (we use Formbuilder). Then when the client is happy can I just 'push a button' and have it live in production?

I guess i have to copy template, and affected database tables over to the production server, but how to know what DB tables have been modified ?

Thank you

Peter


texts:
Got a client who uses his iPhone and iPad to update his site (he doesn't have a laptop!). Craft does a much better job than most as a mobile CMS, but he's running into issues with file uploads. When uploading from his Camera Roll he gets the following:

  Upload failed for image.jpg. The error message was: "Error uploading
  the file: This file type is not allowed"

I've tried too and get same response. In config.php jpeg and jpg are set in allowedFileExtensions, and maxUploadFileSize is ample if that matters. Wondering if there's some weird proprietary stuff with iOS files that's causing this? Anyone else experienced this before?


texts:
I asked a similar question previously but it was a bit too vague (and slightly different) to what I actually need. I'm about to start building a site that requires a booking system.

Essentially the site owner is available 24/7 (with the exception of some dates and times that they would set as unavailable). So users need to be able to book a service for ANY time except the times the site owner has set as unavailable.

In addition to that, the visitors of the site will be booking specific services that have pre-set durations. For instance one service may be 2 hours, another might be 3 hours, etc. When someone books a service the time-slot should no longer be available for another individual to book. For instance if customer X books a service that is set to take up 3 hours on November 16th 2014 to start at 8:00 AM PST, then customer Y can not book any services between 8:00 AM - 11:00 AM PST on that day.

Payments should also be processed when they make a booking, i'd think i could use something like CHARGE for that.

My question then is not only how would i go about building a system like this sans-plugin? I know it's a pretty complex question but i'd really appreciate a little help in the right direction as I'm having a bit of a hard time wrapping my head around how to accomplish this. Thanks a bunch in advance.


texts:
I have installed Craft successfully on a local Mac environment using Mamp. I can access the admin area and the default homepage when I go to this address localhost:8888/craft/public/ but I cannot access the site when I go to this address localhost:8888/craft/ Also, when I click on the news link on the default homepage it is a broken link unless I include the public in the URL.

localhost:8888/craft/news/2015/we-just-installed-craft

localhost:8888/craft/public/news/2015/we-just-installed-craft

How do I get around the public folder dilemma?
Thanks in advance.


texts: Unable to sort large number of blocks in Matrix field in CP and template

texts:
I have about 145 blocks in a single Matrix. If I try and re-arrange (drag&drop) the first few blocks, and then hit save, all is well. However, trying to re-arrange the last few blocks doesn't save at all, reverting the order as soon as I refresh.

I've pumped the php.ini settings (upload_max_filesize=128M, post_max_size=256M
,max_input_vars=4000) and set the block limit in CP to 200 so that shouldn't be the issue.

I'm also not getting a logged error.

Does this ring a bell with anybody?


texts: Images not showing after Craft 2 to 3 migration

texts:
Hi upon migrating my site from Craft 2 to 3 I'm getting errors like this:

Twig Runtime Error – Twig_Error_Runtime
Variable "largeImage" does not exist.

"largeImage" refers to an image transform, this error happens with all image transforms where I've used an assets field to place a picture.

Also whenever I have embedded a picture inside an editor, this doesn't show either and the URL that is written out is:

 src="@baseUrl/images/image.png"

Clearly, something has gone wrong for @baseUrl to appear there. I've checked my base URL settings and it is set to "http://localhost:8888".

I don't know what else to try so any help would be much appreciated. Thanks.


texts:
I'm fetching entries from several different locales and merging them together into a single object.

I then want to sort these to be most recent entry shown first.
Using Supersort and the custom sortAs method I can get this to work showing entries in ascending date order:

{% set sections = 'news' %}
{% set locales = craft.i18n.getSiteLocales %}
{% set pages = [] %}
{% for locale in locales %}
    {% set entries = craft.entries.section(sections).status(null).locale(locale.id).localeEnabled(false).find() %}
    {% set pages = pages|merge(entries) %}
{% endfor %}
{% set pagesSorted = pages | supersort('sortAs', '{ postDate.date }') %}

However, if I try to use the above with the custom rsortAs method then it does not work, just returning the entries in the order they occur within the pages object.

Any thoughts on what might be doing wrong?


texts: How can I get contact form added information on the control panel?

texts: I'm using the contact form plugin to implement the contact form on the front, now I want to see all the contact information on the control panel, So how can I get that in the control panel?


texts: Saving entries with FeedMe doesn't trigger Sprout notification email

texts:
So I have a FeedMe task that runs and updates a custom field for a select amount of entries.

In my notification email, I have a custom rule like so:

{% if object.customField | length and object.customField == 'hello' %}{{true}} {{else}} {{false}}{% endif %}

When I run the FeedMe task, the email doesn't get sent but I can see the entries get updated. If I go into the entries and save one manually, then the email sends so it seems that the rule works.

I also went in a plugin and set up the following event listener:

Event::on(
    Elements::class,
    Elements::EVENT_AFTER_SAVE_ELEMENT,
    function(ElementEvent $event) {
        if ($event->element instanceof Entry) {
            $entry = $event->element;

            Craft::info('Entry being updated: ' . $entry->title, __METHOD__);
        }
    }
);

and after I run the FeedMe task again, I check the logs and every entry that was updated by the task is logged as being saved.

In conclusion, I know the entries are being updated and saved by the FeedMe task but the notification email custom rule doesn't trigger unless I manually save the entries.


texts:
I am creating a custom dashboard for delivery guys where I want to show the order list in two divs. One is Pending Orders and second is History.
Basically I want to filter my order list by order status.
Here is code:

{% set pastOrders = craft.commerce.orders.relatedTo({targetElement: currentUser, field: 'deliveryGuy'}).find() %}
{% for order in pastOrders %}
   {{order.id}}
   {{order.orderStatus.name}}
{% endfor %}


texts: Sort entries in a category via entry field

texts:
I have a section for Businesses. I also have categories that these businesses can belong to. On each category page I want to list all the businesses that belong to that category. So far so good, but here's the rub: Each business also has an entry field that relates the business to a Town entry.

Businesses belong both to a category and a town entry.

On the category page I want to list the businesses by towns. So instead of having a laundry list of businesses, the businesses would be broken up by the different towns they belong to:

Town A
    - Business 1
    - Business 2
Town B
    - Business 3
Town C
    - Business 4
    - Business 5
    - Business 6

I am grabbing my businesses like this:

{% set businesses = craft.entries.relatedTo(category) %}

I have seen other answers to different questions suggest GROUP, but I'm not sure how to correctly go about using the group method on an array when I am trying to group via another array (entry field).

I tried this, but it results in "Object of class Craft\ElementCriteriaModel could not be converted to string":

{% set businessesByTown = businesses|group('bizTown') %}

I know that's fishy and incorrect, but I don't know how to accomplish it the right way. bizTown is the entry field I want to sort by.

If anyone could help, that'd be wonderful! Thank you!


texts: Trying to set a default asset folder using Craft tags

texts:
I'm trying to set a default asset folder for a field, as per the Craft docs on Dynamic Subfolder Paths.

I'm trying to set the asset path for each blog article to be /our-journal/{date}/{slug}, where date is the creation date of the article, falling back to today's date otherwise.

/our-journal/{ entry.dateCreated|date('Y-m') ?: now|dateCreated('Y-m') }/{ slug }

I'm getting an internal server error:

  Could not resolve the subpath “our-journal/{ entry.dateCreated|date('Y-m') ?: now|dateCreated('Y-m') }/{ slug }”.

I've tried using both single and double braces around the variables, as the docs are a bit ambiguous.


texts: Read POSTed JSON data from the request body

texts: Is there a way with the request service to read POSTed JSON from php://input?


texts: Is it possible to allow a user choose tags in admin panel using checkboxes?

texts:
The system I'm building requires a flexible taxonomy, where users should be able to add new taxonomy stuff to entries really easy and freely as soon as the need arises. So tags seem to work best for this situation.

However, there's a usability issue I'm concerned about. And that's a lot of typing, potential typos, and general "closeness" of what's already available to users (existing tags already added by users)

What I would ideally like is a tag field, which would still allow standard entry, but which also has a checkbox list of all existing tags as well - so users could just quick check tags they want to add to an entry - without typing anything - and add any extra tags manually only when these are needed.

Would something like that be possible to implement in Craft?

(The system will be an internal one, so there's no worry about too many users adding too many tags. Eventually, every single required tag will be created at some point, and users will be able to just choose from checkboxes - that's the ideal vision of how things would work on the data entry side)

thanks!


texts: Can I have a textarea field which isn't rich text?

texts:
I have a rich text field that I don't want wrapped in anything.

I just want a text area field, but I'm not sure how to get a text area without making it rich text, as the only multiline text field is the rich text field.

If it is going to be rich text, I need to be able to remove wrapping tags and control those.


texts: How can I set an alias dynamically based on request?

texts:
I have a multi-domain setup where I run multiple one-pager sites from different domains. For development purposes, I have configured it to work like this:
dev has:
http://localhost/www.domain1.com
http://localhost/www.domain2.com

staging has:
https://stage.ourdomain.com/www.domain1.com
https://stage.ourdomain.com/www.domain2.com

and production has:
https://www.domain1.com
https://www.domain2.com

To achieve this with the same site configuration for all three envs, I have created an alias called @baseUrlPrefix that I use in the site configuration (as part of the base URL), so for each env they are set to:
dev: http://localhost
stage: https://stage.ourdomain.com
prod: https:

And for each site I do @baseUrlPrefix//www.domain1.com (etc)
This has all worked fine and all, but I ran into issues when my devs had to do testing from mobile devices, because their local environment would only respond to localhost URLs. So I made a change for our dev config, to do (inspired by https://github.com/craftcms/cms/issues/2486):
use yii\web\Request;
$request = new Request;
...
'@baseUrlPrefix' => $request->getHostInfo(),

Which has also worked, no problem up until I'm trying to upgrade craft (this works in 3.3.15-18), and onwards from 3.3.19 it seems, it throws because it can't find Yii. It seems like maybe the loading order has changed, or I'm doing something incredibly stupid. I read that @web is supposed to actually take care  of this, which it also does, so using @web/www.domain1.com does work as intended, and I can overwrite that alias on production and set it to https:.
BUT, I also read that it's highly discouraged to use @web as siteUrl (https://craftcms.com/docs/3.x/sites.html#site-url) and I don't fully understand the implications of this, or if my use of an @alias is already suffering fromt he same cache poisoning bug?


texts:
I created two twig templates: home.twig and about.twig.
in home.twig it's this code:

go to about template

and in about.twig it's:

about

when I click "go to about template" it shows 404 error but, when I go to http://MY_HOST/about it shows me the about template.
how to link this templates? thank's


texts: How can I set an absolute image url for Open Graph Image tags?

texts:
I need the final tag to look like this:

<meta property="og:image" content="http://mysite.com/uploads/resources/_hero/myimage.jpg">

If I use something like this:

{% set seoImage = entry.featuredImage.one().getUrl('hero') %}

I end up with a relative URL:

<meta property="og:image" content="/uploads/resources/_hero/myimage.jpg"

So I thought "okay, I'll concatenate the site URL to the front and trim off one of the backslashes":

{% set seoImage = siteUrl ~ entry.featuredImage.one().getUrl('hero')|trim('/', 'left') %}

That worked fine until the server has to generate a new image using image transform. Then we end up, just the once, with a URL that looks like this:

<meta property="og:image" content="http://mysite.com/http://mysite.com/index.php/actions/assets/generate-transform?transformId=46">"

Darn, No idea what to do from here. Any ideas on how to get an absolute URL for the OG image tag EVERY time?


texts: Asset field in custom element field layout not saved

texts:
I am creating a plugin with a number of custom elements.

Being new to craft, I have come a long way using documentation and skimming existing code. I am stuck on the following issue. I added a field layout to a custom element following the instructions in the craft documentation (https://docs.craftcms.com/v3/extend/element-types.html#element-content).

I created the cp templates to edit and save the layout. I made the cp templates to create/edit the custom element. The field layout comes up nice and I can edit and save all the fields except when I add an asset field. I my case I want to add a photo. The asset field comes up in the screen, I can select a photo, it will show on the screen. But when I save en go back to the edit , the image is not saved.

I figured out that that field text content is saved in the content table and this is working fine (save, edit, delete ...) The assets seems to be handled in the relation database and I see nothing being saved in there. When I use my asset field for example in the user field layout , the data is saved. I double checked the docu and other code an do not seem to find anything else that explicitly saves this relation in the database.

I am developing on the latest version of Craft. Any help would be appreciated

Thank you

Bart


texts:
Upon running the update tool in the Craft CMS, I get this error.

Error: file_put_contents(path/to/file/composer.json): failed to open stream: Permission denied

What permissions are causing this error? Is it simply the case of changing the perms on the composer.json file? If so, what should they be?

Thanks!


texts: Are there any tools for Craft similar to the Yii Code Generator?

texts: There is Yii demo tutorial at http://www.yiiframework.com/screencasts/ that uses the Yii Code Generator. Are there similar Code Generator tools in Craft?


texts: Has anybody created a reusable PhpStorm Code Style settings export for Craft CMS?

texts:
Craft's codebase has nicely consistent coding conventions. Pixel & Tonic even publishes some information about their Coding Standards.

PhpStorm allows you to enforce a PHP Code Style in the editor and allows you to Import and Export Settings which include Code Style in the list of options.

Has anybody shared PhpStorm Code Style settings that enforce the Craft Standards?


texts: What are useful guidelines for Craft CMS security on VPS (virtual private servers)?

texts:
We have the choice of engaging services like Forge and ServerPilot, or rolling our  own.

Besides pricing, the opacity of what the services are actually providing can be a question -- just how well do they protect?

Would it be equal or better to provide our own securing when using VPS?

To decide, it would be good to understand an apparent baseline for server security.


texts: Is it possible to POST to an action if the system is offline?

texts:
There are easier ways to do this for sure, but...

I have the Mailchimp Subscribe plugin installed to build our email list etc... and it works perfectly!

However, we are now building a "Coming Soon" page with the site turned off to the public while we build out the site.

Is it possible to accept a certain action while the system is offline so that the POST request is accepted and doesnt return a 503 error?

Again, this is possible through using just a Mailchimp form itself but I'm interested to see if this sort of thing is possible if I ever needed this sort of control in the future.


texts: Request didn’t meet the user agent and IP requirement for maintaining a user session when website posts to our action URL

texts:
We have a module that has an action controller method that a third party website posts data to.
We can see that often, we can't save the data and there is an error "Request didn’t meet the user agent and IP requirement for maintaining a user session" in our web log.
I'm guessing it's this config setting "requireUserAgentAndIpForSession" but no idea how to turn that off for a specific request?


texts: Accessing disabled matrix blocks in a plugin

texts:
I've got a plugin which needs to be able to access all the blocks in a matrix - regardless of if the blocks are enabled or disabled.

The entry objects returned by the likes of craft()->entries->getEntryById only seem to include blocks in the matrix fields which are enabled.

Is there a way to access this information through a service - or do I need to work out how this is handled in the control panel (which does show disabled matrix blocks)?


texts: How to restrict access to some section in front-end for admin user only?

texts:
I know this is a basic question, but i never use Craft this way.

I need to show a section ( list of items ) in the frontend but only available for admin users ( that are already logged in the control panel ).

How can achieve this restriction from the template?

Thanks!


texts:
I have some entries with a multi-select field called "gallery". We can choose many images to this field.

I have a given image, how can I query entries whose "gallery" contains this given image? Thx!

I have tried like this with no success:

Entry::find()
  ->section($section)
  ->galleryImages('contains' . $image->id)
  ->all();


texts: Evaluating the if statement in entryType

texts:
I have this simple the loop, and want to assign a unique code, if condition is met.

{% paginate craft.entries.section().type().limit(20) as entriesOnPage %}

{% for entry in entriesOnPage %}

{{ entry.type.name }}

     {% if entry.type('entryTypeHandleA')|length > 0 %}
          a
     {% elseif entry.type('entryTypeHandleB')|length > 0 %}
          b
     {% endif %}
{% endfor %}

This code snippet is the last try, I've tried. I always get printed the first condition, even if it's false. Without filter length, I got printed both conditions.
I'm assuming, that it's ECM that will always exists, so that's why I never get falsey return?


texts:
I am building a site where I need to give each individual user access to site content according to the user progression of content consuming.

For the example, User A has access to watch entry no.1, than only a week later, he can get access to entry no.2 and so on.

What would be the best approach for to create such hierarchy in Craft 3?

Thank you for any hint!!


texts: Freeform - limit who can view 'results' page

texts:
I've got a form that redirects to a results page on submission. Results page currently lives at /form/results/[submission.id]/success/

The results page shows the user's answers, and a bunch of other results.

Is there a 'best' way to make it so that this results page is only accessible for the current user/session? I don't want to have it be available for any random joe to just try IDs and see someone else's results.


texts: entries.onSaveEntry does not fire from frontend

texts:
I created my own actionEntrySave for my frontend form. and I'm using the $entryService->saveEntry($entry); method to store my entries into the database.The problem is this does not fire

craft()->on('entries.onSaveEntry', function(Event $event) {
    die(var_dump("fired"));
});

When I save/edit the same entry in the backend or create a new one I see an empty page with "fired" there.. (just for testing) and I can manipulate the entry the way I want without any problems. If I do the same in the frontend (saving/editing an entry) the event does not trigger but the entry saves. Can someone explain why?

Thank you very much

edit: I already tried onBeforeSaveEntry with the same result

Edit 2 Solved
I solved it now.. my error was I did this

$entryService = new EntriesService();
$dbInsert = $entryService->saveEntry($entry);

But it has to look like

$entryService = craft()->entries;
$dbInsert = $entryService->saveEntry($entry);

I thought all services were singletons. My mistake


texts:
Within Settings, the cart currency is set to Euros. But when I use:

{{ product.defaultVariant.price | currency(cart.currency) }}

The output is:

¤150.49

Anyone encountered this before?


texts: "An error occurred while generating this PDF." in Commerce 2

texts: Like the title says, I cannot output order PDFs in Commerce 2 and not sure how to debug this. Anyone else encountered the same issue?


texts:
How can I split (or explode) a Twig string like this:

{% set fruits = "Apples; Bananas; Tomatoes" %}

into an array like this:

{{ ["Apples", "Bananas", "Tomatoes"] }}


texts:
First off, I appreciate this is open ended and SE isn't the best place for it. For a lack of a better place to ask though, here we are:

I've just built a system for a client where users could sign up an book places on events. None of the bookings on this system require payment, so it's just a case of submitting a form which creates an entry in a channel called "bookings" using:

action=saveEntry

I now have a client who needs to take bookings for events which require payment, and to list those bookings in a front end page. I'm trying to use Charge for payments (only because it seems easy to use, and my client doesn't want to pay monthly for something), which requires the form action:

action=charge/charge

The issue I have is that I want to submit a single form which takes a payment and creates a booking (action=saveEntry) without writing a plugin. I'm not a backend developer, I don't know how to write plugins (despite trying). None of the eCommerce addons available for Craft are out of beta yet.

Is there any way to take a payment and create a booking using template code?


texts: Programmatically create new entry with saveElement

texts:
I am currently trying to save a new entry with craft()->elements->saveElement(), as I want to avoid triggering the onBeforeSave and onAfterSave events.

When I run my script, it returns a successful entry id, but there is no entry in the admin.

Here is my code:

$entry = new EntryModel();
$entry->sectionId = $sectionId;
$entry->typeId = $entryTypeId;
$entry->enabled = true;
$entry->authorId = 1;

$success = craft()->elements->saveElement($entry, false);

if ($success) {
    echo $entry->id;
}


texts: Superslow loading of pages in Craft locally

texts:
I am having trouble pinpointing the issue but I am struggling with some of my pages taking an absolute age to load. For example;

It might be a local MAMP issue, but some pages load fine and I would say these pages seem to load very slowly each time.

it could be related to the imager plugin (generating lots of images (srcset and sizes) but I expect this only to run in the first instance not each time. When I look in my folders (in dropbox) I can see the folders get updated by not each image file.

Or it could be my code and queries and setup, in particular Eager-loading.
I am struggling to get my head around this and I have so far been unable to reduce the amount of queries, this also varies on each load from between 107ish to 115ish.

Here is my code for this particular section. I do have related categories and images for each entry which I believe would benefit from Eager Loading, but I cannot establish if my code is correct for the eager loading?

    {% set categories = craft.categories.group('cables') %}
    {% set cables = craft.entries({
            section: 'cables',
            with: [
                'cableCategory',
                'cableImage',
            ],
            order:  'title'
    }) %}

    {% for category in categories.relatedTo(cables) %}

{{ category }}

            {{ category.description }}

            {% for cable in cables.relatedTo(category) %}
            {% set image = cable.cableImage[0] ?? null %}

                    {% if image|length %}
                    {{ img.imagerSrcsetSizes(image, cable.title, '', 'thumb') }}
                    {% else %}

                    {% endif %}

{{ cable.title }}

            {% endfor %}

        {% for cable in cables.relatedTo(category) %}
            {% include '_includes/cables/cableModal' %}
        {% endfor %}

    {% endfor %}


texts: Is it possible to get a transformed image's file size (bytes, not dimensions)?

texts: I'm using a transformed image in a context where there's a maximum file size. Is there a way to determine the transformed image's file size in the templates? .size can't run on the url string