texts: How can I populate a dropdown via table field type using the default values?

texts:
In the CP I have a table field called colors. I have two columns, "Label" and "Value".

I have populated the table with two default values "Red" and "Blue" (attached).

This table will ultimately populate a dropdown on the front end. Label being the label, and value being the value.

When I edit the entry that I have assigned the colors field to, the default values do not show. I can only choose "Add a row". I do want to be able to add/remove rows like this, but I'd like to have "Red" and "Blue" be there by default.

On the template level I create the dropdown like this:

{% if entry.colors|length %}
<select id="colors" name="colors">
    <option value="">Select</option>
    {% for color in entry.colors %}
        <option value="{{ color.value }}">{{ color.label }}</option>
    {% endfor %}
</select>
{% endif %}

The drop down does not show until I enter a value in the entry. I'm not sure what I'm doing wrong so that the drop down will pull in the default values by...default.


texts:
{% set slug = craft.request.getParam('s') %}

{% if slug | length %}
    {% set category = craft.categories.slug(slug) %}
    {% set faqs = craft.entries.section('faq').order('title').limit(null) %}

{{ category.title }}

        {% for entry in faqs.relatedTo(category) %}
            {% if entry.level >1 %}

{{ entry.title }}

            {% endif %}
        {% endfor %}

{% else %}

 No matching results found

{% endif %}

In the code above, I cannot get {{ category.title }} to display. It is empty. If I put {{ category.slug }} instead, it shows the correct value. The other items in unordered list are displaying perfectly. I am confused as to why the title is not showing


texts: Return all Matrix blocks with a drop down set to a specified value

texts:
I'm in the context of an Entry that has a Matrix field, and one of those Matrix fields is a Dropdown called subsection. I want to grab all Matrix blocks that have subsection set to 'intro'.

This is how I'm trying to do it and it definitely doesn't work. Is there another way to accomplish this?

{% for block in entry.myMatrix.subsection('intro') %}
…
{% endfor %}


texts:
I've gone through all the steps here to remove index.php https://craftcms.com/support/remove-index.php
The .htacess file is the default one that came with Craft on install
<IfModule mod_rewrite.c>
    RewriteEngine On

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

In my config/general.php file I have the setting set explicity..
'omitScriptNameInUrls' => 'true',

I wrote to Arcustech for help with the httpd.conf file as the last step and they said...

Changing that setting is not something we will update on Arcustech. If you were not already aware, we are a Craft CMS Hosting Partner and removing index.php in Craft URLs works on our servers without that update.
If you tell Craft Support you are hosted with Arcustech the Craft support team will know stuff will work here, so something else is wrong in the setup or .htaccess file. The account is not set up as a Craft Optimized plan (https://www.arcustech.com/managed/craftcms-hosting/) but that does not matter for basic functionality like that in Craft.

I asked to be moved to the Craft Optimized plan, but it doesn't sound like that's an issue.
Any idea what's going on? Somedays it's fine. Today, at the moment, it's not.


texts: Users allocating permissions beyond their own

texts:
I have set up a user group named Administrators, to be used for the person in charge of managing the website day to day. But I didn't tick the Admin box as I don't want them to be able to access plugins or updates etc.

I want them to be able to create users and fine tune the permissions of the users they create. So I ticked all the boxes in the User section. But if I log in as that Administrator I am allowed to change my own permissions (and all the other users) to access plugins.

This can't be right, how do I prevent them increasing their own permissions beyond those I have allocated them?


texts:
I have an Assets field assigned to my homepage. I can assign and upload images the same way I've always done.

When it comes to templating, I can loop through the images and output the filename. What I can't do anymore is get the URL. What am I missing?

{% set assets = entry.featured %}

{% if assets | length %}

Some great assets

    {% for asset in assets %}

          {{ asset.title }}

          {{ asset.url }}

    {% endfor %}

{% endif %}

The url's no longer return anything. I've also tried getUrl('someTransformHandle') too.

I can't see anything mentioned in the Craft 3 documentation for assets regarding any deprecations or significant changes.


texts: Most efficient way to check if a section has any active entries

texts:
Just wondering what the most efficient way to check whether a section has any entries or not. Based on this, I'm showing some content. The content doesn't take any information from the entries in the section, so it'll be a superfluous query no matter what.

For context, this is basically what it'll look like:

{% if craft.entries.section('whatever') | length > 0 %}
    Go here
{% endif %}


texts: Caching not working on page with asynchronously loaded asset transforms

texts:
I'm using PictureFill on a large page, containing many image transforms, that doesn't seem to be caching despite most of the page being wrapped in {% cache %} tags. When I view the page after several refreshes with Dev Mode enabled, the Profiling Summary Report is reporting Total Queries at 174, and the HTML source still contains many examples of image urls that contain something like /cpresources/transforms/XX.

I read in this answer that Craft won't cache a page with unresolved transforms, which might explain why this page isn't being cached. But then the question is, why aren't these transforms resolving?


texts:
I am trying to load an image transform and continually get a 404 which references an issue with the UserSessionService. I have a attached a screen shot as well as twig template for one of the transform.

{% set contributor = entry.contributorProfile.first() %}
{% set headshot = contributor.headshot.first() %}

{% set thumb = {
    mode: 'crop',
    width: 200,
    height: 200,
    quality: 80,
    position: headshot.focusPctX ~ '% ' ~ headshot.focusPctY ~ '%'
} %}

<aside class="contributor-excerpt">
    <img src="{{headshot.getUrl(thumb)}}" alt="">
</aside>


texts:
I would like to test out Craft Pro to see if it would be a good fit for my next project.

I have one issue. I have followed the instructions to install Craft CMS @ http://site1.craft.dev - but am unable to see the upgrade/test link in the footer?

Here is a screen shot of the domain I have it installed at:-

Here is a screen shot of the footer:-

How would I activate the trial licence (I am probably missing something obvious, so forgive me if this is the case) :)?


texts: What's the purpose of multiple asset sources?

texts:
If I have just one S3 bucket, should I still have multiple asset 'sources' in order to account for different asset types? Or should I just have multiple folders under single asset source to differentiate media types?

For example, I might have these folders under a single asset source:

Illustrations/Icons
Marketing Images
Screenshots
Marketing Videos
Support Videos

It just seems silly to add multiple asset 'sources' when the details are the same.


texts:
Good mornig

I am having a problem with my bannerImage.
First off i show you how i did it and what the problem is.

In the first picture you can see, how i get the image.
This method works fine for 3 other pages on this website.¨
My field setup is correct, because in other templates it works fine.

The only thing i can now think off is that there's something wrong with the name of the template.

Thanks for your help.

EDIT
I fixed this problem like this.


texts: Output Channel entries on another page with a matrix block

texts:
I know im doing something small wrong but I cant see what at this point.
I have a channel called 'testimonialEntries' and I want to randomly output one of these entries on seperate pages. I cant output the matrix block in 'testimonialEntries' but i can the title, so i know its working just not accessing the matrix block.
{% for entries in craft.entries.section('testimonalEntries').orderBy('RAND()').limit(1).all() %}
{% block in entry.matrixBlock %}

{{ block.heading }}
]

{{ block.bodyContent }}

{% endfor %}{% endfor %}

In this example im getting the entry title, but how do i also get a matrix block?
Edit: AM I getting close?
{% set testimonialEntry = craft.entries.section('testimonalEntries').orderBy('RAND()').limit(1).with(['testimonial']).one() %}
{% set testimonialEntryMatrixBlocks = testimonialEntry.testimonial %}
    {% if testimonialEntryMatrixBlocks %}

{{ testimonialEntryMatrixBlocks.body }}

{{ testimonialEntryMatrixBlocks.quote }}

{{ testimonialEntryMatrixBlocks.role }}

    {% endif %}

Ok final edit incase anyone else runs across this: It Works!
    {% set testimonialEntry = craft.entries.section('testimonalEntries').orderBy('RAND()').limit(1).with(['testimonial']).one() %}
{% set testimonialEntryMatrixBlocks = testimonialEntry.testimonial %}
    {% if testimonialEntryMatrixBlocks %}
        {% for testimonial in testimonialEntryMatrixBlocks %}

{{ testimonial.body }}

{{ testimonial.quote }}

{{ testimonial.role }}

        {% endfor %}
    {% endif %}


texts:
Ok once again I'm having an issue with a plugin controller. It was working once upon a time but stopped sometime in the past year.

I have stripped the plugin down to bare, so there is no reason it shouldn't be working.

File Structure:

craft/plugins/
--webmentionreceiver/
----controllers/
------WebMentionReceiver_EndpointController.php
----WebMentionReceiverPlugin.php

craft/plugins/webmentionreceiver/controllers/WebMentionReceiver_EndpointController.php:

<?php
    namespace Craft;

    class WebMentionReceiver_EndpointController extends BaseController  {
                protected $allowAnonymous = array("actionReceive");

                public function actionReceive()  {
                        $this->redirect('/');
                }
        }
?>

So the plugin name is WebMentionReceiver, the controller is Endpoint and the action is Receive. So index.php?p=actions/webmentionreceiver/endpoint/receive should be the URL. But it 404s.

Any ideas? It is driving me mad!


texts:
Is there any way to migrate the configuration of a Sprout Form between my local environment and the production environment?

I'm on Craft 3.

Ideally, I'd love to generate a migration using the migration manager https://github.com/Firstborn/Craft-CMS-Migration-Manager but would love any way to move the settings of a form.


texts: Do I use Twig filters 'include' and 'extends' for localized site correctly?

texts:
I use regular file names for template structure from documentation for clearer understanding.

I have the template structure:

_layouts

base.twig

_includes

header.twig
body.twig
foot.twig

index.twig
de

_includes

header.twig
body.twig
foot.twig

index.twig

So for top level domain, 'index.twig' extends 'base.twig' and 'base.twig' include 'header.twig','body.twig' and 'foot.twig'.

For sub level domain (example.com/de), It's the same scenario as for top level domain.

All 'index.twig' files in all sub level domains extends the same file located at '_layouts/base.twig'.

The include filters look like this in my 'base.twig' template.

{% block header %}{% include '_includes/header' %}{% endblock %}
{% block body %}{% include '_includes/body' %}{% endblock %}
{% block foot %}{% include '_includes/foot' %}{% endblock %}

All work great, but did I use it correctly?

The thing that confuses me, is that I didn't have to copy '_layouts' folder with 'base.twig' file to 'de' folder, and modify paths in 'base.twig' for all include filters. Why is it so? Twig renders files of an active locale?


texts: Can we use Active Directory for Access Control?

texts: We have a quite elaborate set up for Active Directory, and would like to use this to provision & deprovision access to the Control Panel. Would this be possible in Craft core or in a plugin? Are there hooks to use alternative access methods?


texts: I moved my craft site to a subdirectory, and things are broken now, help!

texts:
I installed craftcms on a regular .com root folder, and everything worked fine. I can go to .com/news and it will go to my /templates/news.html file, etc.

Now my client wants their site on a subdirectory. I copied over all the files to the new subdirectory, but now when i go to .com/subdirectory/news, I get a 404 page. I checked that the .htaccess was correct, I just don't know what else I have to change to make the new site work on the new subdirectory. Please help!


texts: Contact form plugin - if errors jumps to top of page

texts:
Using the standard form plugin can you redirect for errors to a id, which works for the submission confirmation (success)?

 {{ redirectInput('#contact') }}

My form is half way down the page so jumps you to the top when it has errors.

Full code:

{% if craft.app.session.hasFlash('notice') %}

{{ craft.app.session.g*emphasized text*etFlash('notice') }}

{% elseif craft.app.session.hasFlash('error') %}

{{ craft.app.session.getFlash('error') }}

{% endif %}

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

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

<form method="post" action="" accept-charset="UTF-8" id="form">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="contact-form/send">
    {{ redirectInput('#contact') }}

Name

      <input id="from-name" type="text" name="fromName" class="w-full" value="{{ message.fromName ?? '' }}">
      {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

Email

      <input id="from-email" type="email" name="fromEmail" class="w-full" value="{{ message.fromEmail ?? '' }}">
      {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

Message

    <textarea rows="5" cols="40" id="message" name="message" class="clearfix">{{ message.message ?? '' }}</textarea>
    {{ message is defined and message ? errorList(message.getErrors('message')) }}

<input type="submit" value="Send">

</form>


texts: How to improve performance of this nested entries/array template?

texts:
I have an event calendar of sorts for music gigs. The back-end has sections for Artists and Venues, where I enter appropriate info, and another section, Shows, which I choose an artist, a venue, and enter the event date (in a custom field).

The template that pulls everything together grabs all future show dates, groups the dates by the artist, then checks each entry for fields before displaying it in the HTML, like so:

{#-- grab all current shows and order by date --#}
{% set all_shows = craft.entries.section('shows').gig_date('>=' ~ (now.date)).order('gig_date asc') %}

{#-- group shows by artist --#}
{% set artist_shows = all_shows|group('gig_artist.first()') %}

{% for artist, shows in artist_shows %}

    {#-- artist title --#}

{% if shows[0].gig_artist[0].artist_url|length %}{{ artist }}{% else %}{{ artist }}{% endif %}

            {#-- shows list --#}
            {% for show in shows %}

                        {#-- date --#}
                        <time title="{{ show.gig_date.w3c }}">{{ show.gig_date|date('F j') }}</time>

                        {#-- venue name and website--#}
                        {% if show.gig_venue[0].venue_url|length %}{{ show.gig_venue[0].title }}{% else %}{{ show.gig_venue[0].title }}{% endif %}

                        {#-- city --#}
                        {% if show.gig_venue[0].venue_city|length %}, {{ show.gig_venue[0].venue_city }}{% endif %}

                        {#-- state --#}
                        {% if show.gig_venue[0].venue_state|length %} {{ show.gig_venue[0].venue_state }}{% endif %}

                        {#-- notes --#}
                        {% if show.gig_notes|length %}
{{ show.gig_notes }}
{% endif %}

            {% endfor %}

{% endfor %}

This page takes several seconds to render on my site versus the other pages. I've tried this without the |group filtering, and without the date comparison, and it's still equally slow, which leads me to believe it's the pinging the multiple entry fields that's slowing things down.

I have a hunch eager loading will be helpful, but unfortunately I can't wrap my brain around it at this level. Any ideas?


texts:
Our local dev environment allows us to run a CMS like Craft but our (government) host is static only. We currently accomplish things with movable type 4, but would like something more modern. MT 7 costs $1000 a year, so that is right out.

Is there a plug-in for Craft that can export static html we can upload to our host?


texts: Find matching asset (image) for category

texts:
What would be the best approach to have a list of categories (brands in my case.) and if an asset (image) exists that matches that brand name show that asset or instead show a placeholder image.

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

{% endfor %}


texts: Element API: How to get entries up to a certain page?

texts:
I have a query that is pulling entries from a structure with
elementsPerPage' => 3

If my pagination looks like this:

Page 1:
Entries: A, B, C

Page 2:
Entries: D, E, F

Page 3:
Entries: G, H, I

How should I write the query to get all entries up to page 2?

Request Page 2 Results:

Entries: A, B, C, D, E, F

Request Page 3 Results:

Entries: A, B, C, D, E, F, G, H, I


texts:
In the Sprout Forms plugin, is there a way to modify the EntryModel through sproutForms.onBeforeSaveEntry? I have a plugin that sends a cURL request onBeforeSaveEntry, and I'd like to grab the response from that and deliver it to the user on the thank you page.

I've tried setting new properties on the $event object but I'm getting errors, so maybe my approach is wrong? Been searching, but unable to find how to get it done.


texts: How do i put google analytics code into a Global field?

texts: can anyone tell me step by step what to do to put google analytics code into a global field? I have read the earlier answer but i am new to craft and i don't know where to start.


texts: How do I display entries depending on multiple relations?

texts:
In this example, I'm trying to show entries with the category "Beer". This works:
{% set myCategory = craft.categories.slug('beer') %}
 {% if entry.relatedDrinks.relatedTo(myCategory)|length %}

Beers

  {% for beer in entry.relatedDrinks.relatedTo(myCategory) %}
   {{beer.title }}
  {% endfor %}
{% endif %}

I also want to limit these entries to a certain year (not defined by Entry Date). I've created a Section called "Product Year" with entries such as "2020" and "2021". Within the entry for the beer, I've added an Entries field to select the year defined in the Product Year section. I'm not sure how to use that Product Year relation as a filter.
I'm essentially trying to say {% if entry.relatedDrinks.relatedTo(myCategory)|length "and product year is 2020 "%}


texts: Twig Error Runtime When Using Conditionals

texts:
I am trying to create a meta include to display all my meta data and I have the following set up so far:

3. {% if craft.request.getSegment(1) != "404" and craft.request.getSegment(1) != "databytes" %}
  4. <title>{% if entry.metaTitle is defined %}{{ entry.metaTitle }}{% else %}{{ entry.title }}{% endif %} | {{ siteName }}</title>
  5. {% if entry.metaDescription is defined %}
  6. <meta name="description" content="{{ entry.metaDescription }}">
  7. {% endif %}
8. {% endif %}

{# 404 =============== #}

{% if craft.request.getSegment(1)  == "404" %}
  <title>Page Missing | {{ siteName }}</title>
  <meta name="description" content="Sorry the page you are looking for is missing, it may have been moved or deleted, please use the navigation to search for similar content.">
{% endif %}

If I visit main pages the code works and if I go to example.com/404 the code works, but if I visit an invalid url example.com/foo then I get a Twig Error Runtime error:


texts: How to configure Craft to work with Redis replicas?

texts:
We have an existing load balanced / HA deployment of Craft 3.4, to which I want to add support for the redis replica we have available, but I can't work out how to correctly configure this in config/app.php.
For a single redis server I have this config and it works fine:
...
    'components' => [
        'redis' => [
            'class' => yii\redis\Connection::class,
            'hostname' => getenv('REDIS_HOST'),
            'password' => getenv('REDIS_PASS'),
            'port' => 6379,
        ],
        'cache' => [
            'class' => yii\redis\Cache::class,
            'defaultDuration' => 86400,
        ],
        'session' => [
            'class' => yii\redis\Session::class,
            'as session' => craft\behaviors\SessionBehavior::class,
        ],
...

Here's what I'm trying for replicas based on the yii-redis-cache docs, but which doesn't work:
    'components' => [
        'redis' => [
            'class' => yii\redis\Connection::class,
            'hostname' => getenv('REDIS_HOST'),
            'password' => getenv('REDIS_PASS'),
            'port' => 6379,
        ],
        'cache' => [
            'class' => yii\redis\Cache::class,
            'enableReplicas' => true,
            'defaultDuration' => 86400,
            'replicas' => [
                 'redis',
                 ['hostname' => getenv('REDIS_HOST')],
                 ['hostname' => getenv('REDIS_SLAVE_HOST')],
            ],
        ],
        'session' => [
            'class' => yii\redis\Session::class,
            'as session' => craft\behaviors\SessionBehavior::class,
        ],

How do I configure Craft to use both the redis servers available?


texts: Users in odd state of pending and needing password reset

texts:
Users are falling into the following state:

Tried to sign up with public registration
Never clicked or never received (or so they claim) the verification email.
Users try to sign up and email is already taken
Users cannot reset password as their account is not verified.

Is this a problem? Or am I missing something. Is there a way to activate when they click the reset password link email?

Apart from resending verification email manually for all 100+ users is there anything else i can do?


texts: Image thumnail not found(404) issue. What causes the header to set as image/svg+xml instead of png/jpeg?

texts:
Thumbnails not loading in assets list in my control panel with my host platform.sh(works in my local docker env).
Call to index.php?p=admin/actions/assets/thumb&uid=29dad26b-ba90-4b26-b9fb-12b3f6ded747&width=67&height=68&v=1617954445%2068w shows
The file “uploads/70790C46-B60E-4924-9ED3-B0089CDEE51B.png” does not appear to be an image in logs.
Response header content type was set as image/svg+xml.
May be this is the root cause for the issue.
Saw this snippet in cms/src/image/Raster.php
// Make sure the image says it's an image
$mimeType = FileHelper::getMimeType($path, null, false);
if ($mimeType !== null && strpos($mimeType, 'image/') !== 0 && strpos($mimeType, 'application/pdf') !== 0) {
    throw new ImageException(Craft::t('app', 'The file “{name}” does not appear to be an image.',
    ['name' => basename($path)]));
}

try {
    $this->_image = $this->_instance->open($path);
} catch (\Throwable $e) {
    throw new ImageException(Craft::t('app', 'The file “{path}” does not appear to be an image.',
    ['path' => $path]), 0, $e);
}


texts:
I am having trouble getting a freeform success message to display. I am posting back to the same template. What is the proper way to check if the form was posted? I see in the freeform render template there is a freeform.hasErrors, is there something for success perhaps?

            {% if craft.request.getPost('firstName')|length %}

Your message has been sent.

            {% else %}

                {{ craft.freeform.form("contactForm", {
                        formAttributes: { "data-abide": true },
                        instructionsBelowField: true,
                        submitClass: "button",
                        returnUrl: "/contact",
                        useRequiredAttribute: true
                    }
                ).render() }}

            {% endif %}

https://solspace.com/craft/freeform/docs

Update: Working code using query param instead. Thanks @Jan_dh.

            {% if craft.request.getQuery('success') == 1 %}

Your message has been sent.

            {% endif %}

            {{ craft.freeform.form("contactForm", {
                    formAttributes: { "data-abide": true },
                    instructionsBelowField: true,
                    submitClass: "button",
                    returnUrl: "/contact?success=1",
                    useRequiredAttribute: true
                }
            ).render() }}

            {% endif %}


texts: How do I hide children of a disabled parent in a nav?

texts:
So I've got a {% nav %} I'm trying to create with the following code:

{% nav page in craft.entries.section('pages') %}

        {{ page.title }}

        {% ifchildren %}

{% children %}

        {% endifchildren %}

{% endnav %}

My issue is that I've got a top-level page that has been disabled but has some enabled child/sub pages (second-level). So the code above doesn't display the disabled top-level page but it is showing all the enabled children of that disabled page. I've tried wrapping different parts of the {% nav %} code with a conditional but that seems to interfere with the {% ifchildren %} tag.

So my question is, is this the default Craft functionality? If so, what's the best way to solve this problem? Thanks!


texts:
I've found this in the documenation:

  Dates and times are both formatted for the user’s preferred locale.
  They are displayed in the site’s timezone, however they get stored in
  UTC like all other dates in Craft.

That's fine.

I use this timezone: UTC+1 (CET) - Europe/Rome

As expected everything is saved in the database with an UTC offset of minus one hour exept the expiryDate in the craft_templatecaches table: the UTC offset is minus two hours.

Here is my code snippet:

{% set expiredNews = craft.entries.section('news').order('expiryDate')|first %}
{% set expiryDate = expiredNews.expiryDate %}

{% cache until expiryDate %}

Example:

expiryDate in entry: 2015-04-01 00:00:00

expiryDate in cache: 2015-03-31 22:00:00

Why is there an offset of two hours and what does that mean for cache invalidation?


texts: 404 – Not Found from _entry.twig templates in subdirectories

texts:
Following the Minjingo CraftQuest tutorial, I am getting an error on the front end when I access any routes other than the root/home page.

In my template folder, I have a structure that looks like:

templates/
├── index.twig
├── about/
│   └── _entry.twig
├── drinks/
│   └── _entry.twig
└── news/
    └── _entry.twig

In my about section settings, my template is about/_entry, as it is in the tutorial.

The error I get is:

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

Maybe I missed a step? What should I look for?


texts:
A year ago I asked this question and thanks to the answers I got things working.  A year later and i'm trying to do the same thing on a different website...  only this time it's not working!

Section Handle = artist
SuperTable Field Handle = lineUp
SuperTable 'Entry' Field = artistPerforming, which is linked to Section 'artist'

Here's my code:

{% set reverseRelatedElements = craft.supertable.getRelatedElements({
    relatedTo: {
        targetElement: entry,
        field: 'lineUp.artistPerforming'
    },
    section: 'artist'
}) %}

{% for eventLineUp in reverseRelatedElements %}
    {{ eventLineUp.title }}
{% endfor %}

My SuperTable field is assigned to a Section with handle stageEvent, so from my stageEvent entry i'm trying to pull related entry information from Section artist.

Nothing is outputting but I don't get any errors??

Can anyone see what i'm doing wrong?

Many thanks

Martin


texts: Craft equivalent to Drupal Signups module

texts:
I'm investigating a switch to Craft CMS for my non-profit as an alternative to Drupal or Wordpress. We're on Drupal right now, and our website gets used daily to sign up for public events that we host.

The functionality of the Drupal Signups module (ttps://www.drupal.org/project/signup), combined with the Events module, is one thing we'd be want to replicate if we moved to another CMS. Essentially, we want to enable:

a) registration for the event (name, email address, phone number that is temporarily stored -- we don't want to deal with usernames or passwords to sign into the site)

b) a registration cap (i.e. registration closes at 40 attendees)

c) confirmation emails, as well as reminder emails to be automatically sent to registered users that the event is coming up

d) the ability for staff to send a group email to all registrants in case the event is delayed/cancelled from within the CMS;

e) the ability for our staff to view and manage signups from the admin interface (i.e. delete a registrant if they want to cancel their spot)

I see that Craft has plugins such as Venti to handle the event side of things. Is there anything currently available that could similarly handle signups and reminder notices? Does anyone know of similar examples using Craft CMS for other websites?

Thanks!


texts: Storing multilingual content that is used across sections

texts: I'm new to Craft, but starting off with building a multilingual site. I wonder what is best practice for storing multilingual content that is used accross sections (i.e. site navigation headings, footer link text). I know about the static translation files, but I want to enable local editors to translate those themselves in the CP.


texts: Show only top level categories assigned to an entry

texts:
Having a bit of a brainfart here...
If hotspotCategory is my entry's categoryfield and that category group has nested categories, how do I return only the top level categories?

{% set entryCats = entry.hotspotCategory %}
{% if entryCats | length %}
    <span class="filter_cat">
       {% for cat in entryCats %}
          {{ cat.title }} {% if not loop.last %}, {% endif %}
       {% endfor %}
     </span>
 {% endif %}

this works but if I do something like

{% set entryCats = entry.hotspotCategory.level(1).all() %}

I get an

Impossible to invoke a method ("level") on an array.

error.

What am I missing here?

To clarify: my entry has the following categories attached (slow & fast food are subcategories):

- food & dining
--- slow food
--- fast food

Now, on the entry page I only want to display the top level category, not the subcategories.


texts:
Is it possible to update the config.php file in a plugin outside of manually opening and adjusting the array? I'm hoping there's a way I can have a certain user group be able to change the array values with the plugin's control panel page.

The config file is very simple, it looks like this:

<?php

return [

    'active_features' => [
         'change_team' => false,
         'change_series' => false,
         'change_user_settings' => false,
    ],

];

And I need a way for them to be able to toggle, say, 'change_team' to true or false every so often. I've searched around and haven't found anything at all to try. Does this kind of functionality exist at all?


texts:
We have a problem with using Live Preview on a site that uses CDN caching [CloudFront].

When opening Live Preview a POST is sent to the actual page URL containing the information and the response is rendered

/mypage

However /mypage is in the CDN cache for GET requests and so when Craft sends the POST the headers and cookies are not forwarded to the origin. This causes a 400 error.

We tried using a subdomain just for the CP, but of course the site is still on the cached domain and this is the domain used by the CP.

Is there a way to use live preview with CDN caching?

One potential approach would be to have a cookie set that is only set for logged in CP users, then we can set up a cache rule to bypass the CDN cache for all requests with that cookie.

Unfortunately our hosting partner informs us that we cannot have different caching profiles based upon a cookie. So we really need the Live Preview POST to be to paths that are not the actual cached live site paths.


texts: Only allowing users to change their own profiles

texts:
I have added public profiles following an answer on this stack exchange and it works great, the problem arises when adding a "User Profile Form" which allows users to update their own settings. The problem is that currently, anyone can edit anyone's profile if they were to hardcode the URL to another person profile.

So I'm trying to safeguard it by making sure the profile belongs to the currentUser. This is my setup:

_layout.html

{% set users = craft.users %}

_profile.html

{% extends "_layout" %}

{% block content %}

  {% set user = craft.users.username( craft.request.segment(2) ).first() %}
  {{ user.username }}

{% endblock %}

account.html

{% extends "_layout" %}

{% block content %}

  {% if currentUser.username == user.username %}
    <form method="post" accept-charset="UTF-8">
      {{ getCsrfInput() }}
      <input type="hidden" name="action" value="users/saveUser">
      <input type="hidden" name="redirect" value="users/{{ currentUser.username }}">
      <input type="hidden" name="userId" value="{{ currentUser.id }}">

      Location

      Bio

      <input type="submit" value="Save Profile">
    </form>
  {% endif %}

{% endblock %}

Right now I'm getting Variable "user" does not exist. but I'm unsure what's the best way to go about safe guarding this?


texts: modifyEntrySources hook with reverse relations

texts:
Is it possible to do a reverse relation query in a custom entry source?

https://docs.craftcms.com/v2/plugins/hooks-reference.html#modifyentrysources

I have two entry sections, one called courses and one called course occurrences. Course occurrences are linked via an entries field called parentCourse. It easy enough to query course occurrences that don't have a parent course (check if parentCourse is empty/not empty, but the reverse seems to be a little more complex.

I'm looking for the ability to have a custom entry source that lists all the parent course records that don't have a child record basically, making it a reverse relation.

I tested the Reverse Relations plugin and it does display the children entries related on the parent so the relation works, but I was wondering if it can be done directly through a criteria query in the modifyEntrySource hook?


texts:
It looks like the craft/app folder is no longer in the Craft download.

I've been using v.3.0.9 from the site and through composer.

Or am I missing something here?

This is causing a bit of trouble with step 4 in the install process:

  Download the latest version of Craft from craftcms.com, and copy its craft/app/ folder into happylager/craft/.


texts:
Trying to search through a Matrix field, currently I am using conditionals to accomplish this, but if it's faster would like to limit the results to only what I need.

{% for row in entry.matrixField.search(matrixChild1:"mykeyword") %}

{% set getResults = row.matrixChild1.one.slug %}

{% endfor %}

I could not find much on this, I know a search() parametered can be used in Matrix but after all my trying still nothing.  Hopefully it's possible?


texts: How to handle top-level/index pages in structure sections?

texts:
It seems that currently if you want to avoid the main "about" page at the top of an "about" structure having a slug of /about/about/ then the approach people seem to take is to create an About page as a single, and a separate structure for subpages.

An alternative approach that occurred to me is to give the structure section a URL of just {slug} and then make everything a child of the "About" entry. Is there any particular disadvantage to doing this though?

I can see that it potentially allows URLs from different structures to clash (if someone creates a new top-level entry in a structure), but my feeling is that if I have to choose, the possibility for users to mess up the structure seems less bad than the probability that the "separate single + structure" approach will be confusing for users. Is there some other disadvantage that I'm overlooking here, though?


texts: Outputting Year of Entry Group alongside Month

texts:
I have this piece of code which orders my entries by month, which is working great. I only have two issues which I can't work out. How would I display the year of the month beside the month title eg:

{{ month }} > {{ year }}

As the list could run over a number of years it would be good to distinguish this. The next part is I can't seem to convert the month from a number ie: 8 to the word ie. "august". When I filter it, it just returns "Jan".

{% set allEntries = craft.entries.section('featureArticles').find() %}
{% set allEntriesByMonth = allEntries|group('postDate.month') %}

{% for month, entriesInMonth in allEntriesByMonth %}

{{ month }}

        {% for entry in entriesInMonth %}

{{ entry.title }}

        {% endfor %}

{% endfor %}


texts: How secure is Craft and why is it secure?

texts:
What measures have been put in place in regards to securing Craft at the core level.
What measures have been put in place in regards to Craft's Plugins which make use of (connect to if you will) Craft's core?
If possible (without an opinion piece being written), is there anyway to make a comparison between other popular CMS and Craft in regards to security?
How does one know third party libraries which are used in Craft are secure?
Craft is built on Yii PHP Framework and Twig. How secure are these?
Has Craft ever had any security incidents to date?
In the case there is a security incident how does the team at Craft notify people such incident occurred?
How safe is auto-updating within Craft?


texts: Updating uploaded assets directory structure

texts:
How can i update uploaded assets directory structure, when i change assets field "Default Asset Location" settings - so files match this new setting?
I have so much files all in one directory that they hang browser when i open asset explorer app.


texts:
I'm having an issue where the admin is kicking a user out after an indefinite period of time. The corresponding error message is

Tried to restore session from a cookie, but the given hashed database token value does not appear to belong to the given login name. Hashed db value: 5740fb357a555db6a1ee9e9ea2160179daeed342czozMjoiWjdzUk94ZHVSZGJlMEVOT2JyUFJxcmxkY01FeGhoeU0iOw== and loginName: omitted for stack exchange.

A few minutes later I see another error:

2016/01/19 21:53:16 [error] [application] Tried to read the folder contents of /home/domain.com/craft/storage/runtime/cache/, but could not.
2016/01/19 21:53:16 [error] [application] Tried to read the folder contents of /home/domain.com/craft/storage/runtime/assets/, but could not.
2016/01/19 21:53:16 [error] [application] Tried to read the folder contents of /home/domain.com/craft/storage/runtime/temp/, but could not.

My craft directory is installed above my public_html directory.

Here are some things I've tried:

Verified permissions [755] for the app, config and storage directories.
Set overridePhpSession = true
Set userSessionDuration = false

I have not been able to duplicate the error, so at this point I would have to say the error is only effecting 1 user. I had him try a different browser (chrome was previously using IE) and clear his cookies as well. The error still happened in chrome.

Any suggestions you have are appreciated.


texts:
Say I'm building a plugin that adds user memberships to the website. I want to check on my front end templates that user's membership is active and I have built the functionality inside the plugin to do this.
How do I use a tag like {% requireMembership %} in place of the normal {% requireLogin %} to call the function that I've built? I thought it would be simple but can't find documentation on this anywhere.


texts:
I've got a question that I can't seem to get fixed all by myself... I've got a search form and each entry has got field with some checkboxes (in this case these are options). Now I'd like to search when they check multiple checkboxes but I can't seem to get that to work...
I've set up a form in which I'm fetching a parameter and just to test it with 2 checkboxes checked I've split them up in 'week1' and 'week2' like so:

{% set week_search_query =  week1 ~ ' ' ~ week2  %}

I've tried the same with 'and' and '&' in between the quotes but can't seem to get it to work, while with the 'week1' alone like so:

{% set week_search_query =  week1 %}

it works perfectly. (if I print out the content of 'week_search_query' in this case I get

  weken2017:41

with weken2017 as fieldname and 41 as value).
But what I'd like to to is search by 2 checked checkboxes at once as in the first example, so I can:

craft.entries.search(week_search_query)

All help is welcome, I feel like quite a newbie ATM :-)


texts: LDAP connects but fails to return entries

texts:
I am developing a plugin. In local environment if works fine. On the real server it fails, returns 0 entries. The method is called from a template:
ret = "{{craft.nastupy.hledanizamestancu('"+retezec+"', 0) }}"//hledanizamestancu
alert("ret " + ret)

It resides in /variables, and goes like so:
public function hledanizamestancu($retezec) {
  //error_reporting(0);
  $ldap_dn = "intentionally left blank";
  $ldap_password = "so is this";
  $ldap_conn = ldap_connect("and this", 389);
  //print($ldap_conn);
  ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
  ldap_set_option($ldap_conn, LDAP_OPT_DEBUG_LEVEL, 7);
  ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, true);

  if (@ldap_bind($ldap_conn, $ldap_dn, $ldap_password)) {
      echo ldap_error($ldap_conn);
      $dn = "blank once again";
      $filter = "(displayName=*".$retezec."*)";
      $justthese = array("displayName", "email");
      $result = ldap_search($ldap_conn, $dn, $filter, $justthese);
      $entries = ldap_get_entries($ldap_conn, $result);
      $vystup = "";
      foreach ($entries as $e) {
          print("e ".$e);
          if (isset($e['email'][0]) && isset($e['displayname'][0])) {
              $vystup .= $e['displayname'][0].",";
          }
      }
      print("vystup " .$vystup. " konec");
  } else {
    print("I should never ever see this.");
  }
}

I tried both displayname of displayName in the foreach loop, but they fail both. I also tried AJAX directly from JS. Same story. It works in local environment just fine but fails on the server.
Thank you.


texts: How to install Craft 3 on shared hosting

texts:
I would like to learn Craft 3 CMS.

I would like to do so by installing it manually on shared hosting. I am not familiar with Composer and would like to learn Craft before committing to learning Composer.

I do not understand some of the steps given at:
https://docs.craftcms.com/v3/installation.html

So I searched for manual installation of Craft 3 on shared hosting on the net and did not find any helpful articles. Examples on the net are based on using Composer or Craft 2 or using a local dev environment, etc.

So I have come here hoping that some people will help me out with the steps I don't understand at:
https://docs.craftcms.com/v3/installation.html

Here we go:

  Extract the archive wherever you want your new Craft project to
  live.

In my case my shared hosting provides me with the following directory structure:

/home/[accountname]/public_html

I am used to developing with Wordpress and if I use shared hosting I will simply put all of WP in a folder named the same as the domain, eg:

/home/[accountname]/public_html/example.com

So I am not sure where I should upload the Craft files to, also because of the next step below.

  Directory Structure

  Once Craft’s files are in place, your project directory should have a
  directory structure like this:

my-project.test/
├── config/
│   └── ...
├── storage/
│   └── ...
├── templates/
│   └── ...
├── vendor/
│   └── ...
├── web/
│   └── ...
├── .env
├── .env.example
├── composer.json
├── craft
└── craft.bat

  TIP

  The web/ folder represents your site’s webroot, and it can be renamed
  to whatever you want (www/, public/, public_html/, etc.). "

If I were to install these files in eg:

/home/[accountname]/public_html/my-project.test/

Then this becomes confusing to me because I once managed to install Craft 2 on shared hosting and Craft 2 installation instructions made it clear that I had to install most of Craft 2 above the webroot:

/home/[accountname]/craft/

And I had the craft webroot at
/home/[accountname]/public_html/craftsite/

But if I upload craft to:

/home/[accountname]/public_html/my-project.test/

Then obviously all of Craft is under not above the webroot. I imagine this could be very insecure....

But the Craft 3 instructions do not mention that I need to install some folders above the webroot.

I also feel I have 2 webroots now:

My shared hosting tells me that I have a webroot at:
/home/[accountname]/public_html/

While Craft is saying my webroot is:
/home/[accountname]/public_html/my-project.test/web/

Maybe I need to install Craft 3 above the webroot, eg:

/home/[accountname]/my-project.test/

And then the Craft webroot would be:

/home/[accountname]/my-project.test/web/

But I also have a webroot at:

/home/[accountname]/public_html/

So now I also have 2 webroots....

  Step 5: Set up the Web Server

  Create a new web server to host your Craft project. Its document root
  (or “webroot”) should point to your web/ directory (or whatever you’ve
  renamed it to).

I my case I dont believe I can create a web server - I am stuck with the shared hosting server.

So I am not sure how to handle this step.

I am sorry if I am missing some very obvious things here.....

Any help would be very much appreciated.....


texts:
Problem
CP assets uploads are reverse ordered after upload.
Description
I have a folder with 5 images:

1.jpg
2.jpg
3.jpg
4.jpg
5.jpg

I want to upload these images in the Craft CP. I have an Asset field and add the images by clicking the ‘Add an asset’ button. When I'm done the order of the images in the field is:

5.jpg
4.jpg
3.jpg
2.jpg
1.jpg

Example
Before upload:

After upload:

Question
Is there a way to upload assets in the same order?


texts: Garnish event when changing category group

texts: When I am on the categories index (admin/categories), is there a Garnish event that fires when you select a different category group in the sidebar? I want to add some custom JS after the AJAX request completes and the elements have been added to the page.


texts: Use blog index template as category template

texts:
I have a blog listing page which works correctly. I also have categories that I would like to use the same template rather than creating a whole new template since the design is exactly the same.

However when I set the category template to blog/index the page loads correctly but doesn't limit by categories.

Looking at my simplified template code, I'm not sure how to get it to display only the category being viewed or all if on the blog index page.

My urls are

/blog/
/blog/p2 (pagination)
/blog/{{ slug }}

I would like the following url's to use the same template code:

/blog/category/{{ category_url }}
/blog/category/{{ category_url }}/p2

My template code:

{% paginate craft.entries.section('blog').limit(6) as pageInfo, pageEntries %}
{% for entry in pageEntries %}

    some code

      more code

    Keep Reading

{% endfor %}

If necessary I can create a category.html template, but then I'd essentially have duplicate code. Is there a way to do what I want to?


texts: Applying project config changes with post-receive git hook

texts:
I site I'm working on uses a post-receive git hook for deploying changes to the server.

At the moment, it looks like this:

#!/bin/sh

# default cpanel stuff
branch=$(/usr/local/cpanel/3rdparty/bin/git branch | awk '$1 == "*"{print $2}')
while read oldrev newrev ref
do
  if [ "x$ref" == "xrefs/heads/$branch" ]
  then
    echo "Recieved update on checked-out branch, queueing deployment."
    (cd .. ; /usr/bin/uapi VersionControlDeployment create repository_root=$PWD)
  fi

  branch=`echo $ref | cut -d/ -f3`

  cd ../
  # run from dir outside of .git
  # unset git dir because git ugh https://stackoverflow.com/a/10513684
  unset GIT_DIR

  if [ "master" == "$branch" ]; then
    # echo this is master
    # create new working tree in the desired directory
    git --work-tree=../prod-test checkout -f $branch
  fi

  if [ "develop" == "$branch" ]; then
    # echo this is develop
    git --work-tree=../staging checkout -f $branch
  fi

done < /dev/stdin

That works fine. I push from my local and the changes get deployed to staging.

But I want project config and plugin update changes to be automatically applied rather than having to visit the CP and click the sync changes button.

I've seen elsewhere that the way to do that is to run

  ./craft project-config/sync
  ./craft clear-caches/all
  composer update

so I thought I could add it to the hook, just above done < /dev/stdin but it doesn't work, I still have to manually update.

Has anyone else done something like this before?


texts: Matrix getBlockTypesByFieldId() function doesn't work as intended?

texts:
One of the functions in a plugin that I'm working on, is the ability to create fields. It has created a Matrix field, and directly after that, I want to know the MatrixBlockType.

I don't get any results if I use the following code:

$blockTypes = craft()>matrix>getBlockTypesByFieldId($newField->id, 'handle');

However, if I do the exact same thing as the above function should do, and run this code I do have results:

$results = craft()->db->createCommand()
->select('id, fieldId, fieldLayoutId, name, handle, sortOrder')
->from('matrixblocktypes')
->where('fieldId = :fieldId', array(':fieldId' => $newField>id))
->order('sortOrder')
->queryAll();

If you would debug both variables, you'll notice that the first one doesn't contain any data.

If I would be creating the fields and in later server request I would use the first example, I do receive the data. Somehow it's not available right after creating the field.

Can anyone help me out here by any chance? I want to use the first example, which is the correct way.


texts: Passing variables to email template not working

texts:
I am building a Craft plugin which sends emails to users of a subscribed list. I'm trying to get Craft to send the email with a Twig template and pass in variables to that template.

So far I've been able to get the Twig template working properly, except I'm having issues displaying the variables heading and content in my template. They are returned as plain text.

Here's my code for sending the email.

$mailer = Craft::$app->mailer;
$mailer->htmlLayout = false;
$mailer->textLayout = false;
$mailer->setViewPath('@templates');

$mailer
   ->compose('emails/default.twig', [
      'heading' => $list->subject,
      'content' => "Something new has been posted on the Harvest Youth blog. url}'>{$entry->title}",
   ])
   ->setTo($subscriber->title)
   ->setSubject($list->subject)
   ->send();

Here's how I'm trying to use the variables in my Twig template.

{{ heading }}

   {{ content }}

And here's how the email template is returned.

I'd appreciate any help as I'm new to Craft plugins and I'm not fantastic with Twig either.


texts: Commerce: are Shipping prices always assumed to include tax?

texts:
A client is asking if the order calculation can show a 20% tax calculation on the shipping price.
From looking through Commerce 3, it seems this isn't possible, eg Shipping prices are always assumed to be inclusive of tax?


texts: Is there any way to include Solspace Calendar events in a global site search?

texts:
I have a client that wants their Solspace Calendar Events to show up in the global site search results (along with entries from other sections)

My first thought was to query the entries and calendar events separately, merge the result sets together, and then paginate them. Basically this: Merge Craft entries and Venti events in search results

Unfortunately that doesn't seem to work. Is there any way to accomplish this?


texts: Possible to get content block from another entry?

texts:
I guess this isn't possible as it would mean the content is essentially a Global, but I would like to be able use a block from a matrix field from another entry.

At the moment I have a parent page with a block of content, which I would like to replicate on all of it's child pages. I don't want to make the user repeat it on each child page, but I don't want to hardcode it.


texts: Where does Craft store the field definitions?

texts:
I would like to add field and section definitions to versioning. Or at least, have them backed up constantly.

I haven't been able to find out yet how craft handles this. I'd say it's in the database, but apparently it's not: the database has a uid column where values like 305ed8b6-3519-422f-8436-eca448145656 are stored. This probably refers to some git-ish entries in the file system.

So is this out of reach for manual save/restore/export/import?


texts:
I'm essentially in the process of learning Craft and in that process have made some great strides.

Today I was examining Craft's tables to see how it was actually storing fields created through Settings-> fields. To my surprise most fields end up as a new column in the content table. To me this seems like a serious flaw as there is a very real limit to the size a table can grow to.

Given this information; what is recommended for developing a site in Craft that needs to have many fields?

If you have an answer I'd appreciate it. Please make it detailed. I'm at a loss with this one. Hopefully there is something I'm missing because if no... Craft may not be the solution I'm looking for. Which would be unfortunate.

Thanks


texts:
I was wondering if there 's a quick way to just set a locale in your template for example:

{% set locale = 'en' %}

and then use that locale to get the correct content. I know that Craft automaticly uses the right locale based on the url, but I'm importing some templates from Craft with curl into another site and so the Craft template is unaware of the locale. That's why I would like to set it, if possible without the use of an extra plugin.


texts: Can someone help me identify why my entry is invalidating?

texts:
I have a custom plugin that's saving an entry successfully. While saving the entry I'm setting our "merchant" field (an entries field, limit=1) like so:

<?php
# ...
$entry = newEntryModel();
# set the sectionId, typeId, authorId, and some other fields...
$entry->getContent()->merchant = (isset($data['merchant']) ? [$data['merchant']->id] : null; // $data['merchant'] is an EntryModel

This appears to be fine in the CP. I can see and edit the related entry.

However later in the application I have to update this entry and when updating the entry, I'm only updating a single field. While debugging the EntryModel that I'm trying to save I see that if I var_dump $entry->merchant I get an ElementCriteriaModel yet when I dump $entry->getContent->merchant I get 'null'.

My log shows the following error:

  2014/10/31 18:25:46 [warning] [application]
  Craft\ContentModel->merchant failed validation: Merchant cannot be
  blank.

According to this tweet it seems like dumping $entry->getContent()->merchant should be returning a ContentModel instead of null.

Any ideas?

EDIT: I've confirmed that everything works as expected if the field is NOT marked as required. However, this can't really be a solution - I need to make sure that the client cannot leave this field blank.


texts: I am hoping to write a plug-in to cache pages as static HTML. Is there a hook that would give me access to the full rendered HTML of a page?


texts: General question: Has anybody ever used Craft along with ElectronJS to create a native based app?

texts:
Just wondering if anybody has ever used Craft as a platform along with using something like ElectronJS to move a PWA to a native based app for windows or mac?

Is this possible I wonder? Has anybody come across any articles about this?

Thanks!


texts: Using imageoptimize plugin not showing field on entries

texts:
In Craft CMS, I am using the imageoptimize plugin to optimize images. I have added field imageoptimize & in assets created volume added field in field layout but when I am adding entry it showing me the message 'OptimizedImages fields only work when added to an Asset Volume's layout.'.

I am using Craft CMS version 3.024 and ImageOptimize plugin version 1.4.38.
Why is the field not showing up?


texts: How do you template an IF statement to avoid an error if an image is not assigned

texts:
Here is my templating...

      {% if entry.programImage %}
        <img src="{{ entry.programImage.one().getUrl() }}" alt=""/>
      {% endif %}

The field programImage is NOT required.

The image does display for entries that have it.
It throws an ERROR for those that do not.

The ERROR message is as follows.

Impossible to invoke a method ("getUrl") on a null variable.

What am I missing?

Thanks


texts:
Is there a way to direct Craft to include entry.postDate in the search? I'm using a simple query to search entries.
{% set entries = craft.entries.section('mySection').search('*' ~ query ~ '*').limit(null) %}


texts: How to get field values from Global Set using Element API plugin?

texts:
I'm pulling data from a Global Set using the Element API plugin and am wondering if there's a cleaner way to write the transformer function?

My craft/config/elementapi.php file looks like this:

<?php
namespace Craft;

return [
    'endpoints' => [
        'api/settings' => [
            'elementType' => 'GlobalSet',
            'criteria' => ['handle' => 'siteSettings'],
            'first' => true,
            'transformer' => function(GlobalSetModel $siteSettings) {
                return [
                    'defaultTitle' => $siteSettings->getContent()['defaultTitle'],
                    'defaultDescription' => $siteSettings->getContent()['defaultDescription']
                ];
            },
        ],
    ]
];

Thanks in advance!


texts: Saving a "craft-linkfield" field via an entry form

texts:
I'm editing an entry via an entry form as documented here:
https://docs.craftcms.com/v3/dev/examples/entry-form.html

How would I be able to save a link field that's using https://github.com/sebastian-lenz/craft-linkfield ?

I tried this:

<input id="website" type="text" name="fields[website]">

(where "website" is the handle of the link field) but that just throws a syntax error (in json_decode) at vendor/sebastianlenz/linkfield/src/fields/LinkField.php:112

It works fine for other  elements that use one of the built-in field types.

Is this even possible using the standard entries/save-entry endpoint? Or would I need to write a custom controller, and how so?


texts:
Working on site where there is events calendar of conferences and webinars. Users are (literally) all over the world. Trying to figure out how I am going to handle time zones. Factors:
- Fields I am using are two Date/time fields for start and end time + one lightswitch for all day events
- Content editors will inevitably want to input dates for where they are happening. If the conference is in Paris at 9am they want it to show Paris 9am no mater where website user is in world
- For webinars, they have opposite issue. They want the time shown to be relative to user's timezone.
- Users can download ICS link

Has anyone developed a solution to this that works for users and content editors?


texts: Create an Array in Twig and loop through fields in global set

texts:
So I've created a globals set (socialMedia) with 10 input fields, but this could grow in the future, for clients to add links to various social media accounts. This works fine except that the code for this seems overly long and reptitive since I need to put a conditional to check if each field has been output. Like this:

  {% if socialMedia.facebook | length %}

  {% endif %}

  {% if socialMedia.twitter | length %}

  {% endif %}

  {% if socialMedia.flickr | length %}

  {% endif %}

  {% if socialMedia.instagram | length %}

  {% endif %}

  {% if socialMedia.email | length %}

  {% endif %}

  {% if socialMedia.vimeo | length %}

  {% endif %}

  {% if socialMedia.youtube | length %}

  {% endif %}

  {% if socialMedia.linkedin | length %}

  {% endif %}

  {% if socialMedia.tumblr | length %}

  {% endif %}

  {% if socialMedia.googlePlus | length %}

  {% endif %}

  {% if socialMedia.dribble | length %}

  {% endif %}

Ideally I could set an array and then do a for loop and output everything as needed in a couple of lines. However I'm not sure how to proceed with that or if it is even possible.


texts: How can I get the fields of a matrix field? I want to loop through the fields. I have the fields of the section, if the field.handle is of type matrix, I want to get the fields of the matrix.


texts: error in production when using redis for cache and session

texts:
I've added this to the array that is returned in config/app.php:
'components' => [
        'redis' => [
            'class' => yii\redis\Connection::class,
            'hostname' => App::env('REDIS_HOST'),
            'port' => APP::env('REDIS_PORT'),
            'password' => ''
        ],
        'cache' => [
            'class' => yii\redis\Cache::class,
            'defaultDuration' => 86400,
            'keyPrefix' => App::env('APP_ID') ?: 'CraftCMS',
        ],

        'session' => function() {
            // Get the default component config
            $config = App::sessionConfig();

            // Override the class to use Redis' session class
            $config['class'] = yii\redis\Session::class;

            // Instantiate and return it
            return Craft::createObject($config);
        },

    ]

This all works find when my environment is in dev and devMode is on.
When I switch to production, I get an internal server error. I don't know what the issue is because it doesn't give me the full logs.


texts:
I'm needing to add a dynamically added dropdown input field for my form, as is commonly done with javascript.  How would this be possible?

In other words, there may be more than 1 dropdown desired by the user, and I need a link or button that would create any additional desired dropdown inputs.

Thanks


texts: Plugin eager loading not loading relations

texts:
I have a plugin with two records with the relationships as follows:

Placid_EndpointRecord

public function defineRelations()
{
    return array(
        'resource' => array(static::BELONGS_TO, 'Placid_ResourceRecord', 'required' => false, 'onDelete' => static::SET_NULL)
    );
}

Placid_ResourceRecord

public function defineRelations()
{
    return array(
        'endpoints' => array(static::HAS_MANY, 'Placid_EndpointRecord', 'resourceId'),
    );
}

In a service class I have (options being an empty array at this point):

return Placid_ResourceRecord::model()->with('endpoints')->findAll($options);

When I dump the response from the service method i'm getting back is:

Craft\Placid_ResourceModel Object
    (
        [classSuffix:protected] => Model
        [strictAttributes:protected] => 1
        [_classHandle:Craft\BaseModel:private] =>
        [_attributeConfigs:Craft\BaseModel:private] => Array
            (
                [id] => Array
                    (
                        [maxLength] => 11
                        [min] => -2147483648
                        [max] => 2147483647
                        [decimals] => 0
                        [type] => number
                        [unsigned] =>
                        [length] => 10
                        [column] => integer
                    )
                [name] => Array
                    (
                        [type] => string
                    )
                [handle] => Array
                    (
                        [type] => string
                    )
                [host] => Array
                    (
                        [type] => string
                    )
            )

        [_attributes:Craft\BaseModel:private] => Array
            (
                [id] => 1
                [name] => Foo
                [handle] => Bar
                [host] => Bar
            )

        [_extraAttributeNames:Craft\BaseModel:private] =>
        [_errors:CModel:private] => Array
            (
            )

        [_validators:CModel:private] =>
        [_scenario:CModel:private] =>
        [_e:CComponent:private] =>
        [_m:CComponent:private] =>
    )

There doesn't seem to be any hint of the endpoints relation, there is definitely a row in the related table but even if not i'd expected to see an empty array of some sorts.

Is there anything i'm missing or doing wrong? I looked at some of the core files and it seems the records are set up the same way for similar relations and I get no errors so i'm a bit clueless as to what's going wrong. Any help would be awesome, thank you!


texts: CraftCMS > UserSessionService should be compatible with CWebUser

texts:
I've migrated my Craft project from CentOS/PHP5 to Ubuntu/PHP7 ---  since then I'm seeing this message in /craft/storage/runtime/logs/phperrors.log

[14-Jun-2017 14:40:49 UTC] PHP Warning:  Declaration of Craft\UserSessionService::login($username, $password, $rememberMe = false) should be compatible with CWebUser::login($identity, $duration = 0) in /home/hidden/craft/app/services/UserSessionService.php on line 17
[14-Jun-2017 14:40:49 UTC] PHP Warning:  Declaration of Craft\UserSessionService::afterLogin() should be compatible with CWebUser::afterLogin($fromCookie) in /home/hidden/craft/app/services/UserSessionService.php on line 17
[14-Jun-2017 15:50:53 UTC] PHP Warning:  Declaration of Craft\UserSessionService::login($username, $password, $rememberMe = false) should be compatible with CWebUser::login($identity, $duration = 0) in /home/hidden/craft/app/services/UserSessionService.php on line 17
[14-Jun-2017 15:50:53 UTC] PHP Warning:  Declaration of Craft\UserSessionService::afterLogin() should be compatible with CWebUser::afterLogin($fromCookie) in /home/hidden/craft/app/services/UserSessionService.php on line 17
[14-Jun-2017 16:03:04 UTC] PHP Warning:  Declaration of Craft\UserSessionService::login($username, $password, $rememberMe = false) should be compatible with CWebUser::login($identity, $duration = 0) in /home/hidden/craft/app/services/UserSessionService.php on line 17
[14-Jun-2017 16:03:04 UTC] PHP Warning:  Declaration of Craft\UserSessionService::afterLogin() should be compatible with CWebUser::afterLogin($fromCookie) in /home/hidden/craft/app/services/UserSessionService.php on line 17

Any Help?


texts: Is it possible to image upload on a particular size using a control panel?

texts: I am using the commerce plugin. I want to display an image of the specific size without CSS is there any specific way in the commerce plugin?


texts: Different unix users for Craft config and Craft process

texts:
I want to configure Craft to run as user craftcms and have configuration owner craftowner. The purpose is to make configuration read-only to craftcms, so that there can be no changes to the configuration via the interface. We will pull config updates from a git repo.
Is there a canonical guide for implementing this setup? If not, has anyone determined what permissions are required?


texts: Craft 2.5 option to embed image with transform missing

texts:
I know Craft 2.5 uses Redactor II so I assume this problem relates to this, but it would be good to get this confirmed.

Setting aside the fact you need to update the configs, I have noticed the ability to embed an image (in a Rich Text field) with a transform is no longer an option.

In Craft 2.4 there was another button adjacent to the Select button to upload an image with a pre-defined transform. This is missing.

I have also noticed that the image select modal does not close once an image is selected either by double-clicking it or pressing the select button.

Is anyone else experiencing the same issues?


texts: Can I store Assets on a Cloud Service like Amazon S3?

texts: Is there any way to store Assets on a Cloud Service?


texts: 400 bad request ("Unable to verify your data submission.") when Adding product to cart

texts:
When a user tries to add something into the cart the following error appears:

400 bad request ("Unable to verify your data submission.")

2021-02-23 09:08:42 [-][-][fff512a7677a0fcf3272bd46e2fc3270][error][yii\web\HttpException:400] yii\web\BadRequestHttpException: Ihre Dateneingabe konnte nicht überprüft werden oder ist ungültig. in /path/vendor/yiisoft/yii2/web/Controller.php:202
Stack trace:
#0 /path/vendor/craftcms/cms/src/web/Controller.php(138): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))
#1 /path/vendor/yiisoft/yii2/base/Controller.php(178): craft\web\Controller->beforeAction(Object(yii\base\InlineAction))
#2 /path/vendor/craftcms/cms/src/web/Controller.php(190): yii\base\Controller->runAction('update-cart', Array)
#3 /path/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('update-cart', Array)
#4 /path/vendor/craftcms/cms/src/web/Application.php(274): yii\base\Module->runAction('commerce/cart/u...', Array)
#5 /path/vendor/craftcms/cms/src/web/Application.php(577): craft\web\Application->runAction('commerce/cart/u...', Array)
#6 /path/vendor/craftcms/cms/src/web/Application.php(253): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#7 /path/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#8 /path/www/index.php(32): yii\base\Application->run()
#9 {main}
2021-02-23 09:08:42 [-][-][fff512a7677a0fcf3272bd46e2fc3270][info][application] $_GET = [
    'p' => 'shop/product'
]

$_POST = [
    'action' => 'commerce/cart/update-cart'
    'redirect' => 'cbfe8c19da16c2536194408ca0939abfb84103fa6f70889e9e9bddc69715bd14purchase/cart'
    'qty' => '1'

It only happens when the browser is kept open for a long time. So I guess the token is renewed on the server but the old token is still in the browser.
Is there a way to remove the old token brom the client?

The Blitz plugin installed which caches the product page (But not the cart)
There is also a Cloudflare in front of the webpage.

I guess these caching products add to this complexity. Cloudflare might be involved in this as well or probably the main contributor.
Anyone experienced this?


texts: Multi-Environment Config Database Credentials

texts:
Being driven to distraction trying to setup multiple environments with Craft. I have Craft running (and working) locally without issue. I have created a staging server with Digital Ocean and setup the appropriate database. I'm using DeployBot to push changes from Github.

However upon trying to access the remote server, I get the following errors:

  Service Unavailable

  Our site is temporarily unavailable. Please try again later.

and

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

I'm sure there is an obvious solution to why this isn't working, but I'm yet to find it.

Here are my db.php and general.php files with sensitive data redacted:

db.php

return array(
  '*' => array(
    'database' => '******',
    'tablePrefix' => 'craft',
  ),

  'localhost' => array(
    'server' => 'localhost',
    'user' => 'root',
    'password' => 'root',
  ),

  // Use IP of your droplet and MySQL credentials of a user you created
  '000.000.000.000' => array(
    'server' => '000.000.000.000',
    'user' => 'root',
    'password' => '***********',
  )
);

config.php

<?php

return array(
    '*' => array(
        'omitScriptNameInUrls' => true,
        'devMode' => true,
        'loginPath' => 'users/login',
        'postLoginRedirect' => 'commerce/customer',
        'setPasswordPath' => 'users/setpassword',
        'enableCsrfProtection' => true,
    ),

    '000.000.000.000' => array(
      'siteUrl' => 'http://000.000.000.000/',
      'environmentVariables' => array(
        'basePath' => '/var/www/html/',
        'baseUrl' => 'http://000.000.000.000/',
      )
    ),

);

Also index.php file for good measure

<?php

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

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

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

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

require_once $path;

Help needed and much appreciated!


texts:
I am running into problems with virtual hosts while trying to run Craft locally.
My setup was working perfectly and after a restart of my mac I get error messages and I don't understand why.

I am using Mamp to run Apache and MySQL.
When I am going to one of my virtual host url I get the following error:

And when I type 'localhost' I get the following:

I have double checked the httpd.conf and the virtual hosts is enabled and my httpd-vhosts.conf is set up correctly as well.

I assume there is a certain issue with the virtual hosts as but I just cannot figure it out and it stop working without any changes/updates form my side so I'm really loosing it...

Does any one has an idea where to start searching for the problem?


texts:
How can I access plugin settings in the template?

I have config.php file defined in plugin directory and i want to access these values (or their overwritten values) in Twig templates.

I tried {{craft.pluginHandle.getSettings}} but it didn't work, it throws an error that such a method does not exist.


texts: SQLSTATE[23000]: Column 'targetId' cannot be null

texts:
I'm getting the following error whenever I try to post a new entry to one of my channels in Craft:

2015/10/26 14:42:36 [error] [system.db.CDbCommand] CDbCommand::execute() failed: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'targetId' cannot be null. The SQL statement executed was: INSERT INTO `craft_relations` (`fieldId`, `sourceId`, `sourceLocale`, `targetId`, `sortOrder`, `dateCreated`, `dateUpdated`, `uid`) VALUES (:row0_col0, :row0_col1, NULL, NULL, :row0_col4, :row0_col5, :row0_col6, :row0_col7).

From what I can tell, the error is being triggered by the asset field in the section. I'm posting a JS created File to the asset field, not a file from a file input (which works fine during testing). The image file being posted is built from a Data URI which is converted to a Blob, and is then converted to a file. This is rather hacky*, but the best way I could find to successfully (as far as I can tell) post an image to Craft.

Is it possible that some important metadata is being left out when the image file is created, that is causing this error? Or is it a case of the image not being saved before the entry in time for this relation to be created, or vice versa?

*My reason for doing this is because the images are from a mobile phone camera, everything is being posted from a Cordova app.

Edit 1:
From the app I'm posting directly to Craft with Ajax using the entries/saveEntry action. But this is being routed via a plugin I wrote to allow me to use JWT based authentication. I've had no issues with this during testing, only when I switched from using a field input to generating the files via JavaScript has this error started occurring.

Edit 1.5:
I've managed to fix the issue. See below.


texts:
We're developing a new site using Craft. When I'm at work I can save all the work I have done on the site fine. But when I'm at home (using BT broadband), my ability to save any edits I make to the site is very patchy - sometimes it works O.K., more often than not I get the following error message:

  The site can't be reached; The connection was re-set

I've tried using Chrome and Firefox - but same thing happens.

Any ideas?  I'm not a web-expert so answers in layman's terms much appreciated!


texts: Show on user profile page the commissions he is connected to

texts:
I have a commissions section in where we have a matrix field where we add the user (from craft.users) and the function of the user.

A user can be in more that one commissions.

On the user profile page, we want to show besides some personal information, all the commissions in which he is active.

For a single relation field (user type field), we have no problem, but I can't get it working with this matrix field.

Matrix field info:

Section: commissionmembers
Blocktype: members
Fields: member (fieldtype users)
        function (plain text)

This is a working example with a Users field

    {% for user in craft.users.id( craft.request.lastSegment ).limit(1) %}
    {% set commissions = craft.entries.section('commissions').relatedTo(user) %}
        {% for commission in commissions %}
            {{ commission.title }}
        {% endfor %}
    {% endfor %}

Hope you can point me in the right direction how to get it working with the matrix field


texts: Ability to filter products inside Craft Commerce Admin?

texts:
I have multiple sub product types under the same product type in Craft Commerce. They are categorized by a category.
Is there a way (plugin?) to get this kind of filtering?
I see there is a discontinued plugin called CategorySources, and the question has been raised before - but it just links to the CategorySources plugin.


texts: Im building a form in freeform and it is going to contain many state select dropdown fields. Is there any way to duplicate this field so I do not have to populate the options/values manually every time I use that field?


texts: Grouping Super Table Results via Twig Multidimensional Array

texts:
I'm trying to loop through a Super Table array and group results based on a category ('contribution'). I've gotten pretty far but I'm struggling creating an array in Twig that gives me what I need (I find associative arrays very cumbersome in Twig after using PHP for so long...).
Setting the contribution works. I just can't seem to write the merge rule correctly so each contributor merges into their respective role. The next step would to then join together the list of names for further output...
Here is where I am currently stuck:
  {% set featuredContributors = [] %}

  {% for person in book.contributors.all() %}
    {% if person.featured == 1 %}
      {% set contribution = person.contribution.one().title %}
      {% set contributor = person.contributor.one().title %}
      {% set featuredContributors =
        featuredContributors |
          merge({
          (contribution): [contributor]
          })
      %}
    {% endif %}
  {% endfor %}

The resulting array should look like (with each array joined as a comma separated list):
{% set featuredContributors = {
  Editor: 'Person One, Person Two',
  Writer: 'Person Three, Person Four',
  Other Role: 'Person Five',
} %}

Is there an easier way to do this? PHP via a Twig Extension? :D


texts: Craft Licensing and Multiple Environments on Different Domains

texts:
It isn't currently clear how licences work with dev, staging and live environments or to be clearer how it works with different domains.

I have the following domains setup for different environments.

Local: name.test
Staging: sub.domain.co.uk
Preproduction: domain.co.uk
Production: livedomain.com

But this can't be configured on the Craft ID site as far as I'm aware? This also results in Licence Errors across staging and preproduction environments.

Is there a solution to what I'm describing?


texts: How do you add a core twig extension in plugins using addTwigExtension()?

texts:
Is it possible to activate the following Twig extension from within a craft plugin:

http://twig.sensiolabs.org/doc/extensions/date.html


texts: User group discount not applied when user has existing cart

texts:
I've run accross an issue that seems like a bug to me and I'm desperately looking for some help to solve it.

I've created user groups in Craft & Discounts applicable to those user groups in Craft Commerce.

a user lands on the site and adds items to his cart & proceeds to checkout
the user is prompted to login or register
the user logs in OR registers
3a. upon registration the user is activated & auto logged in with the 'autoLoginAfterAccountActivation' => true config option
the user is redirected back to his cart - at this point in time I'm expecting to see a discount adjustment on the cart

The problem is that there is no discount adjustment on the cart - the only way the discount adjustment kicks in is if the cart is updated, by adding or removing an item ie: updateCart is fired.

I've double checked my discount rules & they are definitely setup correctly - the problem is that the users cart is "remembered" from before he was registered ie: before he was part of a user group that is eligible for a discount.

I'm looking for a way to "force" a cart refresh of some sorts.


texts: Using search to display entries based on a value in a number field

texts:
I'm trying to return results based on a year stored in a custom field. For example, returning entries with a model year greater than 2006 and less than 2009. Is there a search syntax to support this?

For example: for entry in craft.entries.section('equipment').search(modelYear: > 2006 && < 2009) …


texts: Sprout plugin: Send information in AJAX success response

texts:
I'm using Sprout for registering to events, I want to be able to send a code in the AJAX response when EVENT_AFTER_SAVE occurs. At the moment, I get {success: true} back, but I want to be able to get {success: true, code: "XXXXX"} after save

The code will be coming from a Channel called Tokens, which consists of one field: tokenCode. I want to grab one at random and send tokenCode as "code"

This is what I want my AJAX request to be, note var redirect = '' + data.token

$('#token-form').submit(function(event) {
  event.preventDefault();
  // prepare some variables
  var postUrl = 'sprout-forms/entries/save-entry';
  var formData = $(this).serialize();

// process the form
  $.ajax({
    type : 'POST',
    url : postUrl,
    data : formData,
    dataType : 'json',
    encode : true
  })
  .done(function(data) {
    if (data.success == true)
    {
      console.log('success');
      console.log(data);

      var redirect = '' + data.token
      $(location).attr('href', redirect);
    }

  });
});

Thanks


texts:
I have a form that contains a static select input of U.S. States:

<select id="state" name="state" class="form-control">
<option value=""> Select </option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
....
</select>

I have the validation figured out on my form, and also have my text inputs getting repopulated if there are any validation errors. I am curious about the best method to repopulate my select input.

I can access the value that was entered via:

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

Which will give me "AL" or "AK" (whichever was chosen). This is fine, but because my list is static, do I now need to have logic on every option?

For example, something like this...

<option value="AL" {% if state == AL %}selected="selected" {%endif%}>Alabama</option>

Or, is there a better way all together?

FWIW, here is how I am repopulating my text inputs:

value="{% if model is defined %}{{ model.name }}{% endif %}

Thank you!


texts: Can we log both access & content changes?

texts: If we implement CraftCMS, we would need logging of both access and publishing (both successful and failed attempts). The ability to change/remove those logs should not be available to those using the CMS. Is this available in core?


texts: {% requirePermission %} with OR condition

texts:
I need to use requirePermission tag to check if one or another permission is active.

I want to reproduce something like this:

{% if currentUser.can('perm1') or currentUser.can('perm2')  %}
   <!-- My page stuff -->
{% else %}
   {% exit 403 %}
{% endif %}

How can I make this possible {% requirePermission "perm1_or_perm2" %} ?


texts:
Doing my first Craft job and stuck with a reverse related entries thing.
I’ve got a channel of “Sectors” and a channel of “News”. The entries in news have a relationship field back to the “Sectors”.
When I’m viewing a “Sector” entry, I want to show links to entries in News that have a relationship to it.

I’ve tried a few things but essentially I’ve got this…

{% extends "_layout" %}

{% block content %}

{{ entry.title }}

    {{ entry.body }}

    {% for entry in craft.entries.section('news').relatedTo(entry) %}
        {{ entry.title }}
    {% endfor %}
{% endblock %}

But, even though I have a news entry related to a specific Sector entry, the above code doesn't show any related entries.

Oddly, if I do this...

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

Then I get some output but it shows me something from a different channel.

I’m confused. Can someone help?

Update

Schoolboy error alert!

I had the wrong field in my news entries. There was a category field set up which had the same values as the sector names. Once I'd replaced the field with the proper one it all worked as expected!


texts: Get related posts excluding current post in Craft 3

texts:
In Craft 3, I’m trying to get the five most recent other posts sharing a category with the current post.  I got this far:

{% for relatedPost in craft.entries.relatedTo(entry.newsCategory).limit(5) %}

That gets five posts sharing the current post’s category, including the current post if it happens to be recently posted.  How do I exclude the current post from the returned results, without just dropping it from the five so I’m only left with four?


texts: Migrating Content from ExpressionEngine that used Matrix Image haystack Technique

texts:
So I'm taking the plunge from ExpressionEngine to Craft! I have a ton of entries I need to move over, though - and I used the "matrix image haystack" technique for my blog posts to inject the images into the body copy.

I love the Matrix layouts in Craft and would like to essentially put those images in their own "block" and separate the text around the haystack tags into their own blocks as well. I'm doubting that's possible, but I'm not going to be able to re-publish hundreds of blog posts a new way, either :)

Has anyone attempted anything like this?


texts:
I am trying to develop an email commerce site that is easy for customers to navigate. The way that I would like to do it is so that I have a range of different parent categories and that when a customer clicks in this it opens a page where the different child categories are displayed with image tiles. When a customer clicks onto this tile it will then bring up the products in that child category.

Is this possible at all and if so what is the best way to go about making it operate in this way?

Many thanks for any help in advance


texts:
I've tried installing a plugin to my Craft 3 local installation. I ran this from the command line in my project root:

composer require boboldehampsink/import but, this error was returned

craft/plugins/import/ does not exist and could not be created.

Thanks if anyone can help.


texts: Javascript event on save for custom field

texts:
I have implemented a custom field type.

Is there any way to register a javascript event handler that is called before my custom field is saved?


texts: PHPUnit testing for Craft plugins or controllers

texts:
Is it possible to implement PHPUnit into Craft CMS? If so, where can I find a good explanation or tutorial? I already tried a Github link for a plugin (testing the plugin).

But I am new to both but really want to TDD the plugins. Any example pages or a quick guide would be great!


texts: Merge Entries but only after X amount of entries

texts:
I'm trying to get entries from two sections and merge them together which is pretty straight forward using the merge filter.

For example, my sections are:

News
Promoted News

But, my main issue is I only want Entry 1 from Promoted News to appear after 2 entries in News and so on (In a 2 entry increment)

I don't want it like this:

News - Entry 1
Promoted News - Entry 1
News - Entry 2
Promoted News - Entry 2
News - Entry 3
Promoted News - Entry 3
News - Entry 4
Promoted News - Entry 4
News - Entry 5
Promoted News - Entry 5

But like this:

News - Entry 1
News - Entry 2
Promoted News - Entry 1
News - Entry 3
News - Entry 4
Promoted News - Entry 2
News - Entry 5
News - Entry 6
Promoted News - Entry 3

I thought about doing it using a conditional and incrementing a variable, but I don't think this would work with pagination so I need to merge them in to one array.

Is it possible to do this? My heads mashed thinking about doing this...

Thanks!


texts: How do I access the checkbox field column value as a PHP array?

texts:
I have a checkbox field for dining cuisine types and I see that the checked options are stored as a JSON-encoded array in the content table. If I have an element that uses this field, is there a way I can just get that JSON-encoded value as an array in PHP? Any time I try to get the value of the field, I'm getting the entire MultiOptionsFieldData object which isn't desired in this case. I just want that array of checked values that's stored in the corresponding content table column.

I don't want to write any loops. I just want access to that actual column value from my element in PHP.

I don't want to write any additional queries to get that column value either. Surely, there must be a way to get the actual field value for checkbox fields. Right?


texts: "Error: Unknown package has no name defined" when updating Craft 3

texts:
I'm getting "Error: Unknown package has no name defined" when updating a site from 3.0.41.1 to 3.5.15.1
I had read a reinstall of composer had fixed this for someone else, but hasn't for me. This also happens on the same site (running locally) from a Windows and Mac OS machine - on the Mac I have been able to install some Craft updates, but I get the same error when updating plugins.
Plugins installed are: CKEditor, Contact Form, Redirect Manager, Twitter, Contact Form Extensions, Contact Form Honeypot.
I'm not able to remove any of the plugins via admin to see if they are breaking the update.
I've tried deleting the /vendor file and reinstalling the plugins with composer install - they all install fine without errors.


texts: Plugin, getting an entry when one of multiple category fields and/or lightswitches are not empty/turned on

texts:
Basically I’m trying to get en Entry where, either one (or more) of three lightswitches is (are) turned on, or where either categoryOne or categoryTwo is not empty.

This is what I got so far, but it doesn't seem to work.

$criteria = [
    'section' => 'news',
    'limit' => 100,
    'search' => ‘lightswitchOne:1 OR lightswitchTwo:1 OR lightswitchThree:1’,
    'categoryOne' => ':notempty:’,
    'categoryTwo’ => ':notempty:’,
    'id' => 'and, not 1, not 2’//Also exclude a couple id's
];
$criteriaModel = craft()->elements->getCriteria("Entry");
$criteriaModel->setAttributes($criteria);
return $criteriaModel->find();

Is there a way to do this is in Craft?


texts:
We have a site that had a feature/plugin created that can handle payment deposits as well as full payments for events.
We're wanting to create a job (like a CRON Job) or process that once a week goes through orders that are deposit payments and checks if the event part paid for is within x weeks, if both of these are true then to send a templated email (if possible to include the link generated by commerce when the order was initial created).
Are there any guides or how-to's to do this?


texts: Craft 3 image asset getUrl() not showing

texts:
I came across an interesting issue. I'm using Craft CMS 3.0.0-RC14 and non of my image paths are showing but the title and the file name does.

{% set image = nav.navLogo.one() %}
{{image.title}} // works
{{image.fileName}} // works
{{image.getUrl()}} // no output, not even error

Any ideas ?


texts:
Hi is there a way that we can manage the S3 bucket and configuration from craft general default config per envirenmont?

We are doing automated deployments to different envirenmonts which migrate the databases but are still manually changing the s3 bucket.

Thanks,

Ian


texts:
Does Craft support any form of single sign-on across separate installations? I don't think there is a native way of doing this, but does anyone have any idea how I would approach this?

What I need is for users of Site A and Site B to be kept in sync in some way so they can use the same username and password to sign-on to both sites. Bonus points if they can automatically signed into to Site B if they are already signed into Site A.

Note that using some form of social sign-on (e.g. Facebook, Twitter, etc.) is not an option for this client.


texts: Logging into CP doesn't set authentication cookie

texts:
Trying to debug an issue where in a dev environment logging into the cp it doesn't set the CP Authentication Cookie (the hash with the _identity) at the end of it. I believe this is the root cause of why no entries load and any request to the craft api returns a 400 with a response of Forbidden: Login Required.

This is the weird part because I am able to log in initially but after doing so it is as if i'm not logged in and I can only see a few things.

The other thing that happens is after a minute the session expired modal will pop up and after entering my pw again the modal won't go away. Now if I check my cookies I'll see the authentication cookie but it seems to automatically expire after it get set.


texts: How can I reload the Live Preview Iframe window using JS

texts:
I tried to reload the iframe window using JS but haven't had any luck getting the lp-iframe iframe element, I was thinking I could do it using the Window.Craft object but not sure how?

setTimeout(()=>{
  var iframe = document.querySelector('.lp-iframe');
  iframe.contentWindow.location.reload();
}, 5000);


texts: User registration: How do implement "Confirm password" and "Confirm email"?

texts: I've got a user registration form on my site, using the code from Craft's documentation. How can I get the form working so it asks the user to enter their email address and password twice? Can Craft take care of that or do I need to use client-side JS validation?


texts: send e-mails via smtp without authentification

texts:
I try to send e-mails via SMTP without authentification and I'm getting the following error:

  There was an error testing your email settings.

I checked my setup on https://www.smtper.net/. No problems!

I read through the troubleshooting-email-errors page but still found no solution for my problem.

Why can't I find a log under craft/storage/runtime/logs/craft.log. This file does not exist on my system. There is only craft/storage/logs/web.log.

When I use another SMTP server (with auth) everything works as expected. Any ideas on how to find out what's going on here?


texts:
I've manage to install Craft CMS with command line, I've the message "installed craft successfully" so I guess it worked, plus my database has been completely populated.
But then, how do we access the CMS lol ?
I've installed it at localhost/craftcms/ but then I don't know where I have to go to use the tool.
I use wamp ( on Windows of course).
Thanks for all, and sorry for my question that I'm sure is stupid but I can't find an answer


texts: Craft Commerce: Bakery site with multiple bakeries (How to handle product types and variants)

texts:
Alright, so I am trying to persuade a client to switch to Craft Commerce for their bakery shop.

Thing is, their current setup is kinda messy, and I just cant figure out how to convert it properly to Craft.

Case:
They have Cakes, Cakes comes in a multitude of sizes, with a lot of choices. Different types of cakes have different choices (Fill, jelly, nuts, colors, figures etc.)

All possible combinations of the choices results in a unique ID (EAN) for that cake, that the bakery can use in their system for production.

Thats ok, we can have product types and variants for all these. But here is the hard part: each bakery have their own set of choices, some bakeries dont have the same type of jelly, or the same colors for the toppings.

Each bakery choose what cakes they want to sell, and what kind of configurations they have.

When on their front page, you type inn your ZIP code and we use that to determine the closest bakery, based on that, we show that bakery's cakes, with their configurations.

Since there are about 10 bakeries, having a chocolate cake with custom variants per bakery will get really messy really fast, given how many cakes each bakery has. So I am trying to figure out how to separate each bakery and its product in the CP.

I toyed with the idea of creating one product type per bakery, and just having a generic "cake" model that can be built up however they like, but this seems very hard for both us and the client, they having to create the same options over and over, and us having to "magically" get all kinds of configurations from some kind of matrix field, creating choices based on this in the frontend, and sending those choices by mail when the order is complete.

Is there some kind of "hack" where I can have a separate product (database) tables per user group, or something like that? If bakery X logs on the CP, we show products from this table, if bakery Y, we show products form another table.

The rest of the site is going to be joint, about us, contact, articles etc are all the same across bakeries. So I would like to avoid having 10 licenses, 10 databases and 10 installs to cope with this.

Any other ideas are greatly appreciated, maybe I am looking at this the wrong way, but having 300 cakes, with 18 variants each is going to make it impossible for a specific bakery to maintain their cakes.

Mathias


texts: Two Domains. One Repo. Need Second License

texts: I have two different domains that are both being deployed from the same Github repo. Domain A has a Craft license. Domain B needs a Craft license. I don’t want to transfer from Domain A to Domain B but they are both reading from the same craft/config/license.key file.