texts: Break-up Element API Config into partials

texts:
I'm working on a Vue SPA (single page application) for a client and my ElementAPI config file has grown to be quite large.  To make it easier to maintain I was looking for suggestions of how to have each endpoint in its own file.

Any feedback is appreciated!


texts: Display only those entries that have assets

texts:
I'm trying to get a list of entries that have at least one asset in it (standard assets field) called "assets".

{% for entry in craft.entries.section('banks').first.assets.filename(':notempty:').limit(2) %}
<p> {{ entry.title }}
{% endfor %}

It don't show anything, no errors either.

Please advice.


texts: Changing Image transforms for different media queries

texts:
Is it possible to set different image transforms for different media queries?
I have a grid layout containing 1 large image and four smaller images on large screens. I have created two image transforms; one called gridSmall and another called gridLarge.
When the screen size is made smaller, all the grid items are arranged in rows of two and ideally I would want them the same size. So therefore I would need the to change the transform of the gridLarge to gridSmall to match the other four images. Is this possible to do without a third party plugin?


texts:
I’ve already got a ton of content put in by the client, and there’s quite a bit of accented characters (é, à, ...) in the titles, and thus also in the slugs where they get url encoded, which my client considers 'ugly'.

Now I’ve added the limitAutoSlugsToAscii' => true rule to the config, but how can I best rework the url’s for the already existing content? There’s about 1000 entries already in the website so I’d rather not go over them by hand.

Can I just clear the slug column in the database? Or will I have to write a temporary custom controller action that I can trigger to loop over all entries to redo their slug? Or is there another (better) solution?


texts: How to fetch Category of current Entry and build "Next / Prev" urls

texts:
My original question here helped me figure out how to build my URL structure but now the site has introduced two categories: design and photo.

I want the "Prev" and "Next" buttons to navigate back and forth within the category of the current entry.

I know how to get the category of the current entry here:

{% for category in entry.category %}
   {{ category.title }}
{% endfor %}

...but I don't know how to put category.title into a variable to build my params. This is my best shot at the solution but it's broken and I've given up spinning on it myself :) Any help would be much appreciated.

{% set category = "craft.categories.relatedTo(entry)" %}

{% set params = craft.entries.section('projects').order('title asc').relatedTo(category) %}

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

{% if nextEntry %}
    {% set nextEntryUrl = nextEntry.url %}
{% else %}
    {% set firstEntry = craft.entries.section('projects').first() %}
    {% set nextEntryUrl = firstEntry.url %}
{% endif %}

{% if prevEntry %}
    {% set prevEntryUrl = prevEntry.url %}
{% else %}
    {% set lastEntry = craft.entries.section('projects').last() %}
    {% set prevEntryUrl = lastEntry.url %}
{% endif %}


texts:
Most of our websites use a main structure for the page tree. In some cases, those structures can become quite large and entries further down are not shown initially without scrolling down/autoloading. This is annoying, especially it has to be done again and again when you reopen the structure overview.
For me some changes / additions could improve the situation:

Have a setting that forces only level 1 entries to be shown, the others are closed.
Alternatively have a button to close all level 2 and deeper subtrees.
and maybe remember search terms when leaving the overview and coming back.

What are your thoughts on this?


texts: Querying across relationships in a template

texts:
I have two Sections on my site: Country and Alert. The Alert section has a relation with Country via an "Entries" field. An Alert represents something that is happening in a particular country for a period of time so it will have a post date and an expiry date.

In my template, I want to show a list of the 5 Countries that have currently active Alerts (ideally ordered by the country with the latest Alert).

I'm not sure how query across relationships in Craft (outside of using the relatedTo query, but that only allows you to related to one entry, not a number of entries)? It seems all relationships are handled in a separate relation table in the DB.

How can I achieve an query such as this within a Craft template?


texts: Is it possible to clear caches and re-index assets programattically?

texts:
When migrating a Craft site, I'm used to...

deploying files
checking my config, tweaking as necessary
loading a database backup
running "Update Asset Indexes" and "Clear Caches" from the control panel

That last step is always important because random oddities and broken images are fixed site-wide because of caching and transforms. Now I'm attempting to automate the process with a Docker deploy script, so I'm wondering: is there any way to Update Asset Indexes and Clear Caches programmatically?

I know that you can nuke the craft_assettransformindex table and delete the contents of /craft/storage/runtime/assets and /craft/storage/runtime/cache (related question), but is that really doing the exact same thing?

Note that by "programmatically," I generally mean anything you could achieve from a Linux terminal: MySQL commands, PHP or shell scripts, etc.


texts: How to apply a discount or sale to a variant?

texts:
The sale and discount menus only discount at the product level. However, I need the ability to apply discounts and sales at the variant level. How would I do this?

Example:
I sell a piece of software (the product). There are new licences and upgrade licences (the variants). I want to apply a discount to only the new licences.


texts: Get related entries in plugin via Entries field type

texts:
I have 2 sections: Gift Cards and Merchants.

In Gift Cards, I have a entries field that is limited to the Merchants section and limited to 1 selection.

In Merchants, I have a field merchantId that is a plaintextfield.

In my plugin, I would like to return all gift cards that have a merchantId of 123.  I've tried a few different ways, but all ways have either given no results or I get a 'missing index Merchant' error in the FieldServices class.

Hopefully someone here has done something similar and can point me in the right direction.


texts:
In the CP there are discounts that are applied to products in cart.

Is there an option in the CP to apply discounts to subscription plans or would this need to be done by creating a module? Just need confirmation before building a custom module as the docs doesn't specify such a option.

Using: https://github.com/craftcms/commerce-stripe

Commerce: Latest to this date

CraftCMS: Latest to this date


texts:
I have 2 basic JSON files, the only difference between the files is the product.type('')

In my general.php I have turned on 'generateTransformsBeforePageLoad' => true,

The first JSON file (200 products ) loads within 2 second and the image is like this:

http:\/\/mysite.dev\/files\/coins\/_transform\/1763-myImage.jpg

The second file (30 products) takes 10+ seconds to load, and displays the image like this:

http:\/\/mysite.dev\/cpresources\/404?x=CjvOQxsnA

I am using the same image transform for both files.
Why is it that the image in the second file isn't saved, because of this it takes 10+ seconds for the file to load.

I am using the same exact code for generating the transforms so I don't know why this is happening.


texts: Is there a way integrate redactor with your assets fields?

texts: Does anyone know if there is a way to extend redactor to render a template, for example, when inserting an image so that it could also display custom asset fields (i.e. caption, photo credit, etc.) in a small html block? I have no idea how difficult or easy it is write redactor plugins.


texts:
Is there a way to reverse the Assets field keeping the fixed order? I've tried a couple of things:

myAssetsField.order('fixedOrder desc') //breaks
myAssetsField.order('id desc') // wrong, since they're not sorted by id
myAssetsField.reverse() // does nothing

Any ideas?


texts:
I have a large site running Yii (1.1.x), complete with many controllers for specific applications.

A big section of the site is "static" pages, which use Yii to render out using a site layout.

I'm interested in migrating the "static" portions of the site into content management, but I need to keep my applications. Is there an easy way to create Craft plugins that will call my existing Yii controllers? Or is there some other way to port the functionality without rewriting everything?


texts:
Twig docs include a format_number filter, as of ver 2.12
My install shows Twig at ver 2.12.5, so should work, but throws a Twig Syntax Error: Unknown "format_percent_number" filter.
This started with not being able to use the Craft "percentage" filter because I was doing this:
{{ var1 / var2 | percentage }}

That filter fails because 'var1 / var2' returns a number without a leading zero and Craft does not like that.
So, two issues:

the Twig filter format_number not work
any thoughts on how to get around the Craft percentage filter issue

Thanks!


texts:
There was this "one time fee" mantra overall and now I read
https://craftcms.com/news/dot-all-2017-announcements

They will charge additionally on yearly base?
Does this include any update and security updates as well?


texts: How to filter entries by month and year?

texts:
I'm taking the month and year from parameters in the url like this...

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

The url would look like this: ?month=September&Year=2014

... and want to return entries from a specific section where the postDate month and year match those parameters.

Be very grateful for any pointers.

Thanks
Lee


texts:
I'm attempting to create something within my template using global values and checkboxes. What I need this to do is "if it's one of the days of the week marked as open, as selected by a checkbox, and the time is between X and Y, then display that we are open, otherwise, say we are closed".

I have Monday through Sunday listed as checkboxes, and their values are set with Monday as 1, Tuesday as 2, etc, and I'm trying to compare it to 'now'|date('N'), which lists the day of the week as a number.

{% for dayOfWeek in theCenter.openWeekDay %}

    {% if 'now'|date('N') == dayOfWeek and 'now'|date('Hi', 'America/Denver') > theCenter.openTime|date('Hi') and 'now'|date('Hi', 'America/Denver') < theCenter.closeTime|date('Hi') %}

We are OPEN

    {% else %}

We are CLOSED

    {% endif %}

{% endfor %}

I've selected Tuesday through Sunday as open by selecting their checkboxes in the globals form. The code above returns 5 'We are Closed' and 1 'We are Open' results. I just need it to check if today is one of the open days, and if it's between open and closing time, and display one result.

I've tried this:

{% if 'now'|date('N') in dayOfWeek and 'now'|date('Hi', 'America/Denver') > theCenter.openTime|date('Hi') and 'now'|date('Hi', 'America/Denver') < theCenter.closeTime|date('Hi') %}

but it returns 6 'We are Closed'. I've been trying to figure this out for several hours, but the documentation doesn't seem to be made for what I want to do, and I'm probably looking in the wrong place.

Any suggestions on how I could get this to work?

EDIT

Here's the entire script:

{% if 'now'|date('z', 'America/Denver') > theCenter.startWinterSeason|date('z') or 'now'|date('z', 'America/Denver') < theCenter.endWinterSeason|date('z') %}
    {% for dayOfWeek in theCenter.openDaysWinter %}
        {% if dayOfWeek.selected and 'now'|date('N') == dayOfWeek and 'now'|date('Hi', 'America/Denver') > theCenter.openTimeWinter|date('Hi') and 'now'|date('Hi', 'America/Denver') < theCenter.closeTimeWinter|date('Hi') %}

The center is OPEN

        {% else %}

The center is CLOSED

        {% endif %}
    {% endfor %}

&nbsp;{{ theCenter.hoursTitleWinter }}

Tuesday &mdash; Saturday
{{ theCenter.openTimeWinter|date('g:i A') }} to {{ theCenter.closeTimeWinter|date('g:i A') }}

{{ theCenter.timeNotes|raw }}

{% elseif 'now'|date('z', 'America/Denver') > theCenter.startSummerSeason|date('z') and 'now'|date('z', 'America/Denver') < theCenter.endSummerSeason|date('z') %}
    {% for dayOfWeek in theCenter.openDaysSummer %}
        {% if dayOfWeek.selected and 'now'|date('N') == dayOfWeek and 'now'|date('Hi', 'America/Denver') > theCenter.openTimeSummer|date('Hi') and 'now'|date('Hi', 'America/Denver') < theCenter.closeTimeSummer|date('Hi') %}

The center is OPEN

        {% else %}

The center is CLOSED

        {% endif %}
    {% endfor %}

&nbsp;{{ theCenter.hoursTitleSummer }}

Tuesday &mdash; Saturday
{{ theCenter.openTimeSummer|date('g:i A') }} to {{ theCenter.closeTimeSummer|date('g:i A') }}

{{ theCenter.timeNotes|raw }}

{% else %}

EPIC FAIL

{% endif %}

Which outputs this:

I need it to only show the center is closed once.


texts:
First sorry for my bad english.

What i want to do: display comments on a page, one at the right one at the left.

My code look like this:

{% for i in 0.. NbComment %}
   {% if  (i is divisibleby(2)) or (i == 0) %}

       <!--Right comment-->

   {% else %}

       <!--Left comment-->

   {% endif %}
{% endfor %}

It works perfectly except when I only have one comment: it display nothing.
Thanks for your help.


texts: Craft isn't regenerating the image transform when the focal point changes

texts:
I've got a basic image transform in a template:

{% set crop = {
    mode: 'crop',
    width: 560,
    height: 550,
    quality: 80
} %}

<img src="{{ image.getUrl(crop) }}">

Once the transforms are generated for a page, it seems like changes to the focal point don't trigger a regeneration of the image transform. Altering the template code (eg. from quality: 80 to quality: 79) does trigger the regeneration of the image.

Is this expected behavior?


texts: How to create a border + border colour field on an image

texts:
My first question here... maybe one of a few! I've inherited a Craft project recently and don't have much experience with it.

I want to allow admin to set a border (and border color) whenever they add an image. Currently, the image field has a field type of Assets. I don't want to change the field type (to a Super Table or similar) because the component is used in so many other places - it would break.

We're using Craft 2 but upgrading to 3 presently.

Has anyone else had to do this before? Any suggestions on how to approach this? Let me know if I can clarify anything.


texts:
I've imported Wordpress comments into a post type called 'comments' in a section called 'interactions'. I have the slug stored in 'relatedPostSlug'.

How would I relate the 'relatedPostSlug' to the actual posts with that slug?


texts: Set fields from two different Matrix blocks, merge them and then set the output in a pretty way

texts:
Newbie here, still grappling with basics, let alone elegance. My aim is to pull content from four different fields held in two different Matrix blocks and pass the output in a nice human readable format to populate the meta-description tag in my layouts and elsewhere later on the entry page.
I'm getting close but still no beer. I'm having trouble with merging everything. Only one or the other MatrixHandles outputs the correct content:
{# Fetch MatrixBlock fields content for artistName and birthDeathLocationDate #}
{% set artistNameQuery = craft.matrixBlocks()
    .owner(entry)
    .field('artistNameBirthDeath')
    .type('artist') %}

{# Fetch MatrixBlock fields content for materials and dimensions #}
{% set artworkMaterialsQuery = craft.matrixBlocks()
    .owner(entry)
    .field('artworkDateMatDim')
    .type('artworkDetails') %}

{# Try to merge the two above queries, with some merge voodoo #}
{% set artNameMat = artistNameQuery|merge(artworkMaterialsQuery) %}

{# Don't know why but this helps trigger the below, and sends it to my base.twig layout tmp #}
{% set metaDescribe = '' %}

{# Print all of the above into a pretty, human/machine readable format for re-use in base.twig or elsewhere #}
{% for block in artNameMat %}
    {% set metaDescribe = block.artistName ~ ' ' ~ '(' ~ block.birthDeathLocationDate ~ ')' ~ ' ' ~ block.materials ~ ' ' ~  block.dimensions  %}
{% endfor %}

And then over in my base.twig template I've got:
<meta name="description" content="
{% if metaDescribe is defined %}{{ metaDescribe }}{% else %} no meta desc {% endif %}" />

So far it's outputting only the artistNameQuery. If I edit my not totally working merge line to just {% set artNameMat = artworkMaterialsQuery %}, it too sends the correct content for that Matrix handle/block to my base.twig.
Other notes. The above code is written within the template for displaying single artists' artwork (entry), outside of the {% block main %}. Running Craft 3.5.11.1.
Any pointers would be much appreciated!
Update:
I just tried making it all a lot more cleaner  / elegant replacing this:
{% set artistNameQuery = craft.matrixBlocks()
    .owner(entry)
    .field('artistNameBirthDeath')
    .type('artist') %}

{% set artworkMaterialsQuery = craft.matrixBlocks()
    .owner(entry)
    .field('artworkDateMatDim')
    .type('artworkDetails') %}

With this:
{% set artNameMat = entry.artistNameBirthDeath.type('artist').all()
    |merge(entry.artworkDateMatDim.type('artworkDetails').all())
%}

But I'm still getting only "one half" of the Matrix fields that I'm after.


texts: Commerce element query on custom field in console command

texts:
I'm on Craft 3.4.30 (latest 3.4) and Commerce 2.2.25 (latest 2.2):
My product type "ticket" has a custom date field with handle productStartDate.
E.g. the following query in TWIG works:
{% set products = craft.products().type('ticket').productStartDate('>= 2021-01-01 00:00:00').all() %}

I get nice results including my custom field productStartDate
I am trying the same in a console command with PHP:
use craft\commerce\elements\Product;
$product = Product::find()
                ->type('ticket')
                ->productStartDate('>= 2021-01-01 00:00:00')
                ->all();

Gives me this Exception:
Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: craft\behaviors\CustomFieldBehavior::productStartDate()'

in /myproject/vendor/yiisoft/yii2/base/BaseObject.php:222

Stack trace:
#0 /myproject/storage/runtime/compiled_classes/CustomFieldBehavior.php(542): yii\base\BaseObject->__call('productStartDat...', Array)
#1 [internal function]: craft\behaviors\CustomFieldBehavior->__call('productStartDat...', Array)
#2 /myproject/vendor/yiisoft/yii2/base/Component.php(297): call_user_func_array(Array, Array)
#3 /myproject/vendor/craftcms/cms/src/elements/db/ElementQuery.php(548): yii\base\Component->__call('productStartDat...', Array)
#4 /myproject/modules/console/controllers/WarmProductGroupsController.php(61): craft\elements\db\ElementQuery->__call('productStartDat...', Array)
#5 [internal function]: modules\console\controllers\WarmProductGroupsController->actionIndex(false)
#6 /myproject/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#7 /myproject/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#8 /myproject/vendor/yiisoft/yii2/console/Controller.php(164): yii\base\Controller->runAction('', Array)
#9 /myproject/vendor/yiisoft/yii2/base/Module.php(528): yii\console\Controller->runAction('', Array)
#10 /myproject/vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('theme/warm-prod...', Array)
#11 /myproject/vendor/craftcms/cms/src/console/Application.php(87): yii\console\Application->runAction('theme/warm-prod...', Array)
#12 /myproject/vendor/yiisoft/yii2/console/Application.php(147): craft\console\Application->runAction('theme/warm-prod...', Array)
#13 /myproject/vendor/yiisoft/yii2/base/Application.php(386): yii\console\Application->handleRequest(Object(craft\console\Request))
#14 /myproject/craft(22): yii\base\Application->run()
#15 {main}

Any hints why?


texts: Understanding migrations and CLI commands

texts:
Can someone please help explain some basics regarding migrations and the associated CLI commands to help troubleshoot when things fail? Specifically,
How does craft know which migrations have been applied and which are new?
I.e. Is it by comparing the craft_migrations table to the migration files found in '/vendor/craftcms/cms/src/migrations' folder (or plugin folders)?
Where does the information from running 'php craft migrate/new' and 'php craft migrate/history' come from? I ask because, when running php craft migrate/all and a migration fails, if I reload the previous DB and run migrate/new it says "No new migrations found", which is clearly wrong. Likewise running migrate/history displays "No migration has been done before." But when running migrate/all again it does attempt to run the migrations again. So clearly something is out of sync (or is terribly wrong in this project).
How are version numbers and migrations associated with each other? I.e. Is it simply based on whatever migration files happen to currently exist in the 'migrations' folder based on the last composer update?
What determines the order that migrations are run? I.e. Are they simply run alphabetically, based on the file names in the 'migrations' folder?
Finally, if a migration fails, is there something else that should be done besides restoring the DB to reset the craft state, before attempting to run migrate/all again?
Appreciate the help. Thanks.


texts: How to remove something from the slug/url

texts:
I got entries in the folder /cms/web/videos/ and the url display this: http://domainname.com/cms/web/videos/barco-auro.

I want it to be this: http://domainname.com/videos/barco-auro.

How do I create clean URLs? I don't find anything on this, or nothing that helps my problem.


texts: Retrieve entries on custom field date using ElementCriteriaModel

texts:
I am trying to retrieve an array of entries on a particular section where inspectionDate is greater than today's date. Here is the code.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'inspections';
$criteria->inspectionDate > '("now")';
$criteria->order = 'dateCreated asc';
$inspections = $criteria->find();

I am getting a Property "Craft\ElementCriteriaModel.inspectionDate" is not defined. error when trying to run this code.I have made sure that inspectionDate is the field handle and is also a date type.


texts: Is it possible to have an asset source pointing to a non public S3 bucket? Maybe also with expiring link urls?


texts: Keep on getting logged out when deploying using Capistano

texts: I keep on getting logged out whenever I deploy using Capistrano, despite the sessions being stored persistently (in the craft/storage folder).


texts:
I'm using the wonderful A&M form plugin to create a form on my site, and I have 3 dropdowns for the user's birthday: month, day, and year.  Currently, I have it set up so that when the form submits, those values get put into a matrix field when logged in the form submissions entry in the CMS.  I would prefer to have it put into a date/time field though, but I'm unsure how to do it.

This is the code in my form:

Birthday
<input type="hidden" name="fields[birthday][new1][type]" value="date">

    <select name="fields[birthday][new1][fields][month]">
        <option selected="selected" value="">M</option>
        {% for i in 1..12 %}
            <option value="{{ i }}">{{ i }}</option>
        {% endfor %}
    </select>
    <select name="fields[birthday][new1][fields][day]">
    <option selected="selected" value="">D</option>
        {% for i in 1..31 %}
            <option value="{{ i }}">{{ i }}</option>
        {% endfor %}
    </select>
    <select name="fields[birthday][new1][fields][year]">
        <option selected="selected" value="">Year</option>
        {% set startYear = now.year - 15 %}
        {% set endYear = now.year - 110 %}
        {% for i in startYear..endYear %}
            <option value="{{ i }}">{{ i }}</option>
        {% endfor %}
    </select>

In this case, "birthday" is my matrix field handle and "date" is the block type handle.  "month", "day", & "year" are obviously the field handles within the matrix field.

There's nothing in the docs. I understand a date/time field doesn't produce an object like a matrix field, but I can't think of a solution of how to convert it.


texts:
This code works as expected...

{% if submission.symptomCheckerSymptoms == "Itching" %}
    it works
{% endif %}

... but when when multiple options are selected, it doesn't.

The field is a checkbox group. What am I doing wrong?


texts:
Currently trying to load an asset located in the following branch of my install:

Craft

html

uploads

Unfortunately when I try to head directly to a specific asset I get the following error message from Craft:

You don't have permission to access /uploads/students/universities/giphy.gif on this server.
Server unable to read htaccess file, denying access to be safe

I've set the following on the uploads folder

chmod 774 /var/www/html/

My site is on DigitalOcean.

Any help would be brilliant


texts: How to Auto-generate a Title based on a multiple entries titles? (using a Entries field type)

texts:
I have two sections (both Channel type):

Releases
Movies

Releases have one Entries field type, the source is Movies
So, I want Auto-generate a Release title from Movies, like this: Titanic, Avatar, Toy Story
This works { movies.one().title } as a Title Format on the Releases Settings but display just the first movie: Titanic, the question is how can load all the entries titles? to get Titanic, Avatar, Toy Story as a title
I do a research and I get this: How can I set an entry title automatically, based on a related entry? but again that display only the first entry title.


texts: A plugin to validate a field depending on another field's value

texts:
I have an Assets field which I want to be required only if a separate Lightswitch field on the same Entry is 'on'. I'm currently trying to implement this with a simple plugin that creates a custom field type (along these lines).

However, in my Field Type's validation() method I can't work out how to access the Lightswitch field's value on this same Entry, in order see if it's 'on' or not.


texts:
I have a press release index page that loops through all the press releases. I want to organize them by year. So everything in 2018 will have a header that says 2018 press releases and then all the press releases for 2018 and so on.

Should I do a conditional that checks the date, or is there something like the | batch but for date? Open to ideas.


texts: Building an area for users to add content for Craft site

texts:
We're building our first project in Craft. It requires an area for users to submit events to the site, and the submissions will wait in an approval queue. We do not want these users to have access to the craft backend.

Also we are using Rackspace cloud hosting for images, and we would need the users to be able to submit their own photos to the site.

Are their any mechanisms in place in craft that we could leverage to keep plugin development to a minimum? I understand this is a broad question, but being our first Craft project I'm sure it has a lot of functionality we are not aware of and it would be a shame to recreate it just because we were unaware.


texts: I have setup a barebones install, and authenticated my bucket using the root user S3 credentials (just for now). Assets do not upload. I read a similar question here where the answer was that the response was being blocked by a firewall. I have tested on other connections and the issue wasn't resolved. Craft support suggested that I could edit some code on craft/app/lib/S3.PHP around line 771 but I'm not sure how to go about solving.


texts: I have a client that can't remember that save equals publish... is there a way to change the text from save to publish?


texts:
I was wondering if it's was possible to order section entries by random.

Example:

{% for entry in craft.entries.section('team').type('mainPeople').order('title random)) %}


texts: Using Craft CMS to manage content within an app

texts:
Has anyone used Craft to manage content within a Cordova/PhoneGap app?  How successful was it? What are the pitfalls?

We have an idea to create a website managed by Craft CMS.  We then want to "wrap" the website in Cordova/PhoneGap so we can make it available as an App. Our immediate questions:

• Is it possible?

• Is the App immediately updated as a website would be or are there further steps?

• Are there any issues to look out for?

Many thanks for any advice.

Martin


texts: Hide/show element actions dependent on tab

texts:
I have a custom element index with an element action to 'Approve' elements.
The element index has 'Live' and 'Staged' sources.
Where/how do I set it to only show this action on the 'staged' source OR just on a selection that contains an element that is not approved (latter probably better).
I've looked at the existing 'Delete' action and see that this uses a data attribute on the element index items 'data-deletable', how do I inject my own data attribute into the listing i.e. 'date-approvable'?


texts:
I have been working with data received from Guzzle and it is producing a Unicode String that looks similar to this Bachelor\u2019s Degree (after some parsing). When I save other content within craft through craft()->entries->saveEntry( $entry ) The unicode items are converted to their appropriate characters. However, when I use this in the ElementCriteriaModel searches, it does not work because it is using the literal Bachelor\u2019s Degree. It does work when I hard code Bachelor's Degree so the lookup code is functional. Also, I tried all of the StringHelper static functions and have done tons of iterations of mb_convert_encoding( 'Bachelor\u2019s Degree', 'HTML-ENTITIES', 'utf-8' ), htmlspecialchars, and htmlentities, but it has not produced a good result. Here is the code I am using for the query just in case:

$criteria = craft()->elements->getCriteria( ElementType::Category );
$criteria->title = $job[ 'eduReq' ];
$eduReq = $criteria->first();

Do you all know how to convert this string correctly so that the ElementCriteriaModel uses Bachelor's Degree?


texts: Fetch locale entries does not work in Live Preview

texts:
I need to display booth local and localized entries in the same page.
So I fetch the different localized entries like this :

{% set localeEntry = craft.entries.id(myEntry.id).site('default').one() %} {# get the locale data #}
{% set enEntry = craft.entries.id(myEntry.id).site('en').one() %} {# get the english data #}

This works perfectly when the page is displaying in the browser, but the variables return empty when the page is displaying in the Craft CP's Live Preview panel.


texts: Craft multisite site without www redirects unwanted to default site

texts:
I'm working on a multisite Craft CMS 3 website. When I'll go to www.site-a.com (default) and www.site-b.com this works fine. The correct sites and templates are displayed. But if I'll go to site-b.com (without www) I'll redirected to www.site-a.com. The sites are not multilangual and doesn't have a seperated webroot. I'll point the domains to the same webroot. This is how I'll set it up in the general config:

   'production' => [
        'env'                   => 'production',
        'siteUrl'               => array(
            'default'           => 'https://www.site-a.com/',
            'second'            => 'https://www.site-b.com/'
        ),
    ],

In my htaccess I'll force to use to the www domain, like this:

    # -----------------------
    # Force www
    # -----------------------
    RewriteCond %{SERVER_ADMIN} !^dev$
    RewriteCond %{HTTP_HOST} !^localhost$
    RewriteRule ^(.*)$ https://www.{HTTP_HOST}.com/$1 [L,R=301,NC]

What I'll do wrong?


texts: P&T Contact Form Plugin: HTML Email Templates

texts: Can you create HTML templates using Twig/Craft tags to style the body of the email message sent by the P&T contact form plugin?


texts:
My client prefers to use a Microsoft IIS hosting environment he already has. After some gnashing of teeth I have managed to get it working there, but it is painfully slow (unlike my local LAMP version).

I was inclined to assume some sort of shared server MySQL bottleneck but the host's response to this thought has been…

  I don't see any bottlenecks on the server itself, mysql connections to the server and queries on it are running very quickly so I would be looking at the code itself. I've done some tests with simple php + mysql connections on the server and these run very fast, so this is pointing at the CMS doing something slowly, but I'm not familiar with the CMS to know what this is.

Does anyone have experience of Craft running well in IIS on a shared server?

Is there any particular config that is worth trying to get it to do so?


texts: Adjust the config to change the order of the formatting menu in Redactor II

texts:
I'm trying to adjust the order of the options in the formatting dropdown menu in the Redactor ii fieldtype but it's not picking up my changes. I have made other changes in this config that have been picked up and working, just not this one.

See below for my Standard.json config file.

{
    buttons: ['format','bold','italic','lists','link','file','image','video'],
    plugins: ['fullscreen','video','table','source'],
    formatting: ['h3', 'p', 'blockquote', 'pre', 'h1', 'h2', 'h4', 'h5'],
    toolbarFixed: true
}


texts: When browsing the assets, there is a "Temporary Uploads" folder. What is it for? Can I disable/hide it?


texts: Live Preview not working - showing home page instead

texts:
I've got a Structure entry, enabled, but Live Preview (or just viewing the page on the public site) shows the home page instead.

Might I have a setting incorrect?

Edit: It looks like previewing any entry shows me the home page.


texts:
My problem is that the Mailer plugin (version 0.5) does not work with Craft Pro 2.3.2620. Unfortunately, I get no error message - it still does not send e-mail (the log is empty). Craft in general is able to send e-mails.

Has someone else the same problem?


texts: Craft 2: Is there a hook for Craft Commerce Orders admin page?

texts:
My plugin is sort of an extension for the Craft Commerce, where I need to provide custom data on the craft commerce orders page.
So I'm wondering is there a way to listen for an event, which fires when an admin navigates to the Orders page?
Thanks.


texts: How do I output image in the loop for an entry?

texts:
I've run into an unexpected situation, where ElementCriteriaModel could not be converted to string.

{% set news = craft.entries.section('news').limit(3) %}
{% for news in news %}
    {% set cover = news.promotionNewsImage %}
    {% if cover|length %}
        {{ cover.getUrl('gtLg') }}
    {% endif %}
{% endfor %}

Any thoughts on that please?


texts: Is there any "Upload Image" custom field in craft so that I will be able to make my images editable. Thanks for the answer.


texts:
I'm looking to add some additional functionality to the user registration process. Basically, we will be creating "access codes" that can be used N number of times during registration. Once N users have signed up using that code, the plugin that I'm writing will prevent additional users from registering on the site.

Right now, I'm having trouble determining how to add errors to the users.onBeforeSaveUser event. My plugin checks availability of the access code that was submitted during the registration process, and I'd like to prevent Craft from saving the user if the code isn't valid/enabled. Here's what the code looks like:

<?php

namespace Craft;

class GatekeeperPlugin extends BasePlugin
{

  ...

  function init()
  {

    craft()->on('users.onBeforeSaveUser', function(Event $event) {

      // The user that's about to be saved
      $user = $event->params['user'];

      // Determine if an access code was submitted
      $accessCodeUsed = isset($user->contentFromPost['accessCodeUsed']) ? $user->contentFromPost['accessCodeUsed'] : false ;

      // If there was an access code submitted...
      if ($accessCodeUsed)
      {

        // Look for it in the database
        $queryAccessCode = craft()->db->createCommand()
          ->select('id, field_code, field_limit, field_timesUsed')
          ->from('content')
          ->where(array('field_code' => $accessCodeUsed))
          ->limit('1')
          ->queryRow();

        // If the code was found...
        if($queryAccessCode)
        {

          ...Do some stuff

        }

        // If the code wasn't found...
        else
        {

          // Prevent Craft from saving the user
          // Add error "Sorry, that code is not valid."

        }

      }

    });

  }

}

It appears that error messages can only be added to models, but I'm working with an event here. The event has a user model within it, but trying to add errors to it (e.g. $event->params['user']->addErrors([array of errors])) hasn't worked for me. Any pointers, here?


texts: How do I pass variables to loops within includes?

texts:
How do I pass variables to a loop within an include?

This is my partial:

{% for photo in photos %}
    <img src="{{ photo.projectPhotos_photo_image.first().getUrl('projectThumbnail') }}"
{% endfor %}

I'm calling it from a template with this:

{% set projectEntries = craft.entries({
    section: 'project'
}) %}
{% set vars = {
    photos: projectEntries
    }
%}
{% include "_partials/photo-tile.html" with vars %}

All well and good

but

What if I want to abstract this from my partial:

src="{{ photo.projectPhotos_photo_image.first().getUrl('projectThumbnail') }}"

In other words, I'd like to pass the src, {{ photo.projectPhotos_photo_image.first().getUrl('projectThumbnail') }} , into the partial but I don't know how!

If I try to do it from the template like this (through photoSrc), it fails, saying the 'photo' is undefined:

{% set vars = {
    section: "category",
    category: category,
    pageOneTitle:  categoryTitle,
    photos: projectEntries,
    photoSrc: photo.projectPhotos_photo_image.first().getUrl('projectThumbnail')
    }
%}

Any tips?


texts:
We are having issues staying logged in to Craft (2.6). There was a plugin error which is what we thought was causing the issues, so we removed the sprout SEO plugin. However the error still persists. We keep getting kicked out, and sometimes the words 'unkown error' pop up. We have not bee able to load any new content due to this.

Please may you assist us urgently.

Thanks you so much,
Ashton


texts: Refer to specific section handle when querying an element by 'getCriteria'

texts:
I can do the following to pull out the page title after parsing in just the page slug:

$page = 'about';
$entry = craft()->elements->getCriteria(ElementType::Entry)->first();
$entry->slug = $page;
echo $entry->title;

(I understand this is overkill, but an answer to this question will help me answer further questions I dare not try to explain here).

The problem is, the slug doesn't need to be unique if other sections/channels/singles use the same name, and the method above only calls out the first instance of "about".

How can I define what section is being referred to?

This will update the handle, but has no effect on the output:

$entry->section->handle = "pages";

This returns a Read Only error:

$entry->section = "Pages"

  Property "Craft\EntryModel.section" is read only.


texts:
I've installed a ssl cert on a site and it's working. Now I want to redirect visitors coming in on http over to https

I've put this code and only this code in the htaccess file, but it's causing a redirect loop.

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.mysite.com/$1 [R,L]

</IfModule>

My original htaccess looked like this:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_HOST} ^mysite.com [NC]
RewriteRule ^(.*)$ https://www.mysite.com/$1 [L,R=301]

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

Could Craft somehow be causing the redirect loop?

In the Craft CP I have the Site URL set to https://www.mysite.com


texts:
Using the Element API, I want to return the values from checkboxes (the $block->product field). These checkboxes are within a matrix that I am already gathering data from. Currently am doing this:

return [
'endpoints' => [
    'fullmembers.json' => [
        'elementType' => 'User',
        'criteria' => ['group' => 'fullMembership'],
        'transformer' => function(UserModel $member) {
            $businessCategories = [];
            foreach ($member->businessTypeMarketSectorsProducts as $block) {
                switch ($block->type->handle) {
                    case 'businessCategory':

                        $businessCategories[] = [
                            'businessType' => $block->businessType->value,
                            'marketSector' => $block->marketSector->value,
                            'product' => $block->product //Here you can see I'm calling the product field...
                        ];
                        break;
                }
            }

            return [
                'id' => $member->id,
                'companyName' => $member->membersCompanyName,
                'addressLine3' => $member->membersAddressLine3,
                'lat' => $member->memberAddress->lat,
                'lng' => $member->memberAddress->lng,
                'email' => $member->email,
                // 'profile' => '/directory/company/' . $member->id . '/' . $member->username,
                'profile' => UrlHelper::getUrl("directory/company/{$member->id}"),
                'businessCategories' => $businessCategories
            ];
        },
    ]
]
];

Here is a sample response:

    {
  "id": "1506",
  "companyName": "Airsprung Group Plc",
  "addressLine3": "",
  "lat": "51.33188454",
  "lng": "-2.20657303",
  "email": "email@email.co.uk",
  "profile": "http:\/\/craft.fira\/directory\/company\/1506",
  "businessCategories": [{
    "businessType": "Manufacture",
    "marketSector": "Domestic",
    "product": {
      "0": {
        "label": "Beds",
        "value": "Beds",
        "selected": true
      },
      "1": {
        "label": "Mattresses",
        "value": "Mattresses",
        "selected": true
      },
      "2": {
        "label": "Seating \/ upholstery",
        "value": "Seating \/ upholstery",
        "selected": true
      }
    }
  }, {
    "businessType": "Manufacture",
    "marketSector": "Contract",
    "product": {
      "0": {
        "label": "Beds",
        "value": "Beds",
        "selected": true
      },
      "1": {
        "label": "Mattresses",
        "value": "Mattresses",
        "selected": true
      },
      "2": {
        "label": "Seating \/ upholstery",
        "value": "Seating \/ upholstery",
        "selected": true
      }
    }
  }]
}

I would like the response to just show the values of the product checkboxes. Can you suggest a way to do this so that I am not returning the label and selected states? Ideally something like this:

"product": {"Beds", "Mattresses", "Seating \/ upholstery"}


texts: Getting assets from an entry programatically

texts:
I want to get the id of an asset I've set for a feature image on an entry.
To find the entry I'm using the slug as the criteria like so:
$entry = Entry::find()
  ->slug('0002')
  ->one();

In the returned object I'm expecting to see an array somewhere for custom field values listing the asset Id's, but it's drawing a blank
[_behaviors:yii\base\Component:private] => Array
        (
            [customFields] => craft\behaviors\CustomFieldBehavior Object
                (
                    [hasMethods] =>
                    [summary] =>
                    [featureImage] =>
                    [geopolygon] => [{"col1":"11","col2":"22"},{"col1":"11","col2":"2"},{"col1":"3","col2":"2"},{"col1":"","col2":""}]
                    [_customFieldValues:craft\behaviors\CustomFieldBehavior:private] => Array
                        (
                        )

                    [owner] => craft\elements\Entry Object
 *RECURSION*
                    [_attachedEvents:yii\base\Behavior:private] => Array
                        (
                        )

                )

        )

I know this entry does have a featureImage because it shows up in the admin and I can also view it on the frontend. I can also see all other custom values I've saved for the entry. What am I missing here?


texts: How can I 'Parse' { entry.belongsTo } to array with users?

texts:
From my plugin, I know I can use ...

craft()->templates->renderObjectTemplate($string, $entry)

... to parse, for example, { belongsTo.first.fullName } to the full name of the first user in the belongsTo field.

Now, I need an easy way to parse { belongsTo.find } into an array with all users related to this belongsTo field. Is there an easy way to do this, or should I let my plugin do the work?

Background information

My custom notification plugin has a settings field where I can set the 'receivers' of a notification. If an entry has a user field called 'belongsTo', and the setting is { belongsTo.find }, I need all the users related to this field, so I can further process the notification.


texts: How can I display second level children only from a specific parent structure item?

texts:
I'm trying to display a list of child structure links, but only from a specific parent. The template I'm working on isn't for the parent in question so I don't think I can use 'entry.'

My structure is set up like this

Parent 1
--Child One
--Child Two
--Child Three
Parent 2
--Child One
--Child Two

I only want to display the children of Parent 1. What I have so far is

{% set pages = craft.entries.section('visit').level('>1') %}
{% nav entry in pages %}

{{ entry.title }}
    {% ifchildren %}

           {% children %}

     {% endifchildren %}

{% endnav %}

Using this outputs all of the second level children instead of just the children from Parent 1. Is there any way to specify that the only children I want to display must come from Parent 1? Can I specify a slug somehow?

Any help much appreciated


texts: Additional code to run when cache is busted(entry added/updated, etc)

texts:
I'm using Craft Pro 3.6 in Headless mode.  I've found that caching the GraphQL responses on the frontend server dramatically speeds up our load time, even with enableGraphQlCaching turned on.
What I'd like to do is have Craft make a cUrl request to an endpoint on our frontend server whenever an entry is published or updated(or whenever the cache busting script would normally run) to clear the frontend cache.
I'm guessing the best approach would be a custom plugin?  However, if there's an easier way to do this I'm all ears.
Thanks for your time.


texts: Craft Commerce: make address phone telephone field required without JavaScript

texts:
Because I used a similar address model to the one supplied in the Craft Commerce templates, which essentially uses the same form partials for both address and billing, and also hides and shows the form using JavaScript, I can't use HTML required attributes.

Is there an easy way to add in the config files a way to make 'shipping.phone' required and return an error in the same way the default required fields work?

Contact details

        <input type="text" id="{{ modelName }}-phone" class="u-full-width" name="{{ modelName }}[phone]" value="{{ model ? model.phone : '' }}">

        Telephone number
        {% if model and model.hasErrors('phone') %}{{ model.getError('phone') }}{% else %}Required{% endif %}

In case we need to contact you about important details regarding your order.


texts: How do I fix a deprecation error for DateTime::year?

texts:
I am trying to work through deprecation warning. I have not touched Craft in a few months, so I am a bit rusty.

The Deprecation Message is:

  DateTime::year is deprecated. Use the |date('Y') filter instead.

The offending line is:

  {% for year in now.year .. firstEntryEver.postDate.year %}

Here is the context:

{% set firstEntryEver = craft.entries.section('posts').orderBy('postDate asc').one() %}
{% for year in now.year .. firstEntryEver.postDate.year %}

 date_range {{ year }}
 {% endfor %}

So, how do I fix this?


texts: Craft 3.6 Upgrade errors - can only install one of yiisoft/yii2 (and other errors)

texts:
I'm new to Craft so maybe I'm doing something dumb, but I can't get past this error screen when trying to update to 3.6:
Composer output: Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Can only install one of: yiisoft/yii2[2.0.38, 2.0.40].
- Can only install one of: yiisoft/yii2[2.0.40, 2.0.38].
- craftcms/cms 3.6.5.1 requires yiisoft/yii2 ~2.0.40.0 -> satisfiable by yiisoft/yii2[2.0.40].
- Installation request for craftcms/cms 3.6.5.1 -> satisfiable by craftcms/cms[3.6.5.1].
- Installation request for yiisoft/yii2 (installed at 2.0.38) -> satisfiable by yiisoft/yii2[2.0.38].

Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.

I deleted the composer.lock file based on some threads I found here, and I tried running composer update from the terminal and it did reduce a much longer error message down to this one, but still no joy.
I'm developing locally on MAMP, 3.5.x was running great.
My composer.json:
{
  "require": {
    "craftcms/cms": "3.5.18",
    "craftcms/contact-form": "2.2.7",
    "craftcms/feed-me": "4.3.4",
    "craftcms/mailgun": "1.4.3",
    "craftcms/redactor": "2.8.5",
    "vlucas/phpdotenv": "^3.4.0"
  },
  "require-dev": {
    "yiisoft/yii2-shell": "^2.0.3"
  },
  "autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },
  "config": {
    "sort-packages": true,
    "optimize-autoloader": true,
    "platform": {
      "php": "7.2.5"
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ]
  }
}


texts: Craft 3 entry.author.getPhoto() is coming up null on template, but the author has a photo uploaded in the user > details section, any ideas why?

texts:
The site is utilizing a Servd bucket to store all assets. The backend shows a photo successfully uploaded to the user > details section, but does not provide a url in the entry.author.getPhoto(), it comes up null. The photoId is also null (screenshots from the {% dd entry.author %} is provided below). Has anyone had this problem before and how did you solve it? I've tried other iterations including entry.getAuthor().getPhoto(), entry.author.photo. I've even used the author id to query for the user object and the photo is null there too. The photo is showing under custom fields on the dump, is there some alternative way I need to grab the photo on the template?
Any help would be greatly appreciated, thank you.


texts: Is it possible to pass metadata to Stripe from Craft Commerce

texts:
With Craft 3 and Craft Commerce 2 with the P&T Stripe gateway is it possible to pass metadata to Stripe? I've tried various combinations of hidden fields but without success so far.

I was hoping something like this on the payment form might work.

<input type="hidden" name="metadata[foo]" value="bar">


texts: Craft plugin for input fields on the front end to check existing user

texts:
I am trying to create a functionality in Craft where the user enter an email and the system is able to tell the user if the user exists or not similar to the attached screen:

I am very new to plugin development, and I am not even sure if I need one, I found this post, which looks very helpful, only thing is I really don't know how to implement it.
How to tell if user exists

Should I develop a plugin? And I don't understand the information on plugin website and I can't find an example where there is an input field on the front end.


texts: Craft 3: how can I set an ordered list of all sites, and set a display name different from the site name?

texts:
The Craft 3 multi-sites is very useful. However, I found the list dropdown while editing an entry confusing and awkward in my case.

I have several sites group, each containing a localized version of the site version:

- International Sales
    - English version
- Production
    - English version
    - French version
— Distribution
    - English version
    - French version

I could have set the sites group like this, to get the right display name when looping on each sites (using craft.app.sites.getAllSites()):

- International Sales
    - International Sales
- Production
    - Production
    - Production
— Distribution
    - French Distribution
    - Distribution France

But as you can see, there's almost nothing that inform the user which site version is using which locale, when editing the sites from the CP's dropdown.

So I had to change each name by something like this:

- International Sales
    - International Sales → English
- Production
    - Production → English
    - Production → French
— Distribution
    - Distribution France → English
    - Distribution France → French

Now I'm facing two problems:

How can I set an ordered list of all sites using Twig?
Because
craft.app.sites.getAllSites() loop through sites using an
alphabetical order, like in the CP. For example, I would like the
Distribution group displayed before the Production group.
How can I set a display name different from the site name? Because
International Sales → English, Production → English, etc. are ugly names, only for visual reference in the CP. I would like to
display their names like in the second version of the list:
International Sales, French Distribution, etc.


texts: Show Entries based on content in a Matrix Field

texts:
I have a product with a variant matrix field(productVariants). Inside each variant is the option to supply a sale price (salePrice).

On the front end, I'm trying to show a product grid of only products that are on sale. Sounds simple, but I can't for the life of me figure out the syntax.

Here's where I'm at so far using matrixBlock queries. A few things I am not clear on:

owner - what is the owner? Docs only say myEntry and I'm not on a page or in a loop to get the entry that the matrix field is a part of
fieldId - is this the matrix field ID or the ID of the text field with the value I'm searching for?
How do I target salePrice in the search syntax since it's one of the fields inside the Matrix field?

{% set myMatrixBlockQuery = craft.matrixBlocks.owner(myEntry).fieldId(33).type('text').search('salePrice:*') %}

{% set saleEntries = myMatrixBlockQuery.all() %}

{% for product in saleEntries %}
{{ product.title }}, etc...
{% endfor %}

I've spent a couple of hours in StackExchange and in the Craft docs and still can't wrap my head around the syntax for this situation so I appreciate your help!


texts: Image in entry only showing when using entry.image instead of entry.assetFieldHandle

texts:
I discovered that I can replace:

{% for asset in entry.assetFieldHandle %}
    {{ asset.url }} -- {{ asset.width }} -- {{ asset.height }}
{% endfor %}

From assetFieldHandle to the name of the handle ... then it works.
But why not with entry.assetFieldHandle?

{% for asset in entry.image %}
    {{ asset.url }} -- {{ asset.width }} -- {{ asset.height }}
{% endfor %}


texts: When posting entries, how do I post tags as well as the title and url?

texts:
I'm trying to create a post where in the entry loop I can also post tags.

TITLE
   TAGS

But in my current understanding there's no way to get the post's tags where I'd assume it would be something like entry.tags


texts: Push/Add asset to Entry by asset filename

texts:
I have spreadsheet that i'm parsing and I have available to me a Entry ID and the Asset filename. Can I add the asset to the entry by the filename?

Im targeting the product entry with:

$product = Entry::find()->section('products')->id($data[3]);
$productImages = ($product->productImages) ? $product->productImages : array();
$name = explode('?', basename($data[2]));
$pushImageId = Asset::find()->filename($name[0])->id; // $name[0] = myfilename.jpg
$productImages = array_push($productImages,$pushImageId);
$product->productImages($productImages);
Craft::$app->elements->saveElement($product);

The handle for the asset field is:
productImages

So when I run this i get this error:

Exception: Argument 1 passed to craft\services\Elements::saveElement() must implement interface craft\base\ElementInterface, instance of craft\elements\db\EntryQuery given

Thanks!

Solution

Based on the answer from robin in this question How to save Asset field of an Entry programmatically in Craft 3

It you just need to attach the asset ID's as an array. So i re-wrote the following code to create a new array of the original asset ids plus the new one. And it worked!

$product = Entry::find()->section('products')->id($data[3])->one();
$name = explode('?', basename($data[2]));
$pushImageIds = Asset::find()->filename($name[0])->ids(); // $name[0] = myfilename.jpg
$newProductImagesArray = array();
foreach($product->productImages as $image){
    array_push($newProductImagesArray,$image->id);
}
array_push($newProductImagesArray,$pushImageIds[0]);

$product->setFieldValue('productImages',$newProductImagesArray);
Craft::$app->getElements()->saveElement($product);


texts:
I am using a 3rd party service to run the image processing so I do not need full URL's for the images. I just need it to spit out the relative path name of the asset, not the absolute URL. I seem to be able to get either the asset.folder or the asset.filename but not both.

{% if entry.homepageImage|length %}
{% set asset = entry.homepageImage.first() %}
  <img ix-path="{{ asset.filename }}" alt="Test Image">
{% endif %}

I did try including the folder when setting the asset but that didn't work either, plus seems quite convoluted for something relatively simple.

{% set asset = entry.homepageImage.folderId(2).first() %}


texts:
When I view the browser console whilst viewing the Dashboard for instance, I get a whole load of 404s for Javascript .map files. For example on a fresh update to v2.3 I get this lot reported as missing:

/admin/resources/lib/garnish-0.1.min.js/garnish-0.1.min.map/
/admin/resources/js/craft.js/craft.min.map/
/admin/resources/js/cp.js/cp.min.map/
/admin/resources/js/QuickPostWidget.js/QuickPostWidget.min.map/
/admin/resources/js/RecentEntriesWidget.js/RecentEntriesWidget.min.map/
/admin/resources/js/GetHelpWidget.js/GetHelpWidget.min.map/
/admin/resources/js/UpdatesWidget.js/UpdatesWidget.min.map/
/admin/resources/js/FeedWidget.js/FeedWidget.min.map/

It just looks like the paths a wrong, if I look in the /js/ folder, the .map files do actually exist.

Is it something I should be concerned about? Everything seems like it's all working ok, so it's not a show stopper at all. I just find it a bit annoying to be honest, so if I can do something to turn off the requests that'd be nice.

EDIT: Solution

As per Jason's answer below, I had the following rule in my .htaccess file to add trailing slashes:

RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+[^/])$ /$1/ [R=301,L]

I removed that and it has cured the issue. I have subsequently put the rule back in and the problem hasn't returned so it must have been cached somewhere.


texts:
Is there a way to update the cart using ajax?

I've tried something like:

$('span.quick-cart-add>p>a').click(function(e){

    e.preventDefault();

    var data                    = {};
    data["purchasableId"]       = $(this).data("id");
    data["qty"]                 = $(this).data("qty");
    data[window.csrfTokenName]  = window.csrfTokenValue;

    $.post( "/actions/commerce/cart/updateCart", data, function(response) {

        alert( "success" );

    }).always(function(response) { console.log(data, response); });

});

I've tried passing "lineItemId" instead of "purchasableId", and also sending to "/actions/commerce/cart/updateLineItem", they all return response.success but the cart is never actually updated.

Am I not sending the right amount of fields/values, or is there something I'm missing when trying to accomplish this via ajax?


texts:
I would like to fetch all entries in a section according to a Lightswitch value inside of a matrix field. Initially I tried:

craft.entries.section('buildings').spaces.space.isAvailable('1').find

but this doesn't pull any results. Is this even possible in a single query? Or do I need to get all entries from the section first, and then loop over them in order to determine if the Lightswitch has the desired value?


texts: Going from a static site generator (Jekyll or Hugo) to Craft CMS; Export/migrations options?

texts:
I currently have a website that's been built using a static site generator (SSG; in this case, Hugo). The site has about 10 sections, each with 40-50 markdown files. As is the case with most content built out using an SSG, the content files are all well structured and include embedded metadata (via YAML front matter) at the top of each content .md file.

The front matter is very well structured and includes the following fields across all article files:

title:
subtitle:
description:
tags:
categories:

There is also a staff/person content type with the usual fields:

name_first:
name_last:
job_title:
reports_to:
Etc...

With Hugo (or just some clever BASH scripting), I can easily template these into a CSV (or multiple CSVs), JSON, etc. I know there are obvious differences between flat files/serialized data and an RDBMS, but I'm wondering if there is a clever way for me to make all of this content easily importable for Craft CMS 3, which our company is hoping to use for a major replatforming in about 3-4 months.

The entire site actually has close to 650 pages, but I figure I can start structuring them in markdown with YAML first to avoid a prolonged copy-and-paste nightmare. (Our current "CMS" is not a CMS by any means and doesn't contains any metadata.) I can parse the content out as very clean HTML, plain text, etc.

Any thoughts, first steps, suggestions, etc would be extremely appreciated. Thanks!


texts: Timout on Entry Save if using Categories

texts:
I can't use "Categories" in Craft CMS, after hitting "Save" for an entry with Categories set, the page will take ~5minutes to load and typically time out. Usually, it does save the page and update the categories -- however, this is just not practical moving forward. The entire Craft site is unable until it finally times out the save.

Has anyone encountered this and have any idea what's going on?

I've tried deleting the Categories and creating new ones etc. It happens everytime when saving an entry with categories set. Is it possible that devMode being enable is causing an issue? (See error below)

I get the following error:

CDbException

CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away. The SQL statement executed was: SELECT *
FROM `craft_info` LIMIT 1

With the following highlighted error line:

  if (!$this->config->get('devMode') || (craft()->isInstalled() && !$this->userSession->shouldExtendSession()))

EDIT:

Turning off DevMode stopped the issue. However it still sounds like from the errors above that this isn't good. Hoping to hear some insight!


texts: List entries related to several categories

texts:
This is the code used to display entries related to categories.

The issue: if an entry belongs to 2 categories, it displays all the categories to which it belongs on the page.

I need Craft to display only the category and entries the (lastSeg) of the slug (selected from a nav).

Can't find where to start?

{% set entries = craft.entries.section('contenuCompositions').relatedTo(category).order('dateYear','comp_opus','title').limit(0) %}
{% for category in craft.categories.group('compositions').relatedTo(entries).level(2).slug(lastSeg) %}

{{ category }}

{% for row in entries.relatedTo(category)|batch(3) %}

    {% for entry in row %}

{{ entry.title }}

    {% endfor %}

{% endfor %}


texts: How can I filter selected/related entries by their categories?

texts:
I have a section called "Events" and an Entries field, we'll call myEntriesField to select related entries from another channel called "Exhibitors"

On the Events page, I need to display the related Exhibitors grouped by their categories. And if there are no related Exhibitors in said Event, I need to hide the surrounding html that displays the category title etc.

I have this in my template:

        {% set theListings = entry.myEntriesField %}

        {% set thisCategory =
             theListings.relatedTo(craft.categories.slug('the-category-i-need'))
        %}

        {% if thisCategory | length %}

Category Title

            {% for theEntry in thisCategory %}

{{ theEntry.title }}

                    ...more entry data stuff...

            {% endfor %}

        {% endif %}

        {% set thisOtherCategory =
             theListings.relatedTo(craft.categories.slug('the-next-category-i-need'))
        %}

        {% if thisOtherCategory | length %}

Category Title

            {% for otherEntry in thisOtherCategory %}

{{ otherEntry.title }}

                    ...more entry data stuff...

            {% endfor %}

        {% endif %}

But this displaying ALL Exhibitors, grouped by their categories, rather than just the related Exhibitors selected in the Event entry.

Any ideas what I am missing here?


texts: How to prevent inconsistent comments in generated project config YAML files

texts:
We're using Project Config to enable a decentralised, git-based workflow. One issue we have is that sometimes the generated YAML files will include a specific comment, and sometimes it won't. In particular, in the /config/project/sections/ files, the YAML files for each section have a siteSettings key, with a list of settings per site (currently we're working only with a single site). Now the line with the UUID of the site will sometimes include a comment with the site name, and sometimes it won't. Here's a diff showing the difference:
--- a/config/project/sections/home--12b67b1c-1077-4a7a-8312-c1cba1234567.yaml
+++ b/config/project/sections/home--12b67b1c-1077-4a7a-8312-c1cba1234567.yaml
@@ -3,7 +3,7 @@ handle: home
 name: Home
 propagationMethod: all
 siteSettings:
-  649a64c1-52f1-4463-8a03-bc84c1234567:
+  649a64c1-52f1-4463-8a03-bc84c1234567: # NameOfTheSite
     enabledByDefault: true
     hasUrls: true
     template: entries/home

We want to prevent this from cluttering up our commits. Of course, we can just not commit those files and/or reset them manually, but keeping track of that manually is a bit tedious. I haven't been able to find out why the comment is sometimes there and sometimes it isn't. Sometimes after creating some new fields, sections or similar all YAML files in config/project/sections will show up as changed in git status, and I don't know when they got overwritten. Maybe it's got to do with whether the site name is defined or not? Though that hasn't changed at least on my machine.
Anyway, is there a way to either prevent Craft from including those comments when generating YAML files, OR have them be consistent? Of course, if the comment depends on the local name of the site, that would result in a lot of unnecessary changes if multiple people use a different site name in their local development environment.
I'm open to other solutions. The main problem is that it's cluttering up our commits and it's annoying to manage manually when commiting. Any insight would be appreciated. Thanks!


texts: How do I select entries that have a particular block type?

texts:
Say I have a channel with a matrix field which has two block types - text and video. Is there any way to select all entries in that channel that have a video block?

Idea 1

Use the Low Blocks plugin to query all video block types, then get their owner IDs, then use those to grab the entries.

Idea 2

Add a light switch field to the channel called "hasVideo". Update this field programmatically using the onSave event and a plugin. Then I can select all entries if hasVideo is true.

Is there a better way I'm missing?


texts: Can plugin copy file into an asset source?

texts:
I have a plugin and I want it to move some files into a system asset source.

I have a dropdown to select the folder which gets its options like this and shows a dropdown to select a folder Id.

public function getSettingsHtml()
{
      $sourceIds = craft()->assetSources->getAllSourceIds();
      $tree = craft()->assets->getFolderTreeBySourceIds($sourceIds);

      return craft()->templates->render('backups/_settings', array(
          'settings' => $this->getSettings(),
          'tree' => $tree
      ));
}

so in my controller what i want to do is copy a file into that folder?  I have the full path to the file but not sure where to go from there?  Ideally it wouldn't matter if it were local storage or cloud storage it would just move it but I'm a little dumbfounded?

Any thoughts?

UPDATE: So I found this method in the Assets Service insertFileByLocalPath() which seems exactly what i needed

$response = craft()->assets->insertFileByLocalPath($backupsPath, $fileName, $folderId);

which starts to work but i keep getting S3::putObject(): [RequestTimeout] Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed.??


texts:
I've been asked to export some data from an old EEv2 site into a Craft site. I thought I should be able to export the data from EE into CSV or XML and then use FeedMe to import it.
But one of the fields on the EE site was using Content Elements which is similar to Matrix or the EE Fluid field.
So before I convert that data into a format that is compatible with EE6, I need to know what format it should be in to get it into Craft.
The Content Elements field was made of headings, an Assets field, a pill field which set alignment for the image, and a Wygwam (RTE) field.
Is the best option to set this up as a Matrix field in EE? Or would I be better using a Fluid field?
Also, has anyone done any exports from EE to Craft using Smart Export which involved Matrix fields in Craft? If so, any things to look out for?


texts: Getting started with Order Adjuster plugin

texts:
Starting with the Business Logic plugin from https://github.com/lindseydiloreto/craft-businesslogic I'm following 3 for 2 etc with Craft Commerce to get started.

I have my main plugin file containing:

<?php
namespace Craft;
require_once('Adjusters/BusinessLogic_TaxRemover.php');

class BusinessLogicPlugin extends BasePlugin
{

    public function getName()
    {
        return 'BusinessLogic';
    }

    public function getDescription()
    {
        return '';
    }

    public function getVersion()
    {
        return '1.0.0';
    }

    public function getDeveloper()
    {
        return craft()->getSiteName();
    }

    public function getDeveloperUrl()
    {
        return '';
    }

    public function init()
    {
    }

    public function commerce_registerOrderAdjusters(){

        return [

            new Commerce_TaxAdjuster

        ];
    }

}

And within Adjusters/BusinessLogic_TaxRemover.php I have:

<?php

namespace Commerce\Adjusters;
use Craft\Commerce_LineItemModel;
use Craft\Commerce_OrderAdjustmentModel;
use Craft\Commerce_OrderModel;

class BusinessLogic_TaxRemover implements Commerce_AdjusterInterface {

    public function adjust(Commerce_OrderModel &$order, array $lineItems = []){

        $myAdjuster = new Commerce_OrderAdjustmentModel();

        $order->baseDiscount = $order->baseDiscount - 5;

        $myAdjuster->type = "Test";
        $myAdjuster->name = "Test Adjuster";
        $myAdjuster->description = "Takes $5 off the order";
        $myAdjuster->amount = -5.0;
        $myAdjuster->orderId = $order->id;

        //if your Adjuster affects lineItems rather than the total, you record the ids here
        $myAdjuster->optionsJson = ['lineItemsAffected'=>null];
        $myAdjuster->included = false;

        return [$myAdjuster];

    }

}

But whenever doing anything to the cart, I just get the error:

Error

Class 'Craft\BusinessLogic_TaxRemover' not found

C:\Users\clive\Desktop\repos\_craft\craft\plugins\businesslogic\BusinessLogicPlugin.php(38)

26     }
27
28     public function getDeveloperUrl()
29     {
30         return '';
31     }
32
33     public function init()
34     {
35     }
36     public function commerce_registerOrderAdjusters(){
37            return [
38             new BusinessLogic_TaxRemover
39
40            ];
41     }
42
43 }


texts:
This is a pretty simple test before I implement some larger functionality. Eventually this will be just a glorified upload form via ajax.

Part 1 - Ajax post

$.ajax({
    type: 'POST',
    url: '/upload2',
    dataType: "json",
    data: JSON.stringify({"abc": "123", csrfTokenName: csrfTokenValue}),
    success: function(data, textStatus){
        alert('form submitted successfully');
        alert('data'+data);
    },
    error: function (data, ErrorText, thrownError) {
        console.log("Failed to process request correctly, please try again");
        console.log(data);
    }
});

Part 2 - Plugin

Plugin is installed. Inside my plugin init I've got a site rule setup:

$event->rules['upload2'] = 'plugin/default/upload';

I can visit this url in the browser without issue. Here's my function I'm trying to access:

public function actionUpload()
{
    $response_array['status'] = 'success';
    $response_array['post'] = $_POST;
    return json_encode($response_array);
}

When I try and run said code via ajax, console returns Bad Request: Unable to verify your data submission. and a 400 (Bad Request) error to boot.

This could easily be one of those doh! moments but so far I'm losing this war. Should I just quit the internet and go live in the woods? (kidding)

Anyone have any idea what I'm doing wrong here? Are ajax posts different in Craft 3?


texts:
According to the CraftCMS FeedMe 4 docs we should be able to import inner element field data when importing content via FeedMe.

I have a section we'll call Parent, which has two fields that need importing; ImportId (text field) and ChildEntry (Entry relationship). Child Entry has two fields, Title and Body.

I am able to map Parent->ImportId and ChildEntry->Title I am unable to map to ChildEntry->Body.

My JSON looks like this:

{
  "data": [
    {
      "title": "secrets",
      "import_id": "UUID-9-3/4",
      "child_title": "Harry Potter",
      "child_message": "Is in a dream",
    },
    ...
  ]
}

Is this expected functionality, or am I reading the documentation correctly?


texts:
First, which template does the actionGetElements use to generate a response?

Second, how can I customize the template for a single entry section?


texts:
Does anyone have any thoughts on automating the implementation Google's new AMP article markup?

https://www.ampproject.org/docs/get_started/create/basic_markup.html

Also see:
Google will start sending search traffic to fast-loading AMP news articles in February 2016

Thanks!


texts: Craft 3: Environment variables are not parsed when used in Assets source field

texts:
I'm using Craft 3 and I have 2 Sites setup.

In my config/general.php file I have:

return [
    '*' => [
        'environmentVariables' => [
            'baseAssetsUrl' => '//'.strtolower($_SERVER['SERVER_NAME']).'/assets/',
            'baseAssetsPath' => realpath(dirname(__FILE__)).'/../web/assets',
        ],
    ],

    'craft3uk.dev' => [
        'timezone' => 'Europe/London',
        'siteUrl' => 'http://www.craft3uk.dev/',
    ],

    'craft3me.dev' => [
        'timezone' => 'Asia/Dubai',
        'siteUrl' => 'http://www.craft3me.dev/',
    ],

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

    'staging' => [
    ],

    'production' => [
    ],
];

I can access the variables fine in a template like:

{% set baseAssetsUrl = craft.app.config.general.environmentVariables.baseAssetsUrl %}
{% set baseUploadsUrl = craft.app.config.general.environmentVariables.baseUploadsUrl %}

But when I try using {baseAssetsPath} like this

I get:

I'm a bit confused as I have a Craft 2 site setup the exact same way and this works fine.

I cannot see anything in the Craft 3 docs regarding this either?

Can anyone help me out please?


texts: Moving from Rackspace cloud files to Amazon S3

texts: Recently moved server from Rackspace to AWS. A lot of media in our entries is hosted by rackspace cloud servers. How intensive would it be to move these all to Amazon S3 in regards to linking media to entries?


texts:
I'm creating a macro I'd like to reuse multiple times but the only thing that changes is the field name (matrix). Here's an example:

{% for block in entry.fieldname1 %}
<h3>{{ block.title }}</h3>

I'd like to increment this macro so I don't rewrite this code snippet over and over again but when I try and change entry.fieldname1 to a string it's no{% set string = entry.fieldname ~ 1 %} it is no longer recognized inside the for loop.

Any ideas?


texts: How automatic slug generator could replace accentuated letters?

texts: When typing in the title, the automatic slug generator doesn't filter or replace accentuated letters such as (ő, ú, á, ű). Is there a way to replace these letters to the unaccented one (like ő -> o, ű -> u, etc..)?


texts: Decimals missing in result after adding up order totals for a customer

texts:
I want to show a user the total sum of all their orders.
My problem: In the result the decimals are "lost" and always show as zeros.

{% set totalOrders = 0 %}
{% for order in craft.commerce.orders.customer(craft.commerce.customer).find() %}
  {% set totalOrders = totalOrders + order.totalPrice|currency(order.currency) %}
{% endfor %}
{{ totalOrders|currency(order.currency) }}


texts: How to keep a users cart active after logout - Craft Commerce 2

texts: How do I set the cart to save / stay active in a users account. When I add some products to my cart (when logged in) and logout or close my browser the next time I come back my cart is empty. I'd like to have the cart 'stay alive' until I complete the order. Help is appreciated!


texts: Trigger Info window in Smart Map using external navigation

texts:
I would like to trigger an info window in Smart Map using a navigation that lives beside the map. I've managed to figure out how to use the zoomOnMarker function, however, the info window does not pop with this function.

{{ entry.title }}


texts: Running console (yiic) under MAMP (Windows)

texts:
I am running Craft 2 under MAMP (PHP 7.0.9) on windows and have a site that works under it. However if I use GIT to cd to the yiic console folder...

/c/mamp/htdocs/website/craft/app/etc/console

... and type ...

php yiic help

... I get an error message ...

Fatal error: Uncaught Error: Class 'Craft\ErrorHandler' not found in C:\MAMP\htdocs\website\craft\app\framework\YiiBase.php:213

... However, if I use PHP 5.6 (the one that I use to run the site - and which therefore has a different php.ini) I get a different message ...

exception 'CDbException' with message 'CDbCommand failed to execute the SQL statement: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected.

... even though the database settings must be OK as Craft works.

How do I get yiic to work?

PS: I have put some debugging into console\yiic.php and the paths that are getting returned match what I would expect.

I have also looked at Error Connecting To (MAMP Pro) Database in Console Command but the modification it suggests to craft/config/db.php refers to a file that does not exist: mysql.sock


texts: How to prevent access to asset folder (and redirect to other page)?

texts:
I have an asset source with url "/guides/".
When I put a file to this folder, a file gets an url:
domain.com/guides/myfile.pdf

If I go to "domain.com/guides", it shows me the file directory.
I prevent access to this by creating .htaccess file and now I see a Forbidden page (You don't have permission to access /guides/ on this server).

I have a Guides entry page: domain.com/guides/my-guides-main-page
Is it possible to make a redirection like this:
domain.com/guides -> domain.com/guides/my-guides-main-page


texts: Display an entry page if entry is disabled

texts:
I am trying to view an entry, even if it disabled on the front end but having no luck.

On the _entry.html (which works perfectly for entries that are live), I have tried the following.  Am I missing something?

{% set entry = craft.entries.slug(entry.slug).status(null).first %}

Thanks


texts: Autocomplete for Visual Studio Code for plugin development

texts:
How to achieve autocompletion for Craft 3 for PHP inside Visual Studio Code?
I mean, what is required (like installing PHP locally, folder structure etc.) if at all possible?

I assume many people who develop PHP are using PHPStorm for this. Also as I recall there are even instructions on how to get autocompletion for Craft 3 inside PHPStorm here: link.
As I'm trying to build some plugins I would prefer setting up an environment that works for me with autocompletion without having to look up everything and playing the guessing game. Out of preference I would like to use Visual Studio Code for this, so currently I'm somewhat stuck as I don't know if it is possible to get a similar kind of autocompletion like in PHPStorm inside Visual Studio Code for Craft 3 and also how to achieve it.
If someone could point me in a direction, I would be more than happy!


texts: Can I open one template/route when Craft is offline?

texts:
I've set Craft offline (System status). Is it possible to "open" one specific URL route so it can be accessed even though the website is offline?

For example the route: /blog/post


texts: Short question: Can I use GraphicsMagick with Craft CMS? If yes, how can it be configured? thanks


texts: Loop through entries in a Matrix block type

texts:
I have a Matrix field with 4 Block types. I loop through them like this

{% for block in entry.MatrixFieldHandle %}
    {% set type = block.type.handle %}

    {% switch type %}
        {% case 'BlockType1' %}
            {{ block.fieldHandle }}

        {% case 'BlockType2' %}
            {{ block.fieldHandle }}

within one of these cases, I need to loop through the entries:

{% case 'BlockType3' %}
    {% for row in block|batch(2) %}

        {% for block in row %}

{{ block.fieldHandle }}

        {% endfor %}

{% endfor %}

The html output is close, but I do not get any content displayed. What is wrong?


texts: Is it possible to get a tweet image when using Twitter plugin

texts:
I'm using Dukt's very nice Twitter plugin and it's working nicely returning the most recent tweet as I want, however I cannot seem to access the tweet's image. Is this possible?

{% set tweets = craft.twitter.get("statuses/user_timeline.json?screen_name=#{twitterHandle}&count=1&exclude_replies=true&include_rts=true&include_entities=true") %}

I've tried adding &include_entities=true

When I print out the json, I can't seem to see any media URLs. Has anyone else had any joy here? Thanks


texts:
I can't find the download links for Craft Pro. Where are they?

https://craftcms.com/support/try-craft-client-pro


texts: Checking value of customer order field within Plugin

texts:
I am trying to check the value of a checkbox as part of my checkout process. I have the following function at the moment.

public function init()
{
    craft()->on('commerce_orders.onBeforeOrderComplete', function (Event $event) {
        $order = $event->params['order'];
        echo '<pre>';
        print_r($order->signupForNewsletter);
            if ($order->signupForNewsletter == 'joinMailingList') {
                echo "I've opted in";
            } else {
                echo 'Not matched';
            }
        echo '</pre>';
        exit;
    });
}

But whether the checkbox is ticked or not I am only get the 'Not matched' statement, so my if statement is always false. I have tried several things, but cannot see how to resolve this.
I think perhaps because the signupForNewsletter is a checkbox in the custom order fields, so it is an array rather than an object.

Here is the print_r results of this code;

    Craft\MultiOptionsFieldData Object
(
    [_options:Craft\MultiOptionsFieldData:private] => Array
        (
            [0] => Craft\OptionData Object
                (
                    [label] => Join Mailing List
                    [value] => joinMailingList
                    [selected] => 1
                )

        )

    [storage:ArrayObject:private] => Array
        (
        )

    )
    Not matched

The checkbox was ticked in this instance as you can see in the value field.


texts: How to trigger code once in a thank you page?

texts:
Here is my scenario;

When a successful transaction occur, payment form page redirects to customer order page which have the orderId in url like /orders?number=1234

In this page i send ecommerce tag into Google Analytics.However this should be send only once, in first visit. So when the customer returns order page and look again, this code should not be fired.

What kind of ways should i follow? Can i do this from server, Craft side?

Thanks.


texts:
I'm usually working on Backends with PHP and ZF/Laminas.

Now I'm building a headless (only Backend) Craft CMS website and have a couple of questions that I didn't find a clear answer on. The Craft CMS project is developed "offline" with Vagrant+Docker and has currently no frontend and won't have it in the near future.

The authors should be able to create an entry (fieldset has only a text) that contains a name. I want to be able to work with the created entry like with a variable/item so I can link other entries and modules to it. Is there a way to do it in the Craft backend itself or in PHP in a controller for example? As I'm working headless, I'm not able to do twig as I don't have the templates or any kind of frontend for now.
The users should be able to upload files and link them to an created item from an author.
What's the best way to fetch these data? I'd like to be able to fetch all (or filter for files or text entries etc.) uploaded files or associated entries to that item.

Is it possible to get the content from specific entries out of my database executing SQL statements in PHP and use the data within a controller?

I'd like to have the newly created entries (by authors) dynamically as items that users can link their uploaded files to.

I'm very thankful for any kind of help!


texts: Is it possible to change the default location users upload their profile photos to? Right now they are stored in /admin/resources/userphotos/ which for me is not preferable for some reasons. I’d rather have them somewhere in html/img/member or similar.


texts:
I've been struggling all evening with getting the urls of my singles in a menu generator. At first I thought I nailed it, but it turned out it used the title of the singles instead of the url. When I tried to get the url I an error, so clearly I'm doing something wrong.

This is the code to generate the menu:

{# generating menu #}

        {# Get all Sections #}
        {% set sections = craft.sections.getAllSections() %}

        {# Loop through all single sections #}
        {% for singleSection in sections if singleSection.type == 'single' %}

            {# Output #}

{{ singleSection }}

        {% endfor %}

It is the singleSection.url that causes the error.

Craft\SectionModel and its behaviors do not have a method or closure named “url”.

I presume the SectionModel does not have an Url, but that doesn't bring me any close to solving my problem of getting the url of single pages.


texts: SQL Error (Feed Me) when matching entries

texts:
I'm currently getting the following error when matching on an entry field.

Offers Test: SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: integer ~~ unknown LINE 3: WHERE "id" LIKE $1 ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. The SQL being executed was: SELECT "structureId" FROM "sections" WHERE "id" LIKE '%' LIMIT 1 - Schema.php:664

Currently, I have two channels one is called "Brands" and the other "Offers". Offers has an Entry field which I'm trying to match on this field, see the below image:


texts:
How can I add a CSS class to all images inserted into a rich text field ?

ie. so an image inserted has style= "image fit" added to the img selector


texts:
I'm looking to write advanced nested search queries in Craft.

For example, below I'm looking to find results that have a featuredContent value of 1 and an endDate after today or empty. In psuedo code, (this == 1 AND (that = foo OR that = bar ).

{% set params = {
  section : 'sectionName',
  orderBy : 'startDate asc',
  featuredContent : "1",
  endDate : ">= " ~ now|date('Y-m-d') ~ ' OR :empty:'
} %}

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

Sadly, this doesn't work. Do I need to write this as a search function? If so, how?

A related question might be: is there a way to directly use MySQL WHERE queries to return entries via TWIG? This would be super helpful at times..


texts: Pass the rendered template HTML string to an external function

texts:
I want to use all of the Craft features to render a page from template, but instead of serving it to the front-end visitors I want to send it to an external mail delivery service (something like MailChimp) using cURL.

I guess I need to get the rendered HTML into a string and then pass it to my cURL function. How can I achieve this, any tips?


texts:
I am stuck on saving entry with a category field.
The error message I get is about not being able to create/update the entry in the relations table.

$accomodationTypecategory = ['title'=>'Hotel']

$entry = new EntryModel();
$entry->sectionId = 3;
$entry->typeId = 3;
$entry->authorId = 1;
$entry->enabled = true;
$entry->setContent(
    $entry->getContent()->setAttributes([
        'title' => 'Test Entry',
        'body' => "Testing",
        'address'=>"101 Silver Avenue",
        'phone'=>'0209900292092',
        'websiteAddress'=>'www.example.com',
        'towns'=>'Newy',
        'accommodationType'=>$accomodationTypecategory
    ]);

craft()->entries->saveEntry($entry);

Any help will be appreciated.


texts:
Downloaded latest release, pushed app-new to server, renamed app to app-old, renamed app-new to app.

Try to go to admin, and I get a 500 error.

Server error log shows.
2017-11-15 12:29:29 Error   500 GET /admin HTTP/1.1

Any ideas.
Trying to update an install that hasn't been updated in a long time.
Going from 2.6.2911 to 2.6.2974

I can still get to admin if I use the old app by renaming app to app-new, and app-old to app


texts: How to reorder structure entries in the Admin panel?

texts:
I converted a channel into a structure and now my entries are listed in reverse order.

I have a very large number of entries. Is there a way or a plugin to permanently sort them and store the order?


texts:
I have a multisite setup and and a search bar at the top of each site. Currently it just searches within that site:

{% set theSite = craft.app.request.getSegment(1) %}
{% paginate craft.entries.search(search).site(theSite).orderBy('score').limit(9) as pageInfo, pageEntries %}

The first segment defines the site.
I need to expand the searches to include all entries in all sites. Is this possible? I tried variations of getAllSites and just .site but of course those didn't work.

If its not possible to search all sites at once I may look at running each search and adding all of the results together.


texts: Headless CraftCMS: How can I tell Craft to load live preview from a different (sub)domain?

texts:
I will be using CraftCMS (Craft Solo 3.3.18.4) in headless mode as the backend for a Rails app. The Craft instance lives on a different subdomain.

How do I instruct craft to use the rails app URI when loading live preview in the preview iframe?

For example, if we presume
admin.domain.com for craft admin and
domain.com for the front end

How do I make the live preview frame to load from the live app?
domain.com/posts/first-posts-slug?x-craft-live-preview=2OcHezCnU8&token=lY6F...


texts: Put SEO and Twitter card Meta tags in the Head section prior the render of the template

texts:
I need to put some <meta /> tags in the <head /> section of the html document prior the rendering of the template. I would like to know how can I achieve this? I also need to query an external database in order to get some data from it and populate the meta tags. What I want to accomplish is to pass a link to my website and get Twitter to display a card with the image, description, etc.
What is the best option in order to accomplish this task? a Plugin? a Controller? a Module? Does anybody know any good tutorial or guide in order to do this?
I'm using CraftCMS ver 3.4.9
Thank you in advance for your support.


texts:
You know, the one that gangs blocks together but never really gets explained in the docs.

I hate that thing. I hate it because double-clicking (or single clicking) anywhere in a Matrix block header toggles the check. And wouldn't one rather collapse/expand a block by double-clicking than by pulling down that menu?

It can be hidden with CSS (with consequences) but I am wondering if there is something I am missing.

I would love to restrict its behavior to just the far-left checkbox/label area. I think it's a UI mistake to make the entire header the active checkbox area.

Can anything be done to suppress or limit the clickable area of the checkbox in a Matrix block header? (or Neo)


texts:
Just wondering if its possible to output an array to the Plugin::log call? Would be really handy to see if an error occurs, what a data object's values are!

Tried the following:

Plugin::log(array('test')), LogLevel::Error);
Plugin::log(json_decode(array('test')), LogLevel::Error);
Plugin::log(var_dump(array('test')), LogLevel::Error);
Plugin::log(print_r(array('test')), LogLevel::Error);
Plugin::log(\CVarDumper::dump(array('test')), LogLevel::Error);


texts: How can I set up tiered volume discounts without enacting a waterfall effect of multiple discounts being applied?

texts:
Trying to set up tiered volume discounts and can't figure out how to not have multiple discounts get applied when the cart total meets minimum criteria for more than one discount.

So the simple discounts I'm trying to have applied are here:

I understand why Craft is applying both: Because the order meets the criteria for both Purchase Quantities. Is there a way I can specify a range, or other workaround?


texts:
I am using structure type entries for navigation with three fields for navigation that uses either:
-customlink field (plain text) or
-category
entry
as the source for links.

I have product categories setup like in this post: How do I add a subcategory to the URL slug for a channel entry?

This gives me the display of products I want from each category. My nav output template for category navigation looks like this:

            {% if entry.menulink|length %}

            {{ entry.title }}

            {% elseif entry.customMenuUrl %}

            {{ entry.title }}

            {% elseif entry.productCategoryLink|length %}

            {{ entry.title }}

            {% endif %}

My category links work to display my nice list of products.
My products section is set like: https://www.dropbox.com/s/o4ia62jo7i8yo38/Screenshot%202016-03-04%2017.29.35.png?dl=0
with the section entry urls set to render an entry in the template 'flowers/_entry.html''

SO thats the setup for navigation and templates.

Two problems are occurring which I cannot resolve yet.

The entry links in my category template produce nothing. When clicking on an entry from the category  I get my base and site templates but the output at 'flowers/_entry.html' is never rendered. I cant work out where craft thinks the entry template for the category should be.

2 . My navigation links are inheriting the current url
So if on the page 'mysite.com/category1' and i click on 'category1' in my navigation the url becomes ''mysite.com/category1/category1'

Have been round the houses for 2 days on 1 above. I don't mind a learning curve but I am in circles and not ascending the curve :)


texts: Schedule plugin not working for Feed Me plugin

texts:
I have created a schedule to run the 'Feed Me' every 1 minute using the plugin 'Schedule', but it doesn't work. I not sure am I using the correct setting or not. I manage to get the latest data if I manually click the 'Run Feed'.
This is my setting for 'Schedule'

This is my timer


texts: How do I disable the default translation feature for a custom field?

texts:
I am making a custom field that provides granular control of what values will be translated and what values will remain shared across multiple sites.

Because of that, I'd prefer to entirely the disable the default translation feature of the field so users cannot accidentally set the field to be translatable (which would defeat its purpose).

Is this possible?


texts:
I need only 2 main categories, A and B, and both can have unlimited subcategories. Ideal would be to split these into groups but how can an editor choose between groups AND only select or create a category?

I could setup a checkbox field which asks is this A or B but this then needs to be linked to the category groups and might make the template tags to call the data unnecessary complicated.

What's the craft-way todo this?


texts: How do I check and indicate that a product is already in the cart?

texts: Is it possible to show the complete products list, but indicate which products are already in the cart? What's the conditional?