texts: Does it make sense to use Craft with relative links?

texts:
A coworker of mine asked me if I could make the links in Craft relative.

Which is not a big deal for navigation links,

relative url:

{% set relativeUrl = entry.url|replace((siteUrl), '/') %}

but it gets trickier for links inside a Rich Text field.

Craft is set up to use absolute links, is there a reason behind that?


texts:
We've been using bootstrap.php to have a basic PHP file run parts of some content-sync from a plugin we've written.

The sync is run from cron and this works great.

BUT - when the sync runs from the bootstrapped file - there are no logging info stored. I.e. the sync code works fine, but nothing is logged to: craft/storage/runtime/logs/<pluginname>.log - when triggering the sync from within the CP as a full-craft request, logging works fine.

Is there a way to get the bootstrap app to setup logging, so that logging from my plugin would work?


texts: Getting Entry By Category for Landing Pages In A Structure

texts:
I have a site governed by a structure, including the homepage.  I have several "parental" landing pages with research areas (Atlantic, Pacific, Midwest etc ) intended to be the gateway to  the children entries in that area. (Boston, New York, DC etc).

I have categories (without urls) corresponding to the landing pages (Atlantic, Pacific, Midwest etc ) and would like to pull teasers from each child entry onto the landing page, so that the Atlantic landing page has teasers from the Atlantic children's entries pulled in via the category field, the Pacific landing page has teasers from the Pacific children's entries via category etc...)

But I would like to do this in one template, rather than using multiple entry types.

I know I can get entries by an array of sections

{% for entry in craft.entries.section([atlantic, pacific, midwest]) %}

My mind cannot bend around how I could start at

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

and trek on from there to grab both the appropriate landing page and the categories that go with it dynamically.  Can I keep using arrays in both the page id's and the categories?  How would can I make a template know to grab the Atlantic and fill it with teasers from the Atlantic category?  Is it even possible?


texts:
Is it possible to add products and discounts to an order from backend?
From what I see it's only possible to edit the orders custom fields.


texts:
I have the following Category loop code which I'm trying to sort by the date the entries within have been updated.

  e.g if an entry was just updated within a category, this category
  would be at the top of the page/loop.

Here's my code

  <!-- START CATEGORY LOOP -->
  {% set categories = craft.categories()
      .level('1')
      .limit('8')
      .all() %}

  {% for category in categories %}

       {% set offers = craft.entries({
            relatedTo: category,
            with: ['offerLogo'],
            limit: 10,
       }).all() %}

       {% for offer in offers %}
          {% include '_card' %}
       {% endfor %}

  {% endfor %}

I just can't get them to be ordered. Any help would be great!


texts: Payment form submission is returning a curl error! ([curl] 3:  malformed [url])

texts:
I'm submitting a payment form via standard POST submission (not AJAX) to the current page URL, with an action value of commerce/payments/pay. To double-check my work, I've also copy + pasted their example form, and I'm still getting the same result.

I've done this a thousand times before, so I'm going a bit crazy trying to figure out what's different in this project. Any help is greatly appreciated!


texts: Parsing a Dropdown Option Label in Matrix

texts:
How do I access the Dropdown Option Label in this matrix?

    {% for block in entry.weather %}
        {% if block.type == "condition" %}

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

            {{ block.degrees }}
            °C

        {% endif %}
    {% endfor %}


texts: Display related entries on a category page filtered by another category field

texts:
I have a Structure called "Stoves".
Each Entry has two Category fields 'fuelType' and 'output'.

Fuel Type categories = ''Wood Burning','Multi-Fuel','Gas' and 'Electric'.
Output categories = '4kW','6kW','8kW','10kW',

On the category page template the following simple code gives me the correct entries based on the 'fuelType' field...  e.g. when viewing the 'Wood burning' page it shows me Wood Burning stoves.
{% set entries = craft.entries.relatedTo(category).all() %}

{% for entry in entries %}
    {{ entry.title }}

{% endfor %}

But I now need to also loop through the 'output' category group so I get something like the following:
ALL Wood Burning Stoves
Intro Text
start loop

4kW Stoves

Stove_4kW_No.1

Stove_4kW_No.2

Stove_4kW_No.3

6kW Stoves

Stove_6kW_No.1

Stove_6kW_No.2

8kW Stoves

Stove_8kW_No.1

Stove_8kW_No.2

Stove_8kW_No.3

Stove_8kW_No.4

...and so on....
end loop
Is this even possible?  Alternatively could I pull with individual entry queries using the individual 'output' category slugs?
Many thanks


texts: How to upload assets without user interaction?

texts:
Context: we sell some magazines and other newspapers on our site, and updating all the cover images manually is a hassle.

I would like the ability to write a url in a field (www.myimageprovider.com/product1) and set a cron job to fetch any new images for the day, for that specific product, and update the entry with the new image.

I'm having a hard time figuring out how to "fake" a file upload from a craft controller/service, as if it was uploaded from the CP form. I have tried something like this:

$file = array();
$url = $entry->getFieldValue('imagefetchurl'); // somegoogleimageurl.com/image.png
$tmpfname = tempnam("/tmp", "UL_IMAGE");
$img = file_get_contents($url);
file_put_contents($tmpfname, $img);
$file['size'] = filesize($tmpfname); // 245 kB
$file['name'] = basename($url); // image.png
$file['tmp_name'] = $tmpfname; // C:\\Windows\\Temp\\UL_XXXX.tmp

$_FILES['assets-upload'] = $file;
$assetOperationResponseModel = craft()->assets->uploadFile(1);

This throws an error

PHP notice

getimagesize(): Read error! - in ...craft\app\services\ImagesService.php(114)

I can see that the image get downloaded, the size and name is correct.

Any pointers and ideas are greatly appreciated

EDIT

After some digging, looks like i have to write my own upload handler for this task. http://www.1-script.com/forums/php/simulate-file-upload-so-that-move-uploaded-file-succeeds-124012-.htm

  Basically not possible unless you change the PHP source

I suppose i could override the function, but my instinct tells me that's a bad idea. I will have to go with an alternative approach


texts: Is it possible to filter with hasDescendants?

texts:
I'm building a navigation menu with 2 levels.

I have a contact page with a subpage thank you, which is hidden.

I hide pages from the menu using a lightswitch option and filter these pages out in my entries call.

However I check if a page has subpages using hasDescendants(), and if the page does, I add the class "has-dropdown" but my contact menu item contains the class "has-dropdown" too which technically is correct as it has a subpage but is it possible to filter with hasDescendants() ?

{% set pages = craft.entries.find({section: "page", genericHideFromNavigation: "[0]"}) %}
{% if pages | length %}

        {% nav page in pages %}

                {{ page.title }}

                {% ifchildren %}

                        {% children %}

                {% endifchildren %}

        {% endnav %}

{% endif %}


texts: Display Stripe card error in Craft 3 front-end entry form template

texts:
I have a custom plugin set up to speak to Stripe's API and process a card charge.  The code triggers in a craft\elements\Entry::EVENT_AFTER_SAVE event because I want to pass along certain data about the entry like its ID to Stripe's metadata parameter.  I figure if the charge fails, it would be fine to have the entry already saved, return the user back to the form with Stripe's error message, and let the user try again, saving the entry again after they correct their card info and resubmit.

I'm unsure how to send this information back to my template with entry and the error message so I can inform the user instead of passively log an error.

Here's an abbreviated example of my charge method:

public function charge($data, $savedEntry)
{
    // set Stripe api key

    $settings = [
        // settings filled with $data
    ];

    $charge = null;

    // charge the card
    try {
        $charge = Stripe\Charge::create($settings);
    } catch (Stripe\Error\Card $e) {
        $body = $e->getJsonBody();
        $error  = $body['error'];

        // since there's an error, return user to form with $savedEntry and $error['message']
        // ...
    }

    return $charge;
}


texts: How to use a Structure including a homepage

texts:
As far as I can tell, it's mandatory to have a Single as the site index.

I always use a Structure for organising my pages, and different entry types for different page templates. I intend to use a nav tag to output the menu. However, this time my site nav looks like this:

Homepage         (site.com/)
    Subpage 1    (site.com/subpage-1)
    Subpage 2    (site.com/subpage-2)
    Subpage 3    (site.com/subpage-3)
About            (site.com/about/)
    Subpage 4    (site.com/about/subpage-4)
    Subpage 5    (site.com/about/subpage-5)
Services         (site.com/services/)
    Subpage 6    (site.com/services/subpage-6)
    Subpage 7    (site.com/services/subpage-7)

If I have to use a Single as the home page, how do I put subpages under the home page?

Previously I've used the nav tag, and just hardcoded a link to the home page before the rest of the li's, but that's not going to work this time as the homepage has subpages.

EDIT: I've updated my sitemap to include a URL structure, which is the real challenge here.


texts: Unable to run console commands (Craft 3, MAMP)

texts:
This was asked and solved previously, but for Craft 2, see Error Connecting To (MAMP Pro) Database in Console Command. Unable to make it work here.

In short, running console commands like ./craft abc in Craft 3 configured using MAMP gives

Craft isn’t installed yet!

Exception 'craft\errors\DbConnectException' with message 'Craft CMS can’t connect to the database with the credentials in config/db.php.'

in /Users/stian/dev/site.no/vendor/craftcms/cms/src/db/Connection.php:179

Stack trace:
#0 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/Connection.php(996): craft\db\Connection->open()
#1 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/Connection.php(983): yii\db\Connection->getMasterPdo()
#2 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/mysql/QueryBuilder.php(380): yii\db\Connection->getSlavePdo()
#3 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/mysql/QueryBuilder.php(399): yii\db\mysql\QueryBuilder->supportsFractionalSeconds()
#4 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/mysql/QueryBuilder.php(57): yii\db\mysql\QueryBuilder->defaultTimeTypeMap()
#5 /Users/stian/dev/site.no/vendor/craftcms/cms/src/db/mysql/QueryBuilder.php(27): yii\db\mysql\QueryBuilder->init()
#6 /Users/stian/dev/site.no/vendor/yiisoft/yii2/base/BaseObject.php(109): craft\db\mysql\QueryBuilder->init()
#7 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/QueryBuilder.php(116): yii\base\BaseObject->__construct(Array)
#8 /Users/stian/dev/site.no/vendor/craftcms/cms/src/db/mysql/Schema.php(71): yii\db\QueryBuilder->__construct(Object(craft\db\Connection), Array)
#9 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/Schema.php(249): craft\db\mysql\Schema->createQueryBuilder()
#10 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/Connection.php(836): yii\db\Schema->getQueryBuilder()
#11 /Users/stian/dev/site.no/vendor/yiisoft/yii2/db/Command.php(580): yii\db\Connection->getQueryBuilder()
#12 /Users/stian/dev/site.no/vendor/craftcms/cms/src/db/Command.php(142): yii\db\Command->update('{{%queue}}', Array, '[[timeUpdated]]...', Array)
#13 /Users/stian/dev/site.no/vendor/craftcms/cms/src/queue/Queue.php(507): craft\db\Command->update('{{%queue}}', Array, '[[timeUpdated]]...', Array, false)
#14 /Users/stian/dev/site.no/vendor/craftcms/cms/src/queue/Queue.php(449): craft\queue\Queue->_moveExpired()
#15 /Users/stian/dev/site.no/vendor/craftcms/cms/src/queue/Queue.php(95): craft\queue\Queue->reserve()
#16 /Users/stian/dev/site.no/vendor/craftcms/cms/src/queue/Command.php(82): craft\queue\Queue->run()
#17 [internal function]: craft\queue\Command->actionRun()
#18 /Users/stian/dev/site.no/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#19 /Users/stian/dev/site.no/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#20 /Users/stian/dev/site.no/vendor/yiisoft/yii2/console/Controller.php(148): yii\base\Controller->runAction('run', Array)
#21 /Users/stian/dev/site.no/vendor/yiisoft/yii2/base/Module.php(528): yii\console\Controller->runAction('run', Array)
#22 /Users/stian/dev/site.no/vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('queue/run', Array)
#23 /Users/stian/dev/site.no/vendor/craftcms/cms/src/console/Application.php(93): yii\console\Application->runAction('queue/run', Array)
#24 /Users/stian/dev/site.no/vendor/yiisoft/yii2/console/Application.php(147): craft\console\Application->runAction('queue/run', Array)
#25 /Users/stian/dev/site.no/vendor/yiisoft/yii2/base/Application.php(386): yii\console\Application->handleRequest(Object(craft\console\Request))
#26 /Users/stian/dev/site.no/craft(22): yii\base\Application->run()
#27 {main}

Ideas?


texts: Radio buttons in matrix field not saving

texts:
Craft CMS version 3.0.9 (updated from 3.0.1 to try and fix).

I have a layout field in a matrix box with the radio buttons field type with the options normal (default), full, left, right.

When saving the entry with the radio button as full, left or right it stays at the default normal.

This functionality was working in Craft CMS 2, doesn’t seem to work since the update to 3.

Any idea on how to fix this?


texts: How to handle multiple users simultaneously editing an entry?

texts:
If 2 or more people are editing a entry at the same time in Craft, the last person to save the entry overrides everyone else's work. It doesn't seem any diffing is involved to resolve this. I'm using matrix fields mostly.

WordPress handles it by locking a post while someone is editing. This is done by sending an AJAX request to the server when auto saving, updating the "last edited" date and which user is editing.

Does anyone know if a plugin exists already for Craft that implements this post locking feature? Or is there something already in Craft to avoid these conflicts?


texts:
I'm quite new here, so I hope this is not a too newbie question:
I'm currently developing a plugin and want a similar view like in Entries > Structures, so I can sort and create children of my elements:

At the moment I have my custom Element Type and added the elements in the structureelements table. I also created the view, but I don't know how I can make them sortable and with child elements:

Could someone point me to the right direction how I can achieve this?


texts:
I have a question about custom routes set in routes.php. Can route segment be optional?

Taking example from docs - 'blog/archive/<year:\d{4}>' => 'controller/action/path', can we make year token optional in url and still match route when someone vists blog/archive?


texts: How can I use asset select modal in utility?

texts: I created a custom utility template. Inside the template, I would like to use the built-in asset select modal for the "Add image" button. Any way to do this please?


texts: How do I use a leading slash with the url() function?

texts:
The url() function won't work with a leading slash as it's path parameter.

For example, this: {{ url('jobs') }}
Outputs: http://example.com/jobs

But this: {{ url('/jobs') }}
Just outputs: /jobs

This is easy enough to remember for developers, but if you're passing a variable from a user input field like {{ url(entry.myField) }}, users can accidentally break a link if they add a leading slash.

How can I make the url() function more resilient when relying on an unknown variable?


texts: How to filter entries by checkboxes using Sprig

texts:
I am using the Sprig plugin to filter news entries on a news overview page. I have three checkboxes for the categories related to the news entries.
I have the page working for the basic functions by adapting code used on the Sprigboard.
But the page won't let me select multiple checkboxes. I can't figure out how to make Sprig respect all checkboxes and push the selection to the url.
I have previously done this using vanilla javascript, but I wonder if such a feature could be solved elegantly using Sprig.
Category checkboxes:
  {% for category in craft.categories().group('news').all() %}
  <li class="filter--content--item {{ category.id in newsCat ? 'selected' : '' }}">
      <input sprig type="checkbox" class="filter_checkbox" name="newsCat" id="checkbox_{{ category.id }}" value="{{ category.id }}" {{ category.id in newsCat ? 'checked' : '' }}>
      <label id="label_{{ category.id }}" class="newsCatLabel" for="checkbox_{{ category.id }}">
          {{ category.title }}
      </label>
  </li>
  {% endfor %}

Search query:
  {% set newsCat = newsCat ?? '' %}
  {% set relatedTo = newsCat ? relatedTo|merge([newsCat]) : relatedTo %}

  {% set entryQuery = craft.entries
    .section('news')
    .limit(10)
    .relatedTo(relatedTo)
    .search(search)
  %}
  (...)
  {% do sprig.pushUrl('?' ~ {page: page, newsCat: newsCat}|url_encode) %}


texts:
I've got a plugin which am triggering emails from (listening to the users.onSaveUser event).

I am using a conditional to send two emails, depending on the permissions of the person registering the user.

In one instance am using $email->htmlBody = craft()->templates->render('emails/employee', $vars); which works fine.

However, in another instance am using $email->htmlBody = craft()->templates->render('emails/prospect', $vars); and getting the following error:

Unable to find the template “emails/prospect”.

Any ideas why this might be happening or how to get more useful feedback?
I have double and triple-checked the spelling of the files and they are indeed available in the file system:


texts: How do I show entries that do not have a certain category?

texts: I’m aware of the relatedTo() parameter for entries that belong to a category but how can I show entries that are NOT relatedTo() a certain category?


texts: Display/edit Sprout Form entry in front end

texts:
Following Sprout Forms -- How to link to individual entries on the front-end I found code

{% set formEntryId = craft.request.getSegment(2) %}
{% set entry = craft.sproutForms.getEntryById(formEntryId) %}

but it doesn't have any field data. Including {{ dump(entry) }} in my template shows object(barrelstrength\sproutforms\elements\Entry) with a lot of structure but no user entered values.

I was actually hoping to reuse my custom form templates (Sprout Forms > Settings > General > Default Form Templates) so it'll cycle through all the field templates like when the user filled in the form but I just want to show values if the form has already been submitted.


texts:
The only thing I don't really like about Craft is that I have to fetch and eventually manipulate my entry in the twig template itself.

Is there a way to hook into the current request before the template gets rendered? Like that I could create some kind of Controller where I fetch all the necessary data, prepare it and then pass it on to the template.

Additionally this would allow me to use another template engine then twig.

If this is not possible, would there be a way to only use craft as the backend? From outside of craft, is there an easy way to find out if there are matching entries/singles/categories to the current request? I'm not looking for a complete answer here, more some key points where I could start looking.


texts: Server respond is very long (25s). Is there a way to optimize the perfomance?

texts:
Normally I'm not working that much with craft and twig syntax, so first of all sorry if I'm not that much into that topic (normaly html,css,js,jquery).
There is one site which need so much time to load. There is much data to load but that can't be the reason that the server needs about 25s to respond.
Do you have any performance tips?

Live Example: http://www.christlicher-gesundheitskongress.de/program.html

Probably this snippet is responsible for the long load time.

{% set z = 0 %}
            {% for program_block in craft.categories.group('program_block') %}

{{ program_block.title }}

{{ program_block.program_date | date ('l, d. F') }} von {{ program_block.time_start | date('H:i')  }} - {{ program_block.time_end | date('H:i')  }}

                    {# {% cache %} #}
                    {% for program in craft.entries.section('program_point').order('program_number') %}
                        {% if program.block.first().title == program_block.title %}

                                {% if program.type == "seminar" %}{% endif %}

 {# {% if program.type != "seminar" %}#{% endif %} #} {{ program.program_number }}{{ program.title }}

                                {% if program.short_description|length %}

{{ program.short_description }}

                                {% endif %}
                                {% if program.type == "seminar" %}{% endif %}
                                {% if program.program_referents|length %}

                                    {% set i = 1 %}
                                    {% for referent in program.program_referents %}
                                         {{ referent.referent_name }} {% if i != program.program_referents|length %}// {% endif %}
                                    {% set i = i+1 %}
                                    {% endfor %}

                                {% endif %}

                        {% endif %}
                    {% endfor %}
                    {# {% endcache %} #}

            {% set z = z+1 %}
            {% endfor %}


texts: Applying image transforms to remote images?

texts:
Is there any way to apply an image transform (either CP-defined or template-defined) to a variable which represents the URL of a remote image? Naturally it would need to be cached locally, but since transforms are already cached I figure it's not too much of a stretch.

My use case is applying a transform to the thumbnail image of a video which is being fetched by an oEmbed plugin.


texts: Conditionally show table column headings

texts:
Is there a way to conditionally display a table column heading if the table field row has been entered? i.e.

if my table has up to 3 columns
and I fill in ALL the fields like this I'd see

ch1 | ch2 | ch3

a   |  b  |  c

but, if I only fill in 2 columns without conditionals I'd see this

ch1 | ch2 | ch3

a   |  b  |

I'd like to conditionally only show the column headings/rows populated like this:

ch1 | ch2 |

a   |  b  |

Is that possible?


texts: Set Password form - use front-end template for admin users

texts:
I am currently building an intranet. I have created a password reset and a set password form that is used on the front-end. However, admin users get redirected to the 'Craft' set password form. is there anyway possible to make all users use the front-end set password form for consistency?

Thanks.


texts: Why is a "Brute Force Protection" dialog appearing on login? How to remove?

texts:
After successfully logging into admin I seem to be getting this message in a browser auth dialog:

Brute force protection, Please use these credentials: User = 'u' and Password is the answer to 1+1”

What's causing this and how do I disable it? Very annoying!

Thanks


texts: Any way to create new entry using certain entry type?

texts:
I'm thinking this isn't possible but would be nice if it were?

Just wondering if you have loads of different entry types for a section then it would be nice if there was a way of creating a new entry with a certain entry type instead of having to go to create a new entry and then select the entry type.

Would be slightly less confusing for clients and would stop some errors in that they would hopefully always get the right entry type instead of typing into the first entry type that shows up.


texts: Searching a specific section by four different types of parameters?

texts:
I'll do my best to explain this.

I have a Portfolio of companies, which I have as a structure, that I need to be able to filter/search through by using up to four different parameters.

Keyword - a basic search field that a user can type into
Industry - a category field
Company Status - a dropdown field
Board Members - a relation to a different structure

I know how to search these individually but I'm not quite sure how to use any combo of these all at once. Whether that be using a keyword and industry to search, all four items to search, maybe just by industry and board members, or maybe just by industry.

Below is what I have so far. Hoping someone will be able to point me in the right direction or help me piece this together.

This handles the search

{# What is being searched #}
{% set portfolio = craft.entries.section('portfolio') %}

{# Potential Query Strings #}
{% set query = craft.request.getParam('q') %}
{% set industryParam = craft.request.getParam('industry') %}
{% set statusParam = craft.request.getParam('status') %}
{% set boardMemberParam = craft.request.getParam('boardMember') %}

{# Related to Industry and/or Board Member #}
{% set industry = craft.categories.group('industries').slug(industryParam).first %}

{# Here's where I'm not sure how to combine the relatedTo for the industry, status, and/or board members #}
{% set relationParam = industryParam ? {targetElement: industry} : '' %}

{% set entries = portfolio.relatedTo(relationParam).search(query) %}

{# Probably best to not use search, as it's slower than relatedTo, so I commented this out. #}
{# .search('companyStatus::"' ~ statusParam ~ '"') #}

{# Spit out the entries #}
{% if entries|length %}

  {% for entry in entries %}

{{ entry.title }}

  {% endfor %}

{% else %} {# If nothing matches the search criteria #}

Sorry, no results.

{% endif %}

Stripped down version of where the user sets the parameters

<form action="{{ url('portfolio') }}">

Filter by Keyword

  <input type="search" name="q" placeholder="Search">

Filter by Industry

  <select class="fancy" name="industry">
    <option value="">All Industries</option>

    {# Only get categories that are being used. #}
    {# This will definitely need some cache tags. #}
    {% set categories = craft.categories.group('industries').order('title asc') %}
    {% set entriesWithCategories = craft.entries.relatedTo(categories) %}
    {% set categoriesInUse = craft.categories.relatedTo(entriesWithCategories) %}

    {% for category in categoriesInUse %}
      <option value="{{ category.slug }}">{{ category.title }}</option>
    {% endfor %}
  </select>

Filter by Status

  <select class="fancy" name="status">
    <option value="">All Statuses</option>
    <option value="active">Active</option>
    <option value="past">Past</option>
  </select>

Filter by Board Member

  <select class="fancy" name="boardMember">
    <option value="">All Board Memebers</option>
    {% set team = craft.entries.section('team') %}
    {% for member in team %}
      <option value="{{ member.slug }}">{{ member.title }}</option>
    {% endfor %}
  </select>

  <input type="submit" value="Go">
</form>

And if possible, how would I do this with AJAX? This can come later, initial search function is 100% okay. I know I could do the the AJAX filter completely on the Front-End but there's potential that the client will want to eventually add pagination if they start adding a bunch of companies to their portfolio.

Thanks in advance.


texts: How to set up multi-env in Craft 3 with .env files?

texts:
How do I take advantage of the new .env files? I want to setup a local and production environment in Craft 3.

Anyone know how to do this or know of any docs out there explaining it ?


texts:
Suddenly, I can't add any entry to a structure.
When I try to save a record, I've got "Could not find a unique URI for this element“. Although, the slug is perfectly valid and unique, but whatever I type in the slug field, same message "Could not find a unique URI for this element". I only got a couple of entries in this structure, so I could not have possibly hit the  'maxSlugIncrement' limit…
Thanks for your help.


texts:
I am trying to query entries (scripts) when a custom expiration date field is within a certain range.

These questions/answers helped me get as far as I am, but I'm still stuck: Advanced query/filter based on date and values and How can you return elements between two values?

Here's the full scenario. On this app's homepage, it lists a handful of recent scripts (prescriptions). It also has sections where it displays scripts that are expired and scripts that are about to expire (within two weeks of the current date).

I did some testing and found that the following conditionals filter the scripts just how I want:

{# When expiration date is between now and 2 weeks #}
{% if expirationDate >= now and expDate <= now|date_modify('+2 weeks') %}

{# When expiration date is anytime before now #}
{% if expirationDate < now %}

Those work great. How can I move this filter into the query itself?

I was thinking something like the following, but it obviously doesn't work because of all the commas. But this is what I'm trying to do. How do I use this correctly in a hash?

{% set scriptsAboutToExpire = {
    section: 'scripts',
    order: 'expirationDate asc',
    expirationDate: 'and', '>=' ~ now, '<=' ~ now|date_modify('+2 weeks')
} %}


texts: PHP mbstring extension isn't enabled? (WampServer)

texts:
I'm using WampServer Version 3.0.4 64bit on Windows 10 to run a local dev site. It's been working fine for a few weeks, and I last opened the site about 5 days ago. Today when I go to my site, I'm getting this error:

  Craft CMS requires the PHP multibyte string extension in order to run.
  Please talk to your host/IT department about enabling it on your
  server.

I checked my PHP extensions menu in Wamp, and there is a check mark next to php_mbstring, so it seems to be enabled.

When I go to localhost in my browser to view my Wamp home page, I see the following error:

  * ERROR * The PHP configuration loaded file is: - should be: c:/wamp64/bin/apache/apache2.4.18/bin/php.ini or
  c:/wamp64/bin/php/php5.6.19/phpforapache.ini

I don't know if this is new, but I haven't changed anything in my wamp configuration files since the site was working.

Full Wamp configuration, in case it's helpful:

I'm fairly new to both Wamp and Craft, so not sure where the problem lies. Thanks in advance for any help!


texts: Custom Category order in a Categories Field

texts:
I have a load of projects, each of which can have zero or more categories which indicate the particular type(s) of work involved. As well as using these categories to produce a 'category page' of filtered entries, they are also pulled through to each index page listing, to show the types of work involved in that particular project.

Therefore, these ideally should be ordered by priority, so one project may feature more use of category 1 so that would want to come first, whereas one project may feature more use of category 2.

For Assets Fields (and I think also Entries Fields), I seem to be able to order the respective elements by dragging and dropping them in the field, but for Categories Fields, the order seems to be determined by the order of the Structure in the Categories page in the CMS.

Is there a way of allowing the user to customise the order the Categories in a Categories field?

Thanks!


texts: What is causing Craft CP assets(JS/CSS) to appear in front-end pages?

texts:
Perhaps in some way related to this, I've got a couple of front-end pages on our website that pull in the following files, which seem to all be CP files. These two pages each utilize plugins I've written, each one a different plugin, so there must be something I'm doing in my plugins that calls this stuff in. Any hints?

selectize.css
craft.css
charts.css
axios.min.js
d3.js
element-resize-detector.js
jquery.js
jquery.mobile-events.min.js
velocity.js
garnish.js
jquery-ui.min.js
jquery.payment.js
picturefill.js
selectize.js
jquery.fileupload.js
xregexp-all.js
fabric.js
Craft.min.js

EDIT: Here is the relevant asset-bundle:

class LivestreamAsset extends AssetBundle
{
    // Public Methods
    // =========================================================================

    /**
     * Initializes the bundle.
     */
    public function init()
    {
        // define the path that your publishable resources live
        $this->sourcePath = "@kr37/livestream/assetbundles/livestream/dist";

        // define the dependencies
        $this->depends = [
            CpAsset::class,
        ];

        // define the relative path to CSS/JS files that should be registered with the page
        // when this asset bundle is registered
        $this->js = [
            'js/Livestream.js',
        ];

        $this->css = [
            'css/Livestream.css',
        ];

        parent::init();
    }
}


texts: Blank Screen on Site Search for some Search Terms

texts:
We are getting a really odd result when doing certain site searches.

The search function loads a completely blank page when we search for the word Anaerobic; Looking at the source some of the template code is rendered but not all of it.

Anaerobic – blank page
Anaerobic digestion – blank page
Anaerobic Digestion Development Centre – returns results fine

Failed Search Terms

https://www.uk-cpi.com/search/results?q=Anaerobic+digestion

https://www.uk-cpi.com/search/results?q=Anaerobic

Working Search Terms

https://www.uk-cpi.com/search/results?q=Anaerobic+Digestion+Development+Centre

It seems to work fine locally - does anyone have any idea what could be causing the issue?

Thanks in advance,

Dan


texts:
I am just getting to grips with Craft CMS and am finding the Contact Form plugin tricky to use. I have built a reasonable site structure, figured how fields, sections, etc work at a relatively basic level and have produced a one-for-all template so far in the templates/ root folder. But the form eludes me.

I have added the contact form example from https://github.com/craftcms/contact-form to the main template at present, and this shows on my /contact/ page. However, the submission of the form returns an error as follows:

Template not found: contact/thanks

I would assume I need to make a section/entry for the contact/thanks page? So I have now done that. The form submits but just goes to a blank page at contact/thanks even though I have created content on that entry. It's not drawing any of the data items specified in the Twig template.

It also does not send an email. I have implemented and tested the Settings > Email webserver details successfully. But all submissions are being collated in the "Form Submissions" area (Contat Form Extensions plugin).

I note that the form has no action, but the hidden field below exists:

<input type="hidden" name="action" value="contact-form/send">

Do I need to create a page for contact-form/send too? I have clearly made the naive assumption that the plugin would sort the sendmail part but some action is required on my part.

Sorry, I'm a noob. Guidance appreciated.


texts:
I can see in the CP (craft 3) that my sections have a 'translatable' icon but I don't find anywhere in the UI to translate section names.

What's the best way to translate these?


texts:
I am having issues debugging craft tasks where the issue is caused by validation errors rather than php syntax / environment issues.

How do you debug validation errors in craft tasks?


texts:
I want to use AVG/SUM mysql and add it to the results of a criteria.
Trying to strategize the best way to achieve this.

I'm looking at elements.onBuildElementsQuery, where it seems I could do something like...$query->addSelect('AVG(field_reviewRating) as reviewRatingAverage');

Or do I need to make this a field type (read only)?

I'm going to be dealing with several thousands of entries, so I don't want to have to query everything and loop through.

I could also just call a service from Twig e.g. (craft.custom.getReviewStats(entryModel)), but I wanted to avoid having to add another query for each returned element.


texts:
I've been using this example to eager load images, stored in an Assets field which is located in a Matrix field.

My query looks like this:

{% set entries = craft.entries.section('project')
.with(['projectMatrix.imageBlock:imageFile']) %}

Where projectMatrix is a Matrix field, imageBlock is a Matrix block type and imageFile is an Asset field inside imageBlock.

But how do I reference the that image in my templates?

{% for entry in entries %}

{% set matrixImage = entry.projectMatrix.type('imageBlock')[0].imageFile[0] ?? null %}

...

{% endfor %}

This is always be null, when eager loaded


texts: How to add a facebook and twitter share button on a page

texts: I would like to add a facebook and a twitter share button to some pages of our sites. Our site already has a facebook and twitter button at some pages. Those buttons redirect to our corresponding pages.


texts: Simple webshop solution (Craft Commerce)?

texts:
I am looking for a simple shopping solution for one of my customers. Since their website is already running with CraftCMS, I am looking if there is any integrated solution available.

However, so far I have found only 3 plugins compatible with Craft3:

Stripe Payments
PayPal Buy Now Button
Craft Commerce

Am I missing one?

Does anyone have experience with one or more of these shop systems?

Right now, Craft Commerce Lite looks the best to me, but I am not sure whether I am overlooking something.


texts: Is it possible to always show Assets folders as opened?

texts:
When adding an image from an Assets field or uploading one to the Assets section (or anywhere there is an Assets field for that matter) if you have subfolders then it currently shows the main folder but closed so you have to click on the arrow to unfold the main folder structure.

Therefore looking for a way to have the folder structures already opened to save a click.

Thanks,

Mark


texts:
I am automatically creating users in a service, is there a way to check if user exists?

I want to log in id user exist or save a new user if it doesn't, I have the following so far which will add a user:

public function add($user)
{
    craft()->users->saveUser($user);

    $user = craft()->users->getUserByUsernameOrEmail($username);
    craft()->userSession->loginByUserId($user->attributes['id']);
}


texts: Craft CMS project.yml not syncing correctly

texts:
I am using the latest version of Craft CMS with 'useProjectConfigFile' enabled.
My development process involves creating/updating Craft settings locally, committing this to Git and then deploying to production. The changes are then sync'd the production Craft CMS fine.
For some reason I have a Global set in the production CMS that doesn't exist on my local version.
Should this be removed when the config file is sync'd up? Any reason why it isn't not syncing correctly?


texts: How do I sort categories by title while preserving hierarchy?

texts:
New to Craft. I'm outputting a list of all the categories in my site.

When I do this:

    {% nav category in craft.categories %}

        {{ category.title }}
        {% ifchildren %}

                {% children %}

        {% endifchildren %}

    {% endnav %}

I end up with (for example):

Legumes

Peas
Beans
Lentils

Meat

Ground Beef

Fruit

Peach
Banana
Strawberry
Grapes

I'd like those to be alphabetical, though, so Fruit, Legumes, and Meat, are listed in that order, with their children also listed in alphabetical order in the nested list.

However, when I do THIS:

    {% nav category in craft.categories.order('title') %}

        {{ category.title }}
        {% ifchildren %}

                {% children %}

        {% endifchildren %}

    {% endnav %}

The entire list gets flattened, alphabetized, and then spit back out into a nonsensical hierarchy, like so:

Beans
Banana
Fruit

Grapes
Ground Beef

Lentils
Meat

Peas
Peach
Strawberry

Is there any way to alphabetize by one level at a time, without completely reinventing the way Craft handles categories? Thanks!


texts: How can i detect that an asset has been published from a plugin?

texts:
So, i must write this Craft plugin to index documents as soon as they are published, though a special publication field used amongst different pages templates (including a matrix field !).

How can i use the publish event to detect that this special kind of assets (assets belonging to a special directory) have been used ?


texts: Import Plugin date format (Post Date postDate)

texts:
Having much success with the Import Plugin

I've also raised this here, but thought this forum perhaps better.

I'm trying to force through a Post Date on my imports, but nothing is being respected, also, doesn't map automatically. All other fields have imported flawlessly, but PostDate seems to stick with the current date (not the date from years ago I want to be the postDate.

Can I check please?

I have CSV column titled tried a few but thought "postDate" would work best.
Date format, matched "31/07/2014" to the field, and "31/07/2014 00:00" but can't get anything to stick though any method (append, or replace)

Thanks in advance.


texts:
Each of my entries has a table with budget projections.

I loop through related entries.   But, how can I loop through and bring in the related table?

This is my table for the entry:

 {% set field = craft.app.fields.getFieldByHandle('budgetProjections') %}

            {% for column in field.settings.columns %}
                {{ column.heading }}
            {% endfor %}

        {% for row in entry.budgetProjections %}

            {{ row.col1 }}
            {{ row.col2 }}
            {{ row.col3 }}
            {{ row.col4 | number_format (0,'.',',')}}
            {{ row.col5 | number_format (0,'.',',')}}
            {{ row.col6 | number_format (0,'.',',')}}
            {{ row.col7 | number_format (0,'.',',')}}
            {{ row.col8 | number_format (0,'.',',')}}
            {{ row.col9 | number_format (0,'.',',')}}
            {{ row.col10 | number_format (0,'.',',') }}

        {% endfor %}

This is my loop for related entries.  It creates a button and link for each related entry.  But now, I want to pull in the related table.  How do I do that?

{% set related = entry.relatedBudgetItems.all() %}
    {% if related %}

 {% for item in related %}

        {{ item.title}} ({{ item.lineItem }})-
        {% endfor %}

    {% endif %}

Thanks!


texts:
Getting a bit stuck on a site upgrade from 3.4 (3.4.29.1). After updating via composer getting DB errors.
Initially:
Integrity constraint violation: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'startDateTime-global' for key 'craft_fields_handle_context_unq_idx'

If I try to restart process (overriding the "It looks like someone is currently performing a system update" warning):
Database Exception: SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'elements'
The SQL being executed was: ALTER TABLE craft_fieldlayouttabs ADD elements text AFTER name

Any thoughts on resolving?


texts: Upgraded to PHP 7.1 - GD or ImageMagick is required

texts:
This question relates to two Craft sites running on the same server. One site is a production version, the other is staging. I use WHM v68 and EasyApache 4.

Production is on PHP 5.5.38. Staging is on PHP 7.0.25. Both sites report the following from admin/utils/phpinfo:

imagick module version: 3.4.3
Imagick compiled with ImageMagick version: ImageMagick 6.9.4-1 Q16 x86_64 2016-10-13

I would like to upgrade both sites to PHP 7.1, starting with staging. When I use WHM's MultiPHP Manager to update staging to PHP 7.1, I'm unable to load Craft. I receive this message:

--

Can’t run Craft CMS :(

Your server doesn’t meet the following requirements to run Craft CMS:

GD or ImageMagick is required, however ImageMagick is recommended as it adds animated GIF support, and preserves 8-bit and 24-bit PNGs during image transforms.
GD or ImageMagick is required, however ImageMagick is recommended as it adds animated GIF support, and preserves 8-bit and 24-bit PNGs during image transforms.
Please talk to your host/IT department about upgrading your server.

--

I don't understand this because I know that ImageMagick and imagick are both installed and enabled. And imagick 3.4.3 (since RC1) should support PHP 7.1.

Thanks!


texts: Admin - Manage entries based on a field type choice

texts:
I have a potential upcoming project which will be the home for a businesses sporting events, they will have multiple event mini sites, about 4 each year. Each event mini-site will have the same structure but they will have different aesthetics.

The content areas will be:

Home (Single)
News (Channel)
Videos (Channel)
Photos (Channel)
Results (Single)
Media Contacts (Single)

I have no problem setting up the site but I would like offer the client the ability to access an edit entries screen that has just the content for that event.

I.e they could choose the Event from an drop down and they would only see the Singles, Channels and Structures related to that event.

Also adding the ability to restrict some users access to a particular events content

Is this possible? Has anyone built a plugin for something like this? or know how to?

Thanks in advance.


texts: FeedMe for Craft 3: Tweaking attribute values from feed before FeedMe process it

texts:
I have a feed where one element is to be mapped to a multiselect field on an entry. However, I would need to tweak the values I'm importing (basically making them lowercase), to match the values of my multiselect field in Craft (I would rather map to value than label, although even if I mapped to labels, I would need to do some changes to the imported values).

I've tried more or less every event that FeedMe offers me (and some I've found in the code that are not in the docs), but I cannot find any that seems to do the trick.

I tried to use EVENT_BEFORE_PARSE_FIELD, which seemed to be a logical point (though the event is not mentioned in the docs), but as it doesn't actually set the  values changed in the event back to the values passed in (as it does with other events), the changes are simply lost. So no luck.

On my last try, I tried using EVENT_STEP_BEFORE_ELEMENT_SAVE, and changing the $contentData. But, as far as I can see, this variable is not passed in to the actual save function, it's just passed to an aftersave function, that for entries seems to do absolutely nothing.

So, short of having to loop through the entire feed, searching for the attribute in question in every node, and changing each of them, I can't see how to achieve this. It would make sense to be able to tweak the values passed in at some point where the code is handling one node, but I can't seem to find it.

If anyone have any ideas, I would really appreciate it.


texts: How do I prevent a runPendingTask script being included in returned HTML via ajax?

texts:
I have created a route to retrieve some categories via AJAX. When the AJAX call returns the HTML a runPendingTask script is also returned with the HTML. How do I prevent this?

/*<![CDATA[*/
(function() {
    var XMLHttpFactories = [
        function() {
            return new XMLHttpRequest()
        },
        function() {
            return new ActiveXObject("Msxml2.XMLHTTP")
        },
        function() {
            return new ActiveXObject("Msxml3.XMLHTTP")
        },
        function() {
            return new ActiveXObject("Microsoft.XMLHTTP")
        }
    ];
    var req = false;
    for (var i = 0; i < XMLHttpFactories.length; i++) {
        try {
            req = XMLHttpFactories[i]();
        } catch (e) {
            continue;
        }
        break;
    }
    if (!req) return;
    req.open('GET',
        "http:\/\/tfc.dev\/hollywood-road\/index.php\/actions\/tasks\/runPendingTasks",
        true);
    if (req.readyState == 4) return;
    req.send();
})(); /*]]>*/


texts: Cache not invalidating when using pagination with cache

texts:
Any idea why this code wouldn’t update/break the cache when new items are created?

Think perhaps the combination of my code for pagination, cache and the ability to also break for pending entries isn't correct and throwing it off...

{#
 # NEWS LISTING TEMPLATE
 # ---------------
 #}

{% extends "_layouts/main" %}

{# Get the most soonest upcoming pending entry for Cache breaking #}
{% set firstPending = craft.entries({
  section: 'news',
  status: 'pending',
  order: 'postDate asc'
}).first %}
{% set cacheUntil = firstPending ? firstPending.postDate : now|date_modify('+1 year') %}

{% set entries = craft.entries({
  section: 'news',
  order: 'postDate desc',
  limit: 6
}) %}

{# Get the articles and paginate them #}
{% paginate entries as pageInfo, pageEntries %}

{% block main %}
{% cache globally using key craft.request.path until cacheUntil %}

{{ entry.title }}

  {% for entry in pageEntries %}

         <time datetime="{{ entry.postDate|date('Y-m-d H:i:s') }}" class=" text-center mb-0 relative z-30 text-sm">

            {% include '_includes/svg/icon-date.svg' %}

            {{ helpers.dateFormatted(entry.postDate) }}

        </time>

            {{ entry.title }}

          view news

  {% endfor %}

{% endcache %}

{% include '_includes/partials/pagination' %}
{% endblock %}


texts:
In my general.php file I have a siteUrl environment variable declared:

'ontherocks.dev' => array(
    'devMode' => true,
    'environmentVariables' => array(
        'siteUrl'  => 'http://local.ontherocks.dev/',
    )
),

'dev.livesite.com' => array(

    'environmentVariables' => array(
        'siteUrl'  => 'http://dev.livesite.com/',
    )
)

But when calling it on my page to get page url: siteUrl ~ entry.url
siteUrl is appearing as it is defined in the Craft CMS General Settings SiteUrl.
Is it possible for the environment variable to take precedence?


texts: Can someone demystify tasks with a little more detail?

texts:
I love the notion of tasks, especially for large processes, but I've found that their isn't a lot of documentation around it which makes trouble shooting them via an authoritative source difficult.

A few things I've found out that I had misconceptions on:

A task is one request, no matter how many steps it has, that runs in the background.
Sub tasks are all part of that initial task's one request
Since a task is a single request it is subjected to the same PHP Limitations that a normal request would be (i.e., memory limit) (this really comes into play when important large amounts of data in a dev environment because there's a lot of information that's being logged via a single request -- could be 100s of MB of log files in request

Some things I'm still confused about:

Does a task run with a separate session ID and thread than the browser that initiated the task via the CP request? I've noticed using the Power Nap plugin that if I initiate the running of task via a CP request I can navigate to other pages while the task is still running, but with other plugins that import Commerce data, I have to wait until the entire import is done before I can navigate to another page.
Do multiple queued tasks all get a single request or are they lumped into a single request?
If I need to insert thousands of entries is it more performant / desirable to place all entries in a single task or queue a task for each entry?

I'm sure their will be more, but I definitely think a single location for figuring out the benefits / use cases / pitfalls of Craft Tasks will be hugely beneficial.

Thanks in advance for the discussion.


texts: I would like to give my client the client account, but first, I would like to assign my colleague as the client, just so we can see what the process looks like and see how our client will view Craft. Will it be possible to update the name and email address afterwards?


texts:
I am currently working through the demo site Happy Lager and installed another separate instance of Craft from github as provided from the Craft site.

I am creating ‘modules’ and adding fields etc..

But

When I try to add an entry all I get is the title field. Even on the dashboard there is no option of including fields for population. Could you advise what seems to be the problem, the demo works fine and i’m especially interested in using the matrix functionality of the field functionality.

But all I get is the title field when I try to add an entry and have experimented with matrix and stand alone fields


texts: Route linked to entry does not get translated correctly

texts:
I have a news archive: /news/
I want to display a link in each article to "News articles related to {the same person}"
I can't use /news/{person}, since I am using categories: /news/{cat}
So I created another section: /related-news/
Since this section will not have entries, I created a Route that links to the appropriate template. In the template I use getSegment to fetch articles at /related-news/{person}
My language switcher DOES translate /related-news/ to the other site's language
but it does NOT translate when there is something after related-news: /related-news/{person}
How can I fix this?


texts: Editing a tag not reflecting on all records.. kindof

texts:
We have hundreds of entries with the improperly spelled tag "accessibilty" (the third i is missing). A search for "accessibility" will not find them (spelled correctly).

I edited the tag on a record and it seems all the records have updated (in the control panel). That is, the tag is spelled correctly on all records.

Search however, does not find them. Both in the control panel and using craft.entries.search('accessibility') only return the ONE record that I edited. If I search for the misspelled tag ('accessibilty') I get all the remaining results.

I've emptied all caches.


texts: Display different Categories groups in custom breadcrumbs

texts:
I have a custom list of breadcrumbs that two of the levels reference different Category Groups. I'm able to get the correct breadcrumb to display for the page that I'm on using category.title, but I need to display the correct category for the previous breadcrumb also.

I've made some progress and have managed to get it to display the first category in the group I want by using {% set county = craft.categories.group('counties').first() %} but I need it to display the category that I've attached to the page with a category field, and not just the first item in the category.

Here's the current code:

{% block breadcrumbs %}

                All Developments
                {% set county = craft.categories.group('counties').first() %}
                {{ county.title }}
                {{ category.title }}

{% endblock %}


texts: if isAjax not working or not detecting ajax request in template

texts:
I can't stand this and have to ask for help again.. Still working on my buddy's website.

I want to increase a entry's counter (using Entry Count plugin)
So for my _entry.html I added an if statement to see if the request is for Ajax or not. If not, show the entire page. If it is only run the counter twig line.

_entry.html

{% if not craft.request.isAjax and not craft.request.isLivePreview %}
    {% extends "_layout" %}
    {% set title = entry.title|t %}

{% block content %}
 {# CONTENT GOES HERE #}
{% endblock %}

{% else %}
    {# ONLY INCREASE THE VIEWS/COUNT #}
    {% do craft.entryCount.increment(entry.id) %}
{% endif %}

Javascript on main page

$.get($(this).attr('data-url-item'), function(data) {
console.log(data);
});

Now I don't need to actually pickup any data or show it, so I'm using $.get() currently have the console.log() there so I can see which version of the page I'm getting.

Any help is appreciated.


texts: Load balancing nodes configuration (3 Craft nodes behind F5 Big-IP)

texts:
Craft deployed and working well on one node.  Now looking into load balancing 3 nodes behind a LTM device (F5 Big-IP).  The server environment is the following:

a GlusterFS replicated "shared" file-system mounted on the 3 nodes
Craft app is installed in the shared file-system (so is the webroot and all common files, but Craft itself is outside of the webroot).
a replicated MySQL database cluster hosting the Craft database (Percona xtraDB Cluster)
Each node is configured with PHP ZendOpcache and Nginx.

Currently, Craft Vhost is enabled only on one node because I have the following questions:

What should I do with the "storage" folder.  Currently, it's on the shared file-system, so all the node share the same folder, is this an issue, i.e. should I move it to a local file system and set CRAFT_STORAGE_PATH accordingly?
overridePhpSessionLocation: I set to true (so it does not write to 'storage/runtime/sessions'
CacheMethod, is this for OPcaching or user data caching?  (Currently ZendOpcache is configured at the PHP level, but I still see entries in the storage/runtime/cache folder)

Any pitfalls I should be aware or specific configuration needed for a load-balanced set of Craft instances?

Thanks.


texts:
Just wondering if theres anyway to force some validation on the username?
I have usernames being displayed locally, and therefore I'm trying to prevent email addresses being used. I have my client side validation set up with regex to prevent an email being used, but some users still seem to have been able to register with the email as there username (presumably they have JS disabled).

It would be nice to enforce that validation server side.


texts:
I've created a Fieldtype to use CK Editor so can take advantage of the advanced table formatting options over Redactor. However I want to keep Redactor for other content management. I came across this post so thought would give it a go: Craft WYSIWYG editor and CKEditor

All seemed to be working well but now whenever I focus on a redactor field the CKEditor buttons pop up. Any thoughts as to why this might be happening? Screenshot:

Fieldtype code posted up at https://gist.github.com/cole007/1ffa5036f8b79516ca34406d7b6833bf

Any thoughts as to what might be causing this?

Cheers

Cole


texts: Does "preprod" count as a dev sounding sub-domain?

texts: I would like to avoid the licensing error modal on a preproduction environment. Would preprod.random.domain work?


texts: How to fetch all assets that are in use, via a specific field

texts:
We have a channel of entries which all include the same asset field.
We are trying to fetch all assets that are actively in use, ergo the assets which have been linked to any of the entries in the channel via the specified asset field.
If possible we would also like to also get the title(s) of the entries to which the asset is linked, as part of the query.
This is happening in a module (PHP) not template (Twig).
Context: gallery of photos (assets) uploaded by teams (channel entries).


texts: Doing something with the success response from a Webhook

texts:
Craft Webhooks is great for sending one POST to a service... but if you need to parse the response from that hook... is there a way to do that? I can't see it as any option in the plugin, and I can't see a Service or anything for having Craft listen to that event?

I'm trying to get it so when a new User is created it's also subscribed to an Active Campaign account. I've no problem creating the Contact in Active Campaign through the Webhook plugin - it works flawlessly. But you can't then add the new Contact to an Active Campaign List because that requires a second POST that includes the new ContactID and a pre-defined List ID.

Craft has no clue about the new ContactID because it wasn't listening or parsing the response to the first successful Webhook (which contains an object with that data in it).

Likewise, it doesn't look as though it's possible to perform both actions in one API call.


texts: Is there a way to force Craft to notice a new license key?

texts: We are rebuilding a site from scratch using the existing license key (same domain) for the new Craft install. The new install was initially running as a Pro Trial, but Craft isn't seeing that we've added the new license. Not a huge problem, I'm sure it'll notice when there's an update or new environment, but just wondered if there is a way to 'refresh' the license.


texts: Problem with Int conversion when making a graphql request

texts:
Have a site that uses jquery, so trying to make calls to the graphql api using $.ajax(). It works fine for simple queries, but when trying to pass Int values for parameters, I keep hitting a variable type error: "Int cannot represent non-integer value".  It appears that maybe my Int values are getting converted to strings in transit - is there a way to avoid this?
A simplified version of the query:
const BLOG_QUERY = `
query SimpleQuery($offset: Int, $limit: Int) {
  entries(section: "blog", limit: $limit, offset: $offset, orderBy: "postDate DESC") {
    id
    url
    title
  }
}
`;

The jquery ajax call:
const params = {
  query: BLOG_QUERY,
  variables: {
    offset:1,
    limit:2
  },
}

$.ajax({
  context: this,
  type : 'POST',
  url : BLOG_POST_ENDPOINT,
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
  data: params,
  dataType : 'json',
  encode : true
}).done(
  ...// Do success stuff...
)


texts:
I'm working on a Commerce Grocery Store that allows users to select a day to have their order either picked up or delivered. Furthermore, some products will have a set quantity for each day of the week. As an example, Fresh Cinnamon Rolls may have 20 available on Thursday, and only 5 available on Friday. With users being able to make an order and then select 'Pickup on Friday', that would mean Friday's quantity for the product needs to be checked and adjusted.

This kind of thing is going to be a bit of work with a Craft Plugin. I've been struggling to come up with simply a concept/path for how I would go about this quantity-by-calander situation. The client is imagining the 'Quantity' field in variants being a calander, where he can define the quantity for each day of the month.

I know this isn't the most technical question as I'm not providing code. But it would be incredibly helpful to get some insight from some of you Craft/Commerce experts on just how you would go about something like this in a plugin. If you thought of an approach while reading this, I'd love to hear it!

Thanks in advance!!


texts: How does the allowAutoUpdates setting differentiate?

texts:
I'm not quite sure from the documentation what the difference is between 'minor' and 'build' updates.

How would the allowAutoUpdates general config setting have treated the update from 2.4.2726 to 2.5.2750?

What would happen when the 2.5.x update was released, depending on whether that setting was true, minor or build?


texts:
First time I install CraftCMS and during the wizard as well as in the Control Panel the fields for BaseURL are displayed like this:

I got passed the wizard by using the comand line tool but now can't create a new site.

Am I missing some sort of option / configuration? (running on Windows Server 2019 / IIS 10 / PostgreSQL 12.2)

Edit: I just noticed the same behavior within the email settings:


texts: Can I make Redactor add a 'title' attribute to img-tag?

texts: If I add an image to a rich-text field, I can set it's title. On the front-end however, the img-tag only gets an alt-attribute. I would also like the title-attribute to be set. Is this possible with a Redactor config-file, and if so, how?


texts:
We've a Craft 3 site hosted with Digital Ocean (Serverpilot set-up) with the DNS routed through Cloudflare.

The client has experienced issues uploading large ZIP files to (c140MB), returning a 413 error. After updating the PHP conf to enable larger files and tweaked the Nginx conf realised that the issue was with Cloudflare file upload limit.

Having set up a subdomain for the site to bypass Cloudflare we are now getting 500 errors in the browser console when trying to upload large files through the Craft control panel:

POST https://admin.site.com/index.php?p=admin/actions/assets/save-asset 500

There are no errors in the server logs and nothing showing up in the Craft debug toolbar.

Any suggestions on debugging and resolving this issue or on what might be causing the 500 error?


texts:
So I am new to Craft and I am attempting a site build with Craft Commerce.
I currently have a channel for Testimonials. Within this I have a relatedProducts field to assign products to testimonials.

What I am trying to achieve is to pull out the specific related testimonials on each specific product page.

Here is the code for my testimonials.

{% for testimonial in craft.entries.section('testimonials') %}

    {{ testimonial.body }}

        {{ testimonial.citation }}
        {% if testimonial.relatedProducts|length %}

            {% for testimonial in testimonial.relatedProducts %}
                {{ testimonial.title }}
            {% endfor %}

        {% endif %}

{% endfor %}

Is anyone able to assist or offer some guidance on how I can achieve this?


texts: After updating to Craft 2.5, standard and custom rich text (Redactor) fields disappear

texts:
After updating to Craft 2.5, some rich text fields have disappeared from the CMS.

While this similar to the issue described here, the answer did not fully resolve my issue.


texts: Composer require looking to craft/plugins/[plugin] directory but throws runtime error?

texts:
I've got Craft 3.1.32 up and running on dev machines and we're ready to get it into our test/stage enviromnments, which are built through a GitLab CI/CD. While doing this, we noticed some plugins wouldn't install and would throw a composer error:

  [RuntimeException]
  craft/plugins/[plugin-name]/ does not exist and could not be created.

Now, craft/plugins is the Craft 2 location for plugins, and that directory doesn't exist in Craft 3, right? I see there's a file that gets created called /vendor/composer/installers/src/Composer/Installers/CraftInstaller.php that has a reference to craft/plugins/{$name} so I'm guessing that this file is being invoked to do some quick stuff to clean  the plugin name. But I'm not sure what the directory is really doing.

Any ideas?

EDIT:
It looks like there's a nice file within the composer/composer repo that dates back to Craft 2: See CraftInstaller.php in GitHub that is pointing at old directories


texts:
I am trying to get Craft running on the Digital Ocean/ Serverpilot combination I've seen recommended here. Serverpilot is installed on the droplet and running fine. I created an app, uploaded the most recent version of Craft and unzipped it on the server. I renamed htaccess to .htaccess and put the db credentials in db.php.

I get a white screen on example.com and example.com/admin.
So I tried the alternate URLs recommended in Crafts installation guide, still white screen.

I also tried playing around with the omitScriptNameInUrls setting. No luck.

I also tried adding RewriteBase / to my .htaccess file.

I get this in the Apache access log: 82.156.127.145 - - [03/Mar/2016:01:45:59 -0500] "GET /admin HTTP/1.0" 500 -
82.156.127.145 - - [03/Mar/2016:01:46:00 -0500] "GET /admin HTTP/1.0" 500 -

This is in the Nginx access log: 82.156.127.145 - - [03/Mar/2016:01:46:00 -0500] "GET /admin HTTP/1.1" 500 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4" "-" 1072 0.014 "0" "0.014" "museumrotterdam.nl"

This is in the PHP access log: 82.156.127.145 - [03/Mar/2016:01:45:59 -0500] "GET /index.php?p=admin" 500 0 - 14106 17679 0.013 3407872 154.23% 0.00% "/admin"
82.156.127.145 - [03/Mar/2016:01:46:00 -0500] "GET /index.php?p=admin" 500 0 - 14106 17679 0.012 3407872 82.35% 0.00% "/admin"

There's nothing in the server's error logs.

When I add 'devMode' => true, to the config Craft does not log any errors.

What else could I try?


texts: Sprout Forms Recaptcha js error - everything flagged as spam

texts:
I'm using the Google reCAPTCHA plugin with Sprout forms. I'm trying to use an invisible reCAPTCHA badge, but I'm getting a js error on page load:
Unhandled Promise Rejection: TypeError: null is not an object (evaluating 't.addEventListener')

When I have reCAPTCHA enabled, every submission goes to spam with the error ["Google reCAPTCHA can't be blank."]
If I disable it, the form works fine, but it is overwhelmed with spam.
I'm not using a custom form template (well, I customized some of the html elements, but I didn't touch any of the actual twig elements).
Full error message is attached.


texts: Dynamic placeholder text in 'Plain text' field type

texts:
I have a plain text field that encourages content editors to write a more detailed description of a piece of content.

However, on the front-end the template will use the post title by default if this is not supplied.

I would like the placeholder text for this optional plain text field to represent the reality of this in the Dashboard - i.e. to display the title field as the placeholder if the field has not otherwise been used.

When editing the field, I have tried setting the 'Placeholder Text' as {title}, but this does not work - it displays "{title}"!

Is this possible? I don't want to create a new custom type of field as it seems a little heavy handed for this use case.


texts: Can access admin page (now), but not any site pages...yii not found http execption

texts:
Have not accessed my local .test sites in a bit.  I tried today.  I am getting a series of errors.

At first I could not access any page to include the admin page.  I ran Composer update from the command line (within a site's directory) and then updated Craft from the command line (.\ craft update all).  I can now access the admin page and successfully login, but I am still getting errors trying to access the actual site's home page (or any page other than the admin page).

HTTP 404 – Not Found – yii\web\NotFoundHttpException
Template not found: login

All my templates are located here...(according to Finder)  /Users/myname/Documents/Websites/mysite/templates/index.twig

Where should I start?


texts: Use-case: custom plugin or extended use of entries/categories/tags

texts:
I have to integrate a jobs feed into our website and I've been digging in the documentation, reading the core's code for a while now, and I am in a dilemma trying to figure out if in out use case I should write a plugin or just try to build everything on top Craft's core types?

It's important to know that each job will belong to a company, and will have a lot of custom settings that apply to each job. I've started developing a plugin for it, based on the Brandon's events plugin, which until now is working fine, however I's still not convinces if I'm doing things rights, since the Elements API is a little under-documented.

The questions that I have now are:

Should I base the Company on the Sections type, if I want the jobs to be translatable?
Should I base the Job on the Entry type, and write custom field types for every custom setting a job has to be translatable? (eg. Benefits and Requirements blocks, Many-to-Many relationships between job's industry, employment type, etc.)
Should I handle the saving of Many-to-Many relationships on my own, or Craft handles these if I choose the right core type?
Should I save all these custom fields a job has in the content table or in a custom table?
I will also import jobs from out ATS system, would it be enough to write a plugin just for this, and integrate all the aforementioned requirements into Craft's code types, without developing a plugin?
I would like to tag every job with the technologies a job requires, and assign custom logos of these technology tags. How would I handle this using a custom plugin, extending the core tags?
The jobs will have an advanced search and filtering based on the Many-to-Many relationships with industries, experience level, employment type; what would be the best approach to achieve this? using custom queries in a plugin with a custom element type or building on top of core types?

I just started using Craft, so I still don't understand 100% the core, that's why I cannot decide which would be the best approach.


texts:
Each of my entries has multiple categories (e.g. series, disciplines, and stages). I can get a list of elements related to a single category but I'd also like to get the category information as well (title, summary etc). Ideally, I'd like to pass the $slug to the transformer so I can grab the category from there, is that possible?

Here's my current code for an endpoint from elementapi.php

'api/series/<slug:{slug}>.json' => function($slug) {
  // get category by slug
  $series = craft()->elements->getCriteria(ElementType::Category);
  $series->group = 'series';
  $series->slug = $slug;
  $series->first();

  return [
    'elementType' => ElementType::Entry,
    'criteria' => [
      'section' => ['lessons'],
      'relatedTo' => ['targetElement' => $series]
    ],
    'transformer' => function(EntryModel $entry) {
      return structureEntry($entry);
    }
  ];
},

/*-------------------------------------------*/

function structureEntry($entry) {
  return [
    'id' => (int)$entry->id,
    'title' => $entry->title,
    'slug' => $entry->slug,
    'summary' => $entry->summary ? $entry->summary : null,
    'featuredImage' => $entry->featuredImage->first() ? getImageSizes($entry->featuredImage->first()) : null,
    'body' => $entry->body ? (string)$entry->body : null,
    'series' => $entry->series ? getCategoryData($entry->series) : null,
    'stage' => $entry->stage ? getCategoryData($entry->stage) : null,
    'disciplines' => $entry->discipline ? getCategoryData($entry->discipline) : null
  ];
}

function getCategoryData($categories) {
  $cats = array();

  for($i = 0; $i < count($categories); $i++) {
    $cats[$i] = [
      'id' => (int)$categories[$i]->id,
      'title' => $categories[$i]->title,
      'slug' => $categories[$i]->slug,
      'summary' => $categories[$i]->summary
    ];
  }

  return $cats;
}

Ideally, I'd like to do something like this:

'api/series/<slug:{slug}>.json' => function($slug) {
  // get category by slug
  $series = craft()->elements->getCriteria(ElementType::Category);
  $series->group = 'series';
  $series->slug = $slug;
  $series->first();

  return [
    'elementType' => ElementType::Entry,
    'criteria' => [
      'section' => ['lessons'],
      'relatedTo' => ['targetElement' => $series]
    ],
    'transformer' => function(EntryModel $entry) {

      $category = craft()->elements->getCriteria(ElementType::Category);
      $category->group = 'series';
      $category->slug = $slug;
      $category->first();

      return array_merge(structureEntry($entry), structureCategory($category));
    }
  ];
},

Any help would be appreciated, thanks!


texts: How to show variations of a single entry? Even possible?

texts:
We are building a Commercial Real Estate site for a fairly large commercial real estate company and we're coming from an older custom-built site and there is a work flow and associated data logic we're having trouble figuring out how to best replicate in Craft.

When they list properties for sale or lease, they have a set of common fields for a given building (ex. address, photos, city, etc) and then sometimes need to add Units within that building, each with its own set of fields (ex. size, unit number, price, etc).

Sometimes these Unit(s) get listed all together on the one listing (or in the Craft sense, entry) on the front end. However, sometimes they need to be listed separately on the front end (ie. individual Units can be chosen to show up as their own listing (or separate entry)). This is in varying combinations (ie. any Unit could be flagged to show as separate - but not all Units need to). In this case, those separate Units still share (and display) the common building fields (ex. address, photos, city, etc).

What this means from an entry point of view, is we potentially need multiple URL slugs to get to each listing when some Units are flagged to show separately (for example: sale/building1, sale/building1-unit200, sale/building1-unit303 ...or whatever).

So what we're trying to solve us how to handle this. We are trying to preserve an intuitive and easy workflow for the editor, where they go add a new listing on one entry page, and via a Matrix field could add multiple Units - and within each Matrix Unit block, could have a toggle field that says "Show this unit as a separate listing").

The question then is how to access those "show as separate" units on the front end as they technically all share the same URL slug?

We briefly considered using related fields (separating out units as entries and the common building data as entries) but that would become incredibly difficult to remember, maintain and organize for which units belonged to what buildings across many hundreds of listings and thousands of units. As well, many buildings do not even have units.

We also considered a custom plugin that would create a duplicate entry for each flagged Unit when the entry is saved (and conversely remove duplicated entries when a Unit is unflagged). That seems kludgy and possibly complicated but maybe we're wrong on that? Also, not certain if there'd be a way to hide those duplicate entries from users in the CP so they're not confused by those (as they're always thinking that they work on one single entry for each building with its units).

Any thoughts on how to tackle this would be greatly appreciated.


texts:
I’m using Craft to add CMS functionality to an e-commerce website via craft/app/bootstrap.php

Trying to pull a 'timeline' structure with a featuredImage Asset Field.

This code works and pulls the full size image, but I can’t work out how to pull the ‘small’ size of image which is set up as a transform.

I assume it should be something like $entry->featuredImage[0]->url['small'] but nothing seems to be working.

Any help appreciated.

$timeline = Craft\craft()->elements->getCriteria(Craft\ElementType::Entry);
$timeline->section = 'timeline';
$timeline->with = 'featuredImage';
$timeline->withTransforms = 'small';

foreach ($timeline as $entry)
{
  ?>

<img src="<?php echo $entry->featuredImage[0]->url; ?>" alt="<?php echo $entry->featuredImage[0]->title; ?>"/>

<?php echo $entry->title; ?>

          <?php echo $entry->body; ?>

  <?php
}


texts: revision entry is the same with saveEntry in plugin

texts:
I have made a plugin where I save a status of a related entry. I have enabled revisions in the section. But when I update the status entry, a new version is made with the newest content, but all the content of the previous versions are overwritten and are the same as the latest version.

Did I forgot something?

My code:

$saveStatus = craft()->elements->getElementById($statusEntry->id);
$saveStatus->getContent()->setAttributes(array(
                            'eigenaarId'  => array($user->id),
                            'advertentieId' => array($entryID),
                            'doorkoppelaarId' => array($doorkoppelaar->id),
                            'statusCode' => $status['status_code'],
                            'statusMessage' => $return[$i]['message'],
                            'statusErrors' => json_encode($errors),
                            'statusWarnings' => json_encode($warnings),
                        ));

$newStatusEntry = craft()->entries->saveEntry($saveStatus);


texts:
Live preview is not working.  The following error appears in Inspect Element (Safari).  It then times out and generates a whole bunch of can't load errors. but this appears to the root of those subsequent errors.

  XMLHttpRequest cannot load http://www.mydomain.com/index.php?p=posts/2016/thisost. Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin.

I saw a related question that referred to the .htaccess file.  But I can't seem to find the.htaccess file.

So, I guess this is an A and then B question.  The first (A) being the focus and B only of import if its related to the solution for A.

I hope that makes sense.  Thanks


texts:
I have a includeJS variable set that populates a javascript calendar from an entries loop, with a large amount of entries which needs to be cached.

Whenever I cache this section I get this error:

Error while sending QUERY packet. PID=11878

What's the problem here?


texts: How can I send a confirmation Mail to the user who submits the form within the ContactForm Plugin ?


texts:
I'm not sure what is the cause for this page rendering so slow.
I thought it was the image transforms but I've removed them and still it's really slow to render.

Page in question: http://dharmaavenue.net/e-drops

From the profiling report:

Time:   64.61081s

Memory: 461,289Kb

Total Queries: 52

As you can see it's just a simple nav menu.
Here is the code:

{% block content %}

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

            {% nav entry in eDrops %}

                    {% if entry.slides|length %}
{#
                        {% set image = entry.slides.first() %}
#}
                         {{ entry.title }} >

{#

#}

                    {% else %}
                        {{ entry.title }}
                    {% endif %}

                    {% ifchildren %}

                            {% children %}

                    {% endifchildren %}

            {% endnav %}

{% endblock %}

The entries are basically individual gallerys with many images in the slides field. I'm guessing that all the details of these are being fetched unecessarily, and that stopping this from happenign will solve my problem.

If anyone can help me with this it would be most greatful :)


texts: Efficient way of looping through a large amount of users?

texts:
Hi I have a plugin that loops through users to find out their interests. Counts the number of interests in total for each interest and displays this in a widget on the dashboard with the interest name and amount of users with that interest. The code I have works but fails with a max execution time and only pulls out minimal results for each interest. Is there a way to do this more efficiently so the script does not timeout. This is what I have so far but I'm sure looping through 20k+ users and checking each interest field to see if the category id is in it is highly inefficient. Cheers.

public function getInterestRank()
{
    $criteria = craft()->elements->getCriteria(ElementType::Category);
    $criteria->group = 'interestTags';
    $category = $criteria->find();

    //Get all users
    $user_criteria = craft()->elements->getCriteria(ElementType::User);
    $users = $user_criteria->find();

    $interestArray = array();

    foreach($category as $interest)
    {
        $title = $interest['title'];
        $count = 0;

        foreach($users as $user)
        {
            if($user['interests']) {
                if(in_array($interest['id'], $user['interests']))
                {
                    $count = $count+1;
                }
            }
        }
        $interestArray[$title] = $count;
    }

    arsort($interestArray);
    return ($interestArray);
}


texts:
I am trying to edit an entry automatically when you press a button. Is there a way to do this?

A bit more detail: I have listed up a few entries, each with their own button. When I press the button on a specific entry, I want the currentUser to be added to the User Field of that entry.

Currently I have managed to get this semi-working with a form where the user can edit the entry through input fields etc., changing their value, then submiting (as outlined under Entry Form in the docs). This is the prossess I want automated. When you press the button in the front-end the entry is edited with values set in the code and submitted.

Thanks!


texts: Switch entry type depending on entry field

texts: Is there a way to switch entry type dynamically depending on the selection of a field value on a entry page? For instance, could I have a structure for motorized transportation and then have a dropdown that has the values car and motorcycle. If "car" is selected then an entry page would be presented that gets number of doors, if "motorcycle" is select then an entry page is selected that gets engine cc's?


texts: Best way to use custom enums in my plugin templates?

texts:
I am building a plugin that's uses an enum for custom statuses. The statuses are integrated within my plugin with the exception of changing the status in my template code.

pluginname/enums/PluginStatus.php

<?php
namespace Craft;

class PluginNameStatus
{
    const Approved = 'approved';
    const Denied   = 'denied';
    const Pending  = 'pending';
}

What is the best method to grab the enum values and display those in a select field for my edit template? All of my templates are rendered via controller actions so I am thinking that assigning the enums to an array and passing to the templates as $variables might be the most practical method.

pluginname/controllers/PluginNameController.php

<?php
namespace Craft;

class PluginNameController extends BaseController
{
    public function actionShowIndex()
    {
        $variables['customStatuses'] = array(
            PluginStatus::Approved => 'Approved',
            PluginStatus::Denied   => 'Denied',
            PluginStatus::Pending  => 'Pending',
        ),
        $this->renderTemplate('pluginname/_edit', $variables);
    }
}


texts: How to use category in auto generated title?

texts: I have an entry which has a category field. I want an auto-generated title for this entry that uses the assigned category title (first category title in case of multiple categories). I am not sure what to insert in the "Title Format" field.


texts:
I currently have a plugin which needs to do things on save and delete entry events. My save entry code is all working perfectly but the onDeleteEntry code doesn't ever fire when I delete an entry.

I have tried using the event both ways mentioned in the documentation

craft()->entries->onDeleteEntry = function(Event $event) {
$entry = $event->params['entry'];
//etc etc
};

and

craft()->on('entries.deleteEntry', function(Event $event) {
$entry = $event->params['entry'];
//etc etc
});

both of these are inside the init function.

Does anyone know if there is a particular way this event needs to be used that differs from the onSaveEntry event, which works fine?

Here's a link to the events reference https://craftcms.com/docs/plugins/hooks-and-events#events


texts: Matrix field validation on guest entry submission

texts:
First I illustrate the way I set up guest entry form.

Let's say I have channels blog product and comment cart.

Guest entry submits to the comment cart channel. Form lives in template which I use to show blog's product's entry.

Now I just send required field title which won't get passed by validation unless it isn't blank.

According to Guest Entries settings to show my blog's product's content along with my guest entry form I have to change the name of entryVariable key from entry to whatever not taken variable name let's say entryError in an event of validation error to not overwrite blog's product's variable entry.

In short this is how the template looks like when blog product entry load. This is just part of the form which is executed when first item is added to the cart matrix field in cart channel.

{# Product's title #}
{{ entry.title }}

{# Product's text #}
{{ entry.text }}

{# Show form error #}
{% macro errorList(errors) %}
    {% if errors %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="guestEntries/saveEntry">
    <input type="hidden" name="sectionId" value="2">

    <input type="hidden" name="title" value="Some dynamic title">

    {# Matrix field "cart" #}
    {# Block type field we want the product to save in. #}
    <input type="hidden" name="fields[cart][new1][type]" value="product">

    <input type="hidden" name="fields[cart][new1][fields][productTitle]" value="{{ entry.title }}">

    {# Quantity #}
    Quantity *
    <select id="qntySlct" name="fields[cart][new1][fields][productQuantity]">
        <option value="">--Please, select the quantity--</option>
        {% for i in 1..10 %}
            <option value="{{ i }}"{% if productQuantity == i %} selected{% endif %}>{{ i }}</option>
        {% endfor %}
        <option value="">I need more</option>
    </select>

    {# Error message #}
    {% if entryError is defined %}

            {{ errorList(entry.getErrors('productQuantity')) }}

    {% endif %}

</form>

Form submits if title quantity is defined and if not I get entryError defined but don't get the title's quantity's  error shown.

The warning of title's quantity's error is logged in the Application Log.
Have anyone came accross this unlikely issue?

CORRECTION UPDATE

Thanks to the Robin's comment bellow to debug it with {{ dump() }} function I found out that input quantity field with variable title is returning the error value. However I didn't mentioned in my question that I'm actually posting/retrieving to/from matrix field as I didn't want to make the question pointlessly complicated with all those fields I've set.

I've been misleaded/figured that to access field's variable in

{{ errorList(entry.getErrors('variable')) }} for example, is not valid for matrix field.

Now I can't find any info on how to access matrix field for entry validation using:

{% macro errorList(errors) %}{% endmacro %}.


texts:
I am trying to install Craft CMS on Ubuntu 14.04 running NGINX, I get this error log, any suggestions on how to fix this?

2017/08/26 16:18:08 [error] [exception.Craft\HttpException.503] exception 'Craft\HttpException' in /usr/share/nginx/craft/app/etc/web/WebApp.php:800
Stack trace:
#0 /usr/share/nginx/craft/app/etc/web/WebApp.php(203): Craft\WebApp->_processInstallRequest()
#1 /usr/share/nginx/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#2 /usr/share/nginx/craft/app/index.php(62): CApplication->run()
#3 /usr/share/nginx/html/index.php(19): require_once('/usr/share/ngin...')
#4 {main}
REQUEST_URI=/

Thanks


texts:
Basically, a client needs to provide a discount that offers free shipping over a certain item total. Easy enough. But the discount needs to only apply to one shipping method, not all.

I can easily display no shipping charge, but if a customer chooses a shipping method that they should still be charged for, I am unable to remove the free shipping discount.

So it's this issue:

https://github.com/craftcms/commerce/issues/181

Does anyone have a work around?

Like is there a quick and dirty business logic few lines of code to remove a discount programmatically?


texts:
Just tried to run the auto-update to v3.0.0 and it failed catastrophically with the message:

  Error: file_put_contents(/var/www/html/craftcms/composer.lock): failed to open stream: Permission denied

Now my control panel page has a "Finish Up" button that doesn't seem to do anything (the styling on the page is completely broken).

It also looks like Craft didn't take a backup, as my most recent backup is from RC4, back in January.

I'm not sure how to recover from this, if it's even possible, as the docs don't seem to have any useful information.

Any help would be appreciated.

UPDATE

Following Brad's instructions below (thanks Brad!), I found that my composer.json file had the version set to 3.0.0-RC5 (I guess the RC4 backup is the most recent after all--I thought I was on a later version).

I tried running composer update but now I'm getting the following error:

Problem 1

- Installation request for craftcms/cms 3.0.0-RC5 -> satisfiable by craftcms/cms[3.0.0-RC5].
- Conclusion: remove roave/security-advisories dev-master
- craftcms/cms 3.0.0-RC5 requires yiisoft/yii2 ~2.0.13.0 -> satisfiable by yiisoft/yii2[2.0.13, 2.0.13.1, 2.0.13.2, 2.0.13.3].
- yiisoft/yii2 2.0.13 conflicts with roave/security-advisories[dev-master].
- yiisoft/yii2 2.0.13.1 conflicts with roave/security-advisories[dev-master].
- yiisoft/yii2 2.0.13.2 conflicts with roave/security-advisories[dev-master].
- yiisoft/yii2 2.0.13.3 conflicts with roave/security-advisories[dev-master].
- Installation request for roave/security-advisories dev-master -> satisfiable by roave/security-advisories[dev-master].

I also tried setting my version to RC4 in composer.json but got the same result.

Should I just remove roave/security-advisories from composer.json and try again?

Please excuse my ignorance--I have approximately zero experience with Composer.


texts:
Ok, I'm getting pretty crazy here. I'm trying to remove a variant from the cart. Adding works fine, like this:
<input type="hidden" name="purchasableId" value="{{ variant.id }}" id="{{ variant.sku }}">
<input type="submit">

(variant is an item from product.variants)
However, when I want to remove an item, I do it like this:
<input type="hidden" name="lineItems[{{ variant.id }}][qty]" value="0">
<input type="submit">

But nothing gets removed. The weird thing is, when I query for lineItems, there's an item with the id "92". The id from the variant is 19874. So that's the id I use in the hidden qty field. I have absolutely no idea where this 92 comes from. It is not the variant id. It's alo snot the product id. I don't know what it is. What am I doing wrong here?


texts: Equivalent of "EE Pages" module in Craft?

texts: I'm struggling to find a solution for a clients request to be given complete flexibility to create new sections and pages from within Craft. Essentially I would create a series of generic page templates which the admin could then use to build out the site and I can use the Navee plugin to provide a way to create a custom navigation. But this does not change the URL of the entry of course. I suppose what I need is a version of the ExpressionEngine Pages module for Craft. Is there such a thing?


texts: How to render template instead of throwing an error?

texts:
I'm working on a plugin that hooks into Craft's Guest Entries plugin.

I want to send a confirmation mail after an entry has been saved. This works nicely so far.

Now I want to catch any errors in the mail service. This works nicely so far. Here's my code:

private function mailHandler($from, $to, $subject, $text)
{
    try
    {
        $message = new \craft\mail\Message;

        $message->setFrom($from);
        $message->setTo($to);
        $message->setSubject($subject);
        $message->setTextBody($text);

        Craft::$app->mailer->send($message);
    }
    catch (\Exception $e)
    {
        echo \Craft::$app->view->renderTemplate('error', ['error' => 'Test']);
        die();
    }
}

There are two problems I'm facing:

1) I have to "stop" the controller action, that's why I need the die. This seems dirty though, is there any other way I could stop the controller?

2) If I do it like this, my error template is rendered, but without any CSS. What am I missing there?

Thanks a ton for your help!


texts:
I'm having an issue creating a matrix block from a module. I'm currently doing the following:

Calling an API using Guzzle
Getting that request and iterating over a media block.
Trying to create a new Matrix Block with each iteration.
Adding data from the request into each Matrix Block.

** EDIT **

I got this working using the following code:

                $data = json_decode($json, true);
                $number = 1;

                foreach($data['media'] as $element) {
                  $matrixData = array();
                  $matrixData["new$number"] = array(
                    'type' => 'media',
                    'enabled' => true,
                    'fields' => array(
                      'mediaDescription' => $element['likes'],
                    )
                  );
                  $user->setFieldValue('recentPosts', $matrixData);
                  $number++;
                }

Example JSON

"media": [
        {
            "media_id": "2053313765945828720",
            "instagram_user_id": "1",
            "shortcode": "Bx-1f2_nuVw",
            "created_date": "1558994096",
            "caption": "",
            "comments": "7077",
            "likes": "1131719",
            "media_url": "https://www.instagram.com/p/Bx-1f2_nuVw",
            "media_image_url": "https://scontent-lhr3-1.cdninstagram.com/vp/8e6c054cec7d3c3657bc73d49dae0fd9/5D7B651B/t51.2885-15/e35/c0.134.1080.1080/s150x150/61993210_834852143539503_2474404095511077560_n.jpg?_nc_ht=scontent-lhr3-1.cdninstagram.com",
            "type": "IMAGE",
            "mentions": [],
            "hashtags": [],
            "date": "2019-05-28 02:44:09",
            "last_check_date": "2019-05-28 20:25:24"
        },
...

Unfortunately, now my forloop isn't saving new matrix blocks.


texts:
I have a series of talks that have speakers as a related entry.

I'm looking for a way to order the talks by the last name of the speaker (the last name is the title of the speaker channel).


texts: Fields not displaying for some entries in control panel

texts:
Since I updated to Craft 2.5, I have a weird bug in my entry edition window. Some entries work just fine, and other gives me this :

Like if there was nothing (actually there is something, this single in particular has two tabs and many fields in each..)
Any fix ? Thanks !


texts: Is there an updated version for Craft 3 showing how to change the name of 'Singles' and 'Structures'? https://www.youtube.com/watch?v=ObC4mhXjiOE


texts: Special order filter (by language) in CP for Craft Commerce

texts:
We have a online-shop for german customers (Craft 2 + Commerce 1) and will expand the shop for american customers (via second domain).
Is there a way to filter the order (status) views in the Backend by domain/language.
The purpose is that the american backend user should only see orders that come via the american domain and the german backend user should see only german based orders.


texts: User Registration Form error message customisation

texts:
Where can I edit the error messages for the user registration form e.g for

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

I want to change this wording:

Email "tom.bowler@mailbox.net" has already been taken.

to something like:

Email "tom.bowler@mailbox.net" has already been taken. Login here instead...