texts: We have a Global page that has about 10 tabs with a bunch of fields each. The thing takes between 50 and 80 seconds to load. The debugger shows that it fires off over 9000 events and makes almost 900 db queries. I'm trying to figure out how to troubleshoot this in order to try to speed it up. It appears that each time afterRenderTemplate is fired, it takes 5 or more seconds before getting to the next step.


texts: Excluding specific field value from search

texts:
I want to find all entries that match the title field where excludeFromSearch != 1 (is false).

{% set query = 'and excludeFromSearch not 1 and ' ~ 'title:"' ~ "myValue" ~ '"' %}

    {% set results = craft.entries({
    section: querySections,
    search: query,
    orderBy: 'score',
    }).limit(50) %}

It does not work. My field excludeFromSearch is a lightswitch.


texts: When to use " is same as" and when to use "=="

texts:
{% if foo is same as('bar') %}

vs.

{% if foo == 'bar' %}

When to use first and when to use second? Does one of them has advantages over another?


texts: Locale Global section in CP bringing back page can not be found

texts:
I've been asked about doing a Russian version of a website. I've set up a new locale in the Locale settings, as well as an ru/ folder with index.php and .htaccess. Adding a news story in Russian works fine, though changing a Global section to Russian brings up a "Page Cannot be Found".

The address for this is http://example.com/admin/globals/ru/globals

Does this look right?

general.php:

return array(
    'omitScriptNameInUrls' => true,
    'siteUrl' => array(
        'en' => 'http://example.com/',
        'en_gb' => 'http://example.com/',
        'ru' => 'http://dropinn.net/ru',
    ),
);

/site/ru Folder:

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

// Tell Craft to serve the Russian content
define('CRAFT_LOCALE', 'ru');


texts:
How do I use/call globals in entries? Trying to insert a simple global called {{ whateveryounameit }} with some text but don't see anything except its name.

Any other ways to display common content across multiple entries?


texts:
We just migrated a site from Craft 2 to Craft 3 and I'm running into an issue with some redirects we used to have setup in Sprout SEO.

Our site runs a Craft CMS backend with a Nuxt frontend along with a 3rd vanity URL. We used to have Sprout SEO setup in a way that all requests to the vanity URL would get redirected to the main domain running on Nuxt. However, it seems that Sprout now appends the Base URL to the redirect along with using the 'Sites' functionality in Craft 3, which has effectively broken the redirects.

So I guess my question comes down to this: is there a good way in Sprout to redirect from one domain to another like was possible in the Craft 2 instance? And if not, is there a different way to do so within Craft? We want to be able to give our content team the ability to add redirects rather than hardcoding them in the nginx config.


texts: How do I handle and/or repopulate checkbox group(s)?

texts:
I have a contact form (public facing only) on my site that has a checkbox group. The user can pick their favorite color(s). Upon successful submission I am capturing that data within the CP via a plugin.

I have a checkbox field within the CP called "colors".

This is how I am outputting the values in my template:

<input type="text" id="name" name="name"class="form-control" value="{% if contact is defined %}{{ contact.name }}{% endif %}" placeholder="Full Name"/>
{{ contact is defined and contact ? errorList(contact.getErrors('name')) }}

....

{% for option in craft.fields.getFieldByHandle('colors').getFieldType.options %}
<div class="checkbox">
    <label>
        <input type="checkbox" name="fields[colors][]" value="{{ option.value }}">{{ option.label }}
    </label>
</div>
{% endfor %}
....

So far so good. Name is required, so if a user submits the form without entering a name, but has chosen a few colors, I would like the colors to be checked when the page reloads. I am able to do that on the name field easily.

The next part of the question, how do I handle the array of options via my plugin?

Here is what I have in my controller:

ContactFormController

....
$contact->profession = craft()->request->getPost('profession[]');

When I log what the model is getting here is what I am seeing:

[name] => My Name
[colors] =>
....

I assume that I will also need to set up a FK relationship in my record file so once the form is submitted I can have a 1:many relationship. I'll look at the docs on how to set that up - and post what I've done back for future reference.


texts:
I have a template which I want to use for different sections.

In my template I have this code:

{% set pages = craft.entries.section('catering').level(1) %}

  {% for page in pages %}

{{ page.getLink() }}

  {% endfor %}

But I want to select the current section by Craft self. So I can use the same template for multiple sections.


texts: What is the best approach of updating existing Craft installs with new features?

texts:
I'm currently developing a blueprint for all my Craft websites. It contains a set of sections, fields, plugins etc. All configured the way I need for my websites. The websites itself are basically a fork of this blueprint and only has to have a custom template and content and we're good to go.

The number of features in my blueprint will be growing as time passes along. What would be the best approach of updating all Craft installs so that each website (build upon previous blueprint versions) can benefit from the newly developed features.

I could just backup the DB and code from the blueprint and import them into the website, but then I will be losing all content.

Any idea?
Thanks in advance!


texts: How can I implement advanced action routes (in routes.php)?

texts:
We want to mask specific action routes in our project's routes.php file. Currently what we have looks like this:

return array(
    // /actions/api/element/section/name/{$name}/
    'api/test/(?P<name>)'  => ['action' => 'api/element/section'],
);

We would like to pass name into the action array somehow. Is there something documented or undocumented that I'm missing? Or is what I'm attempting not possible at this time?


texts: Force browser to download latest CSS file

texts:
Is there any simple way to automatically add a version number when referencing a CSS file?

Example: <link href="style.css?v=VERSION-HERE" rel="stylesheet" type="text/css">

Version could be a timestamp when the style.css was last modified or something like that.

The reason for this is that I often have to tell my clients to force the browser to reload because they don't see the latest changes I've made in style.css.

If it matters, I use Deploybot and github.


texts:
I notice that you can add icons for your sub navigation. However looking at the template for the subnav loop there isn't any markup to render that icon. Anyone know if this is coming in the future or missing code?

Example pulled from Craft Commerce plugin

$context['subnav']['settings'] = array('icon' => 'settings', 'label' => Craft::t('Settings'), 'url' => 'commerce/settings');


texts:
I have a controller which fetches an asset from an entry (this is the service method that provides the asset):

public function findPoster($entryId) {
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->id = $entryId;

    $entry = $criteria->first();

    if ($entry) {
        if ($entry->downloadItem) {
            return $entry->downloadItem->first();
        }
    }

    return null;
}

That works great, however now I need to send the asset to the browser. Having a little poke around in the method listing I see there is a CBaseController::renderFile() which sounds to be what I need, however I can't work out the correct way to build a path to the file. Accessing $url from the asset I've fetched returns a public relative path but obviously I need the path on the filesystem.

So far I've got this working:

$name = strtolower($asset->title) . '.' . $asset->extension;

header('Content-Type: ' . $asset->getMimeType());
header('Content-Disposition: attachment; filename=' . $name);

$path = realpath(craft()->basePath . '/../../public/' . $asset->url);

die(file_get_contents($path));

However this is far from ideal because:

I have to hardcode the public directory which isn't the case at any other point in Craft, so it feels really dirty.
Manually setting the headers seems like something a controller method would be able to take care of properly.


texts: Content from two sections but one of which is related to a specific category

texts:
I am looking to do the following.

I'd like to display a list of entries from two sections. That much is straightforward; however the kicker is that I only want entries related to a specific category of one of the sections.

So:

Everything from SectionA
Only CategoryC from SectionB

Possible?


texts: Reverse Related entries with Matrix Field

texts:
I have a site with channels ‘articles’ and ‘tutorials.’ An article entry has a matrix field which contains an entry field to link to a tutorial. Every tutorial is linked from within at least one article.

I would like each tutorial page to link back to the articles it appears in.

If I'm on a tutorial page and have the following code in my template…

{% set articles = craft.entries.section('articles').relatedTo(entry) %}
{{ articles|length }}

articles|length is always zero.

I did a test with just a simple entry field to link to a tutorial and that works fine. Is there something special that needs to be done to get it to work with a matrix field? Could it be a configuration issue?


texts: Send email notification to user's email when their entry has been enabled

texts:
Running craft 2 on a customer's site. They have users that sign up on the site to receive personalized quotes. What I'd like to do is send an email notification to that user after an admin has enabled the entry that the user created.
I can't find any plugins that do this specifically. I've been trying to customize sprout forms/email to do this, but I'm not having any luck.


texts: _entry.twig in sub folder, rich text editor images using relative URL and are therefore not found

texts:
This may be something obvious that I'm missing, but how can I make craft use absolute URLs for images add to rich text editor fields? Or use the {{siteUrl}} prior to the image src URL in order to fix the issue of images not being found.

Side note - Why are the images not visible within the rich text editor when added? Is this because of the relative URLs too?

Thanks


texts: Complete user profile after social public registration

texts:
I use Dukt plugins (-oauth and -social) for public front-end registration. I would like complete user profile after registration (e.g. license agreement checkbox).

How is it possible to accomplish this?

I would like intercept social callback after authentication and show a custom page.... I suppose OnBeforeSave event is not useful for this scenario. Thanks


texts: How to fetch matrix block items with the ElementAPI

texts:
I have a question regarding the ElementAPI:

I am sucessfully using the ElementAPI to fetch assets related to an entry. Now I have a matrix field where a user can add multiple galleries (multiple block of selected assets) and i want to retrieve the images. But I can't figure out how to use it for nested matrix blocks...

This is how I fetch the data with ElementAPI from non-matrix assets fields (elementapi.php config)

'endpoints' => [
    'api/v1/installation-views/<sourceEntryId:\d+>/<fieldHandle:[A-Za-z]+>' => function($sourceEntryId, $fieldHandle) {
        return [
            'elementType' => 'Asset',
            'criteria' => [
                'relatedTo' => [
                    'sourceElement' => $sourceEntryId,
                    'field' => $fieldHandle
                ],
                'kind' => 'image'
            ],
            'transformer' => function(AssetFileModel $asset) {
                return [
                    'id' => $asset->id,
                    'title' => $asset->title,
                    ...
                ];
            },
        ];
    }
]

How would I do that for asset fields nested inside a matrix block? I guess I can't use the nested field handle as handle?


texts:
Looking for some input on how to setup a Craft site. I have 2 sections of the site containing content grouped by the same set of topics (or categories).

For example, within Services there 6 sub-pages. Resources has 6 sub-pages using the same categories as Services.

In other words there is a page under Services and Resources named Topic 1. In Services the Topic 1 page will contain a description of Topic 1. Under Resources the Topic 1 page will contain PDFs and FAQs related to Topic 1. The PDFs and FAQs would ideally be sorted by a custom order. There are similar pages under Services and Resources for Topic 2, Topic 3, etc.

Recommendations on how to set this up in Craft?


texts:
I want to try and stop Commerce 3 creating a new customer address if it’s a duplicate of an existing one.

As an example, a store selling digital products has a checkout form that simply asks for the customer’s country, no other address info is required. All we need is one select field for the country (pre-checked if we already have that info). We could add radio buttons to select any previously saved addresses as well as a field to select a (new) country. However, even if we do that, there’s still a chance the user opts to enter a new address and actually submits a duplicate.

I’ve created a plugin that catches a duplicate address and then tries to set the cart’s billingAddressId so a new address isn’t created. What I have so far though doesn’t work. It doesn’t successfully update the billingAddressId. If I use Craft::$app->getElements()->saveElement($cart) it results in a loop in this case.

How can I complete this to update the cart, or perhaps the post data in this case, with the matched billingAddressId?

Event::on(Address::class, Address::EVENT_BEFORE_VALIDATE, function (Event $e) {

    $sentCountryId = $e->sender->countryId;
    $currentUser = Craft::$app->user;
    $cart = craft\commerce\Plugin::getInstance()->getCarts()->getCart();
    $addresses = $cart->customer->addresses;
    $match = 0;

    // Only check against saved addresses if currentUser has any
    if ($currentUser and $addresses) {

        // If true, loop saved address to check for a country match
        foreach($addresses as $address) {

            // Loop until a match is found
            if ($match == 0) {

                $savedCountryId = $address->countryId;

                if ($sentCountryId == $savedCountryId) {
                    $match = $address->id;
                }

            }

        };

        // If there’s a match set the cart’s billingAddressId
        // to stop a new address being created:
        if ($match) {

            $cart->billingAddressId = $match; // This doesn’t work on it’s own
            // Craft::$app->getElements()->saveElement($cart); // Results in a loop
            $e->handled = true;

        }

    }

});


texts: Craft Commerce Fixed Shipping Rate (without currency conversion)

texts:
I'm trying to create a fixed shipping rate that isn't affected by payment currencies - it's X2.50 where X is whichever currency.
I've been trying with an adjuster but it's also affected by the currency conversion rate. Is there some way I can force a price to not be affected by the currency conversion?
$adjustment = new OrderAdjustment;
  $adjustment->type = 'shipping';
  $adjustment->name = '';
  $adjustment->description = '';
  $adjustment->amount = -$order->storedTotalShippingCost;
  $adjustment->setOrder($order);

  $adjustments[] = $adjustment;

  $adjustment = new OrderAdjustment;
  $adjustment->type = 'shipping';
  $adjustment->name = '';
  $adjustment->description = '';
  $adjustment->amount = $adjustedPrice;
  $adjustment->setOrder($order);

  $adjustments[] = $adjustment;

Would a custom shipping method be better here or would that have the same problem?


texts: Remove the anchor in nav loop based on another field conditional

texts:
I'm using this solution to output the children within a current structure entry.  Unfortunately I need to take out the anchor on some entries that don't yet have content, but still include the (unlinked) title.

I'm trying the following

{% nav page in subnav  %}
  {% if page.id != entry.id %}

{% if page.pageIntroText|length %}{%endif%}{{ page.title }}{% if page.pageIntroText|length %}{%endif%}

  {%else%}

{{ page.title }}
{%endif%}
{% endnav %}

.. but it removes the anchor regardless of whether there is any content in pageIntroText field?

Any ideas?

Many thanks

Martin


texts: How do I loop through entries for a specific entry type?

texts:
I would like to loop through entries in a channel but only the ones for a specific entry type. Is this Possible?

I'm using the free version of craft on a test site, I have used the channel for my pages but also want to set up a blog. I have set up a blogPost entry type, is there a way to target this in a loop?


texts: Adjusters: Conditionally include tax in price

texts:
I have a question about adjusters: I am working on a shop which has two tax zones (Switzerland and EU) and two tax rates (8% and 19%). The tax should always be included in the item price. From my understanding that is not possible for both tax zones at the same time. So I am having my eye on the adjusters.

I would use an adjuster to do the following:
The client facing cart on the front end gets no adjustments. Only after the shipping address has been confirmed I would apply either one or the other adjustment (8% or 19% included) conditionally via the plugin to the order.

Does that make sense? Is that possible and if so is this even the best way to go or am I missing something which is more awesome?

If the answer is yes then I would invest more time and just dig into it.

Thanks in advance!


texts: Friendly order number - start sequence at specific number

texts:
Folks:

I'm having trouble getting my head around friendly order numbers and sequencing. The client has asked for his sequence to start at 11 000.

I can set up a sequence that starts at 1 based on the docs. I can get this to show on the email receipt. What I'd like to know:

How can I get this to start at 11000 and be sure it rolls over to 12000 when orders hit that number?

I'm guessing that whatever the code winds up being, it's set in the "Order Reference Number Format" field, correct?


texts:
Is there a specific or preferred way to set the username for new user registrations to be their email address?

At the moment my user signup form contains both fields:

  Username
    <input type="text" id="username" name="username" placeholder="joesmith" {%- if account is defined %} value="{{ account.username }}"{% endif -%}/>
    {% if account is defined %}
        {{ _self.errorList(account.getErrors('username')) }}
    {% endif %}

  Email
    <input type="text" id="email" name="email" {%- if account is defined %} value="{{ account.email }}"{% endif -%}/ autocapitalize=off autocorrect=off>
    {% if account is defined %}
        {{ _self.errorList(account.getErrors('email')) }}
    {% endif %}


texts: How to check if on a channel/category index?

texts: In the previous question I asked for a way to detect the 404 page from a plugin. Brandon gave me a good starting point with this answer. However, I wondered what method I could use to also detect wether the user is on any category/channel index page?


texts: Plugin Routes: Asterisk Token effect from CP Routes

texts:
I'd like to use the asterisk token functionality that is available in the CP in my plugin. This way I can have an infinite amount of 'pages' under certain routes. In the CP, it looks like myroute/*

Is it possible for me to get the same functionality in my plugin routes?

Routes have been working amazing for me via the standard:

public function registerSiteRoutes()
{
    return array(
    'myroute' => array('action' => 'myPlugin/myAction')
  );
}

Though when I try the asterisk trick, it doesn't work:

public function registerSiteRoutes()
{
    return array(
    'myroute/*' => array('action' => 'myPlugin/myAction')
  );
}

Does anyone know if this is possible and/or the way to accomplish this?

Thanks!


texts: Setting tab 'error' class for tab with error

texts:
When creating an editor interface within my plugin, I am using the following snippet to create a set of tabs inside a tab pane:

{% include "_includes/tabs" with {
   tabA: { label: 'Tab A'|t, url: '#tabA' },
   tabB: { label: 'Tab B'|t, url: '#tabB' },
} %}

Now, when I submit my editor form and there is an error in a form field that's part of tabB, I want to indicate this by highlighting the tab title in red. This is usually done by adding the class 'error' to the tab. So, using Twig, I could determine which tabs have errors right before defining the actual tabs and apply the class 'error' to the relevant tabs. I could also apply the 'error' class using JavaScript upon form initialization.

Just wondering what the recommended way of doing this is or whether there is some built-in code to easily do this?


texts: Send Emails to dynamic list of recipients

texts:
I would like to send an Email to a dynamic list of recipients with SproutEmail.

I've created a Plugin that adds custom element actions in the users indexview that raise a custom SproutEmailEvent to send a Notification. The event works fine already, but I want to send the notification to the dynamically selected list of users.

Let's say I select 4 Users in my user indexview and click on my custom action "Send Reminder email", then all of the four selected users should receive the notification email.

Also of course, I would need to address the selected users in the email template, like "Dear {firstName} {lastName}"

I understand how I could do that with a single user, but how about a dynamic list of selected users?

Thanks for your help.

Robert


texts: Working with content of HTML  http-equiv Attribute in extending main layout template

texts:
I am extending the meta of my main layout template in one page only, utilizing the technique explored in some depth here.
How do I add an HTML block from template extension to main layout template? (i.e. meta data)
I want just one page to have the refresh meta, such as this:
<meta http-equiv="REFRESH" content="20; /news">

When I reference the HTML  http-equiv attribute, how may the content part be put into the format below?
{% set metaProperties = [
    { name: "http-equiv", value:"refresh"  },
] %}


texts:
We have a Craft site with nearly 800 entries. For SEO purposes we need to change the page title and page (SEO) description for each entry, a laborious task to say the least.

Is there a way to have, say, a PageTitle variable which we apply to all entries with SEOmatic, and if we need to change the structure of the title, we just have to change the PageTitle variable once. This variable itself would have variables within it, e.g:

  Beautiful {villaBedrooms} bedroom villa in {villaLocation.last.title}, Bali. From just ${villaPrice}. {villaHook}


texts:
When I use the hacksaw to truncate the formatting goes away.  If I remove hacksaw it comes back.  So, my question has changed, is there a way for me to truncate the text while keeping the formatting?

The return on the line below is from a rich text field and it will not show formatting unless I remove hacksaw.

 {{ workItem.summary | hacksaw(words='75', append='...') }}


texts: Plugin Development: intercept Entry before returned to template

texts:
Is there a hook in Craft to intercept an Entry before being returned to a (front-end) template? Thinking here of ways we can manipulate what is being returned in the Element Criteria Model without affecting the underlying content.

Thoughts appreciated


texts: CSRF in plugin dashboard widget 400 error

texts:
Yes, it's another csrf question, the standard, 400 Error - Bad Request: Unable to verify your data submission.

If in config/general.php I set 'enableCsrfProtection' => false, then everything works nicely. So it's definitely a csrf problem.

Here's the twig template for the widget:

src/templates/_components/widgets/Livestream_body.twig
---------------------
<script type="text/javascript">
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
</script>

and the Javascript:

src/assetbundles/livestreamwidget/dist/js/Livestream.js
-------------------
$(document).ready(function () {
   var data = [];
   data[window.csrfTokenName] = window.csrfTokenValue;
   $.post('actions/livestream/main/manage-get', data, function(response, textStatus, jqXHR) {
       alert('Posted OK!');
   });
});

I can see the csrf token value changes on page load, and as I said, without csrf enabled, the js successfully loads the widget, so, what am I doing wrong on the csrf? I don't have any  element. Would that make a difference?


texts: Workflow for running Craft CMS with Docker in production?

texts:
I've been looking into running Craft CMS with Docker in production. One of the most helpful and comprehensive resources I've found so far is Matt Gray's blog series. While it goes into great depth, I'm still left with some questions.

How to handle license.key when building a Docker image for production? It seems insecure to just check this into version control.
How to manage the installation of plugins? I currently add plugins to composer.json, the contents of which are installed when the Docker image is built. I then use the Craft CLI to install the plugin inside the container (while all services —database, nginx, php — are running) which updates my project.yaml config file (available in host folder, mounted into container), which in turn I can check into version control. That way, when I build a Docker image and run it, Craft can use this project.yaml file. This is convoluted and painful at best; is there a better way?
How to manage entry types, field groups, etc? Currently I manage this in much the same way as I handle the installation of plugins. This means that in production, one can never create new entry types, as they would be overwritten once a new Docker image is built and put in production.

In all, this doesn't feel robust and seems very error-prone. Does anyone have a Docker + Craft CMS workflow that's more robust that what I described above that they're willing to share?


texts: Prettiest way to loop through nested relations?

texts:
Let’s say i have a location channel, a studio and a team channel. A location contains one or several studios and a studio contains one or several teams.
I can display all the teams in a location by looping through all the studios related to the location and then through all the teams related to the studio.

Is it somehow possible to do that in one loop?  To only loop through all the teams related to the location ( which aren’t related directly to each other)?

location/_entry.html :

{% set studios = craft.entries.section('studio').relatedTo(entry) %}

{% block content %}

Studios in {{entry.title}}

    {% for studio in studios %}

{{studio.title}}

    {% endfor %}

All teams in {{entry.title}}

      {% for studio in studios %}
      {% for team in craft.entries.section('team').relatedTo(studio) %}

{{team.title}}

      {% endfor %}
    {% endfor %}

{% endblock %}


texts:
I am using the Social Login plugin from Dukt. It mentions in the configuration instructions to add things to a social.php file that you place in craft>config.

I've done that, but I assume I'm doing something wrong with the PHP file, as it just shows up in the CP on the social login settings page, rather than actually performing the additional functions I'm looking for.

I'm not super well-versed in PHP, so I'm sure its user error. Can anyone help? Here's the contents of my PHP file:

'lockDomains' => [
'awebaddress.net']

And here is what is showing up in the control panel:


texts: Creating and using custom content tables

texts: If I want to create fields that get set to a custom content table rather than craft_content how would I do that?


texts:
So I’ve got fuzzy search activated and it works as it should... going to the right; but if I have a plural? Is there no way around this?

Search term: "intaglio" = 12 results … includes "intaglio" and "intaglios”

Search term: "intaglios" = 9 results … only includes “intaglios”


texts: Admin Panel For Page Only Shows Disabled Matrix Blocks

texts:
I'm a Craft novice trying to help some people who have taken over a Craft 3 website.  There is a Single Page where the Main Content is a series of Matrix blocks. The problem is the admin Control Panel for the page only displays the disabled blocks.  The website itself is fine -- showing just the enabled blocks.
Is there an All/Enabled/Disabled toggle somewhere? How do we get this page to display all the blocks?


texts: Set Structure Parent when creating Entry in Plugin

texts:
I have Structure-type Section for entries and want to pragmatically populate a large list of multi-tiered entries.

I see you can create an entry like:

$entry = new EntryModel();
$entry->getContent()->title = 'New Page';
$entry->getContent()->body = null;

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

What I want to do is add the parent(s) of the entry, something like:

$entry = new EntryModel();
$entry->getContent()->title = 'New Page';
$entry->getContent()->body = null;

// this entry would be a child in order of Sports -> Tennis -> This Entry
$entry->getContent()->parent = sports->tennis;

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

Is there a way to do something like that?


texts: Getting relation through entry field by author

texts:
I currently have a structure called 'Divisions' that includes 'Team' pages as children. On the 'Team', there is an entries field 'Head Coach', which is an entry created on a 'Coaches' channel.

The coach has an account and has created the entry, so he is the author.

My question is, assuming the coach is the 'currentUser' is there a way to find the relation between that 'Head Coach' entry and the 'Team' if they are related by the author?

I have this code so far:

{% set coachingTeam = craft.entries.section('divisions').type('team').relatedTo({
    targetElement: currentUser,
    field: 'headCoach'
}).find() %}

The only way I've found to do this was to loop through all the teams, and if the currentUser and the author of the 'Head Coach' entry matched, then set the team.

It seems expensive, but I can't figure out how to do this with a relations call.

{% set allTeams = craft.entries.section('divisions').type('team').find() %}
{% set coachingTeam = '' %}
{% for team in allTeams %}
    {% if (team.headCoach|length and team.headCoach.first.author.id == currentUser.id) %}
        {% set coachingTeam = team %}
    {% endif %}
{% endfor %}


texts:
I'm trying to create a category through the api to import a load of datas,
but I'm stuck, the category won't be saved, and the saveCategory() method just returns false

$category = new CategoryModel();
$category->setContentFromPost(array(
    'groupId'       =>  $this->category_group_id,
    'title'         =>  $data[0],
    'colorCode'     =>  $data[1],
    'colorPreview'  =>  $data[2]
));
$category->enabled = true;
$res = craft()->categories->saveCategory($category);

Can I get a glimpse of what's happening, or the error ?

Is there anything wrong in this code ?
Does anyone have a good example/documentation for this ?

Thanks for your help.

Nicolas


texts: How can I check if an Entry was posted less than a month ago?


texts:
I'm getting a Deprecated Warning on the property safeHtml:

  The embedded asset property safeHtml is now deprecated. Use a
  combination of the isSafe() method and the code property instead.

This is picked up on line 4 and 11 of the code below:

        {# if video embed #}
        {% if embed.type == 'video' %}

                {% set vidcode = embed.isSafe() | trim('<iframe') %}
                {% set vid = '<iframe class="aspect-ratio--object" ' ~ vidcode %}
                {{ vid|raw }}

        {# else if rich embed #}
        {% else %}

                {{ embed.isSafe()|raw }}

        {% endif %}

How do I update this code correctly to remove the warning?


texts:
Folks:

I'm slowly working my way through a Craft3/Commerce2 upgrade. My current issue:

When updating redactor I receive multiple errors. I just want to be sure I'm on the right track.

Error 1:

Cannot create cache directory /.composer/cache/files/, or directory is not writable. Proceeding without cache

Cannot create cache directory /.composer/cache/repo/https---composer.craftcms.com/, or directory is not writable. Proceeding without cache

Cannot create cache directory /.composer/cache/files/, or directory is not writable. Proceeding without cache

I assume the vendor > composer folder needs to be writable to make this work, correct?

Error 2:

Package "craftcms/vue-asset" listed for update is not installed. Ignoring.

This seems straightforward but where do I find this? I figured as it seems to be part of Craft it would already be there.


texts: Matrix field alternative (or easier field grouping)

texts:
Just started working with Craft, and it's been great! One question I have is regarding the 'correct' way to create a group of fields, rather than using Matrix or Table.

To better illustrate, see the below screenshot of a Matrix, which is setup as a Global for people to add their contact information.

Obviously, it's not really being used for the purpose of repeating content, but at least it groups fields together nicely. It does have the greyed-out button when setting Max Blocks to 1.

The other alternative would be to create each Field separately for the 3 fields above, and add those to the Field Layout. This is kind of a fair amount of work, and leaves you with a massive cluster of Fields (I'm aware you can Group them).

Anyway - hope I've explained myself! Just wanted to bounce ideas around, and at least make sure I'm on the right track!


texts:
I'm looking for advice. We've had a client float an idea with us for a possible extension to their existing Craft website.  They want to provide a library of pre-recorded fitness video classes for their customers - This would be a subscription AND 'on demand' service. I guess like Mijingo but for fitness? Here's some questions I have:

Is this possible with CraftCMS or would it need Commerce?
We're thinking the Stripe payment plugin - any advice/alternatives?
Can we stream off S3 or is it better to use Vimeo CDN, is there a plugin to assist?
How to ensure videos are only available to logged in users?
What happens when somebody unsubscribes - how do we automatically remove/pause their access?

If anyone has experience in something like this and can offer any pointers, pitfalls to avoid etc,  i'd be so grateful.

Many thanks!


texts: Carry address over with customer's order when creating user

texts:
When a user is created with the same email as a customer, the orders are attached to that user account. I have a Customer Info custom field attached to the Users, and that is updated to include the order, which is great.

Is it possible for the addresses within that order to be carried over to that same Customer Info field as well? I know that if a new address is added now they're a user then that would be saved. But what about carrying over addresses from the pre-existing order?


texts: Craft commerce 3 - Module - Lineitem - Get usergroup

texts:
I have the following code working. The only thing i have to do is to check which usergroup is the customer in. Is there a simple way to check what usergroup is the customer in? This is my first custom module.
Event::on(
LineItems::class,
LineItems::EVENT_POPULATE_LINE_ITEM,
function(LineItemEvent $event) {

    // @var LineItem $lineItem
    $lineItem = $event->lineItem;

    // @var bool $isNew
    $isNew = $event->isNew;

    $purchasable = $lineItem->getPurchasable();
    $variant = $purchasable->getProduct();

    // IF GUEST USER  > NORMAL PRICE
    $lineItem->salePrice = $lineItem->getSalePrice();
    $lineItem->price = $lineItem->getPrice();

    // IF USER IS IN DEALER USERGROUP > DEALER PRICE
    $lineItem->salePrice = $variant->dealerPrice;
    $lineItem->price = $variant->dealerPrice;

}

);


texts:
I'm having issues finding out what all the classes are Craft uses to style its control panel.

I have extended the layout but is there any place with more information about what classed there are and how to use them?


texts: How to run domain.com and m.domain.com from one install

texts:
I have an upcoming project where it may be necessary to have a mobile site and a desktop site as the desktop design will not work well responsively.

I built a similar site recently in ExpressionEngine and used Multiple Site Manager (MSM) which allowed me to have separate templates with the same url structure pulling content all from the main site. Since that build I've starting moving new projects to Craft and would like to find a solution to this.

Since Craft does not have a feature similar to MSM, at this point, what would be the best way to approach this. Urls need to be the same on both domain.com and m.domain.com with all content being sharing the same channels.


texts:
I am importing data into Craft. I happen to know that the id for my desired category is 22. The category is not being saved.

Here is my code.

    $entry = new EntryModel();
    $entry->sectionId   = 3; // 3 is Episode Section
    $entry->enabled     = true;
    $entry->authorId    = 1;
    $entry->slug = $slug;
    $entry->postDate = $postDate;
    $entry->getContent()->title = $title;
    $entry->getContent()->body = $body;
    $entry->getContent()->summary = $summary;
    $entry->getContent()->metaDescription = $summary;
    $entry->showName[] = 22;

Where showName is the category handle of my category field.


texts: Slow saving when devMode false, but not while true

texts:
All of a sudden, saving entries became really slow (up to a minute). Regardless of entry type.

I came across this question: Saving entries in admin panel

Problem is when I turn on devMode saving goes without a problem and only takes a second, so I am unable to debug it.

Does anyone know why saving all of a sudden is very slow, and/or why saving is fast only with devMode true?


texts: Do I have to restart apache server every time I change a Craft PHP file?

texts: When I make a change to a .php file of Craft, say config/routes.php, do I have to restart the server to take effect ?


texts: CP search for entries where a specific field is empty

texts:
In the control panel, is it possible to search for entries where a specific field is empty? The Craft search syntax page doesn't help here, and the logical values used in twig don't seem to work here. I haven't been able to find any other info about this either.

Side note: the search syntax is a bit out of reach for many non-dev users (read clients). An advanced search/filter form for entries would be awesome.


texts:
I am new to craft CMS and installed it in an Amazon EC2 instance via Composer.
This worked.
My vhost.conf looks like this
<VirtualHost *:80>
ServerName craft.example.com
DocumentRoot /var/www/vhosts/viacraft/www-craft-test
ServerAdmin tristanvii@example.com
ErrorLog /var/www/vhosts/logs/error_log_viacraft
<Directory /var/www/vhosts/viacraft/www-craft-test>
        AllowOverride All
</Directory>
RewriteEngine On
RewriteCond %{SERVER_NAME} =craft.viainfo.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

Database setup worked and passed.
Then according to the manual I called
https://craft.example.com/index.php?p=admin/install
which leads to an File not found error.
Then I put a hello.php in /var/www/vhosts/viacraft/www-craft-test but https://craft.example.com/hello.php did not worked which I did not understand.
Then I put the hello.php in /var/www/vhosts/viacraft and it worked which is strange because the web directory in the vhost.conf is /var/www/vhosts/viacraft/www-craft-test and not /var/www/vhosts/viacraft/
Any ideas to this behaviour?
Then I managed to start the whole thing by entering
https://craft.example.com/www-craft-test/admin/dashboard
Why do I have to enter my webfolder www-craft-test in the path to call the dashboard???
I made my first entry - a blog and when I press Preview the following page is called
https://craft.example.com/www-craft-test/admin/entries/blog/17-my-first-blog
with the error

Page Not Found
Template not found: blog/_entry

I am not in development mode.
Settings/Site This site has its own base URL is UNCHECKED
This is my .htaccess in the www-craft-test folder
 <IfModule mod_rewrite.c>
  RewriteEngine On

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

In the templates folder there is still the original index.twig file.
A bit confused, happy to get some helpful ideas?
Thanks
Tristan


texts: Using Element API, how do I get the next entry?

texts:
return [
    'endpoints' => [

        'journal/<entryId:\d+>.json' => function($entryId) {
            return [
                'elementType' => 'Entry',
                'criteria' => ['id' => $entryId, 'section'=>'journal'],
                'first' => true,
                'transformer' => function(EntryModel $entry) {
                    $nextEntry = $entry->getNextSibling();
                    // also tried getNext()

                    $upNext = [];
                    $upNext["title"] = $nextEntry->title;
                    // errs out here ...
                }
            ];
        }
    ]
];

I feel like I'm missing something obvious, but how do I get the next sibling of an entry using Element API?  Would it be easier/better to pass both the current entry ID and the next entry ID (which I have available) into the criteria to make it easier to grab?

Thanks!


texts:
I have everything loaded, my path to "craft" is correct and the database credentials are correct but when I go to domain.com/admin, it pulls up a blank screen. Not a 404, server error, of the "oops" screen. It's just blank.

My folder permissions are also correct. Anyone else had this? I checked the server requirements and those are also within the correct parameters.

Jeremy


texts: Can I use Craft CMS for a large custom web application?

texts:
I know the easy answer is "yes", but let me elaborate:

Say I want to create a community for grocery shoppers. I let bloggers and other influencers design their own menus that define which ingredients end up in the users' shopping carts.

The users pick the menus that interest them, and based on factors like number of people in the family etc, the right quantity of ingredients are added to the cart. When the user is ready, she clicks purchase, and an order is sent to the nearest (or selected) grocery store.

I have developed sytems of similar complexity earlier in my career, but then by using my own CMS system- which of course let me do whatever I wanted.

My question is - would Craft CMS be suitable for this kind of task? Is it in fact more than a website CMS? Is it really scalable?


texts: Overcoming Rackspace Cloud Files 10,000 object limit

texts:
Original question from Craft Slack:

Is there anyway to hack the AssetIndexTool to start at a certain asset/position/filename/index?

We’re using Rackspace Cloud Files and have around 25k images loaded. However, Cloud Files is limited to returning 10,000 objects per “page”. And it doesn’t look like Craft will paginate these objects. Wondering if we can just hack it to start the asset indexing at a certain place instead of starting at a certain index/filename, etc.


texts: Need to build products page with filters (price, category,..etc)

texts:
I need to build a product page with filters on the side to filter the product by : price ( less than 100, between 100 and 200 , between 200 and 300 , greater than 300 )
and also by category,
Category only now is working :

{% if category is defined %}
   {% paginate craft.commerce.products.relatedTo(category).limit(limit) as products %}
{% endif %}

Not using variants right now.

regards


texts: Basics of overriding an admin page template - Craft 3

texts:
I want to override the admin/users page template when a plug in is installed.

Detail:
On the user page domain.com/admin/user all the groups are listed in the sidebar area. I get this from the \vender\craftcms\cms\src\templates_layouts\cp.html file. I want to install/use use a custom template for the user page using a plug in.

What are the basics of overriding a admin template through a plugin?

Edit - More detail:

I have a plugin that creates a new controller exactly the way that is proposed in this post. The controller does two things (maybe more later):

1) On entries page it displays all the entries to a logged in user that was posted by them and others from their same group. It does not display entries that were posted by users in other groups.

2) On user page it displays only users from their own group. It does not display any other users from other groups.

On the users page all the groups are listed here:

It does not make sense to display all the groups here as the logged in user can only see or edit users in their own group.

I need to change what is displayed in the group listing area.


texts: {% block content %} is a no-go in template/subfolders

texts:
I’m on a mac running MAMP and my install is functional. Localhost will direct to and display files in “templates” but it wont fully cooperate with subfolders within templates, such as templates/news. From templates/news/_entry.html, I’m able to {% extends "_layout" %} to the _layout.html, but I can’t call up anything via the block. Using {% block content %} is a no go.

I’m sure it’s a simple fix, but it’s hard to search for an answer when I don’t know where to start. Can anyone help?

Attached is a screengrab of my templates folder. You might notice from the "brews" folder that I've been following the Mijingo tutorial for Craft CMS. Nonetheless, the default "news" folder also doesn't load the block.


texts: Craft on Heroku is not logging. How can I make it start?

texts:
I don't have any logs appearing in craft/storage/runtime/logs (in fact I don't have anything at all in craft/storage/runtime.  I'm running Craft on Heroku.  I've tried setting post-install scripts in the composer.json file to run

chmod -R 774 craft/storage

but it doesn't change the permissions (they remain at 700).  We run Papertrail to collect logs from the dynos, but these only seem to include web requests - no application logging.  I've tried enabling devMode, but it makes no difference.

I'm trying to debug some issues we have with the application occasionally falling over, but without access to logs it's impossible - is there any way to make Craft start logging?  Just logging to stdout would be fine, as Papertrail would collect the logs. I can't find any configuration options, maybe I've missed them?


texts: Where do we get the SMTP Authentication information?

texts: We are trying to get Office 365 working with a Craft website.  How do we know what the host name and port number is.  Plus, under SMTP authentication setting is asking for a username & password, where do I find this?


texts:
I have a controller which is eventually going to be set up for POSTs and GETs, but the weird thing is I can only access it through localhost/index.php?p=actions/twoFA/get where twoFA is my plugin handle and get is an action method in my controller. How can I make it so that it behaves like all the examples online where I could go to localhost/actions/twoFA/get? What's happening? Also, my actionTrigger is set to actions and I have not set up any site routes in my plugin.

UPDATE: I have decided to make this work a little differently, and I therefore do not need any help.


texts: How to check if an Image Transform exists?

texts:
Is there an elegant way to check if an image transform exists?

{% if craft.imageTransformExists('thumb') %}
  <img src="{{asset.getUrl(thumb)}}" alt="Image">
{% else %}
  This image transform doesn't exists, please create it
{% endif %}


texts:
I've got this

    // Creating users through frontend
    Event::on(Users::class, Users::EVENT_BEFORE_ACTIVATE_USER, function(UserEvent $event) {
        $userId = $event->user->id;

        // Allow assigning user groups through the frontend (circumvent elevated user sessions)
        $groupId = Craft::$app->getRequest()->getBodyParam('userGroup');
        if ($groupId) {
            Craft::$app->getUsers()->assignUserToGroups($userId, [$groupId]);
        }

        // This does not work
        Craft::$app->users->getUserById($userId)->setFieldValue('discountPercentage', 15);
    });

Assigning the user group works fine, so I don't get why assigning a field value doesn't. The discountPercentage field is a simple Number fieldtype

I also tried $event->user->setFieldValue('discountPercentage', 15); without success.

Also I tried surrounding 15 in quotes, like '15', but that didn't work either.

Edit:

Submitting the "create user form" through the frontend gives no errors. discountPercentage is just left blank.


texts:
Without taking the time to explain the reason behind the requirement, I need to make about 3,000 empty entries.

How can I do this, that is how can I generate X number of entries without manually saving them from the admin area, outside of writing my own plugin? I don't think there's any good way to just write some SQL and barf them into existence right inside the database :(

Edit:

So I'm fairly certain this would have to be done via custom plugin development if it is indeed possible. I've never made a Craft plugin before, so I'm a little gunshy!

I imagine the structure of the plugin would be something like this:

public function onSaveEntry(Event $event)
{
    $title = $entry->title;

    for ( $i = $title; $i<8000; $i++)
    {
        do
        {
            public function saveEntry(EntryModel $entry)
        }
    }
}

Now, this is pseudo-code at best. I'm not sure what to exactly do here. But I hope this illustrates my thinking:

When I save a new entry, I want this thing to fire.
Right now my entries have auto-generated titles: take the last entry and add one: 5000 -> 5001 -> 5002, etc.
As long as we have less than 8000 entries (technically 3000 entries, as our entry titles will be 5000 - 8000) we want to keep saving new entries.
Once we finally save an entry with a title of 7999 or 8000, stop making entries.

Is this possible? What do I need to do?

Thank you soooo much to whoever out there can help me out!


texts:
I'm trying to add Heap Analytics as a tracking tool to my Craft site. From Heap's installation docs, I need to add this code snippet before the closing  tag. I'm pretty new to using Craft, can someone please explain how to go about doing this?

Code snippet:

<script type="text/javascript">
    window.heap=window.heap||[],heap.load=function(e,t){window.heap.appid=e,window.heap.config=t=t||{};var r=t.forceSSL||"https:"===document.location.protocol,a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=(r?"https:":"http:")+"//cdn.heapanalytics.com/js/heap-"+e+".js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n);for(var o=function(e){return function(){heap.push([e].concat(Array.prototype.slice.call(arguments,0)))}},p=["addEventProperties","addUserProperties","clearEventProperties","identify","removeEventProperty","setEventProperties","track","unsetEventProperty"],c=0;c<p.length;c++)heap[p[c]]=o(p[c])};
    heap.load("YOUR_APP_ID");
</script>

Heap installation instructions: https://docs.heapanalytics.com/docs/installation


texts: Is there an easy-to-follow tutorial to learn Craft CMS basics?

texts:
I am thinking about using Craft CMS for building multiple websites for my organization. A friend recommended Craft CMS, but I am finding it very hard to get started, unlike GRAV, which was very easy to install and use.

I am looking for a tutorial that steps users through the building of a simple website from A to Z and in the process explain why Craft CMS should be given more consideration over other tools.

I looked online only to find a few such tutorials, but you have to pay to access them. I am in the evaluation phase and do not want to pay for something that I might not use.

If anyone knows of a good and comprehensive tutorial, please let me know.


texts: Is it possible to repopulate radio button inputs with values from submission.fieldMetaData using the standard form.render() method?

texts:
I've been able to repopulate text fields this way, but the radio buttons remain unchecked even when there was a value submitted.

{% for field in application.fieldMetaData %}
    {% set submittedValues = submittedValues|merge({ (field.handle): attribute(application, field.handle).value}) %}
{% endfor %}

{% if form|length %}
    {{ craft.freeform.form(form.handle, {
      returnUrl: '/',
      overrideValues: submittedValues
    }).render() }}
{% endif %}


texts: How can I ensure using actionUrl in my template does not show script name in the generated URL?

texts:
I have an controller action in my custom plugin that processes Paypal IPN requests. How it works is that you provide a URL for Paypal to send it's notification requests to and then process them and send an acknowledgement.

I'm using {{ actionUrl('plugin/action') }} in my template to generate the URL that I provide to Paypal, but no matter what I try I can't get it to omit the script name from the URL. $omitScriptNameInUrls set to true in config has no effect.

This is necessary, because I need to do some checking in my config file based on the URL to disable CSRF protection for only the Paypal IPN controller action, as described in this question: What's the best way to skip CSRF for plugin controllers?


texts: Site search that matches in more than one field

texts:
I'm wondering how to conduct a site search that takes search words and matches them in more than one field. So for example if I have an entry with fields that contain the following words:

Description Field: foo

Body Field: bar baz

A search for 'foo', or 'bar', or 'bar baz' finds the entry, but a search for 'foo bar' does not.

I have rebuilt the search index.


texts: How do you display user photo in templates?

texts:
I tried using the following but it's not working:

{% if entry.author.photoUrl|length %}
<img src="{{ entry.author.photoUrl(84) }}" alt="" />
{% else %}
no photo
{% endif %}

Also, another question of mine is... when i upload a user photo on the profile tab, am I suppose to see the photo's thumbnail? All I see is the upload box with the button but the file seemed to have uploaded successfully to /craft/storage/userphotos


texts: Wrong siteUrl chosen in multi-environment config

texts:
I have following setup for my site urls (after other testing domains):

return [

    '*' => [
        'omitScriptNameInUrls' => true,
        'usePathInfo' => true,
        'generateTransformsBeforePageLoad' => false,
        'convertFilenamesToAscii' => true,
    ],

    'mp.mydevserver.pizza' => [
        'devMode' => true,

        'siteUrl' => [
            'en' => 'http://mp.mydevserver.pizza',
            'de' => 'http://mp.mydevserver.pizza/de',
        ],
    ],

    'mypage.com.mydevserver.pizza' => [
        'siteUrl' => [
            'en' => 'http://mypage.com.mydevserver.pizza',
            'de' => 'http://mypage.com.mydevserver.pizza/de',
        ],
    ],

    'mypage.com' => [
        'siteUrl' => [
            'en' => 'http://mypage.com',
            'de' => 'http://mypage.com/de',
        ],
    ],

];

The staging domain is mp.mydevserver.pizza

The acceptance domain is mypage.com.mydevserver.pizza.

The production domain is  mypage.com

Staging works fine. But on Acceptance, Craft always uses mypage.com as Site Url. I can reach the site, but ofc, every link is wrong. I've read that in this case the order matters and the mypage.com.mydevserver.pizza would have to appear first. But it actually IS before the mypage.com entry in the array?

Why is it picking the wrong settings?

Thanks, Robert


texts: Route manipulating - set regioncode before language-code

texts:
I just finished the structure of a new site, now I am faced with the problem: "regions". I thought I can use categories for routing.

Because I need:

  example.com/REGION/LANGUAGE/about-us
  or
  example.com/fr/en/about-us in reality -> frensh region, english language

First problem: Localize all content and get the language parameter in the URL - CHECK, this is done (i got example.com/en/about-us - quite easy)
Second problem is, how to get the category (top level) into the routing (not done, I am struggling with this)
Third problem - and maybe biggest problem - how could I switch the both parameters, because any URL-part is placed AFTER the language parameter. So I would get
example.com/LANGUAGE/REGION/about-us
if I complete the second problem and not
example.com/REGION/LANGUAGE/about-us
This has to be possible with craft or a workaround, but I do not get it. Maybe someone has a solution or a hint for this in other CMS I solved this structure, but in Craft....well....not yet


texts:
When I download the Craft CMS and try to unpack it. I get the error: "Unexpected end of archive". It seems the download pakage is not complete. When I browse in the .zip file I only see a craft folder (and no public).

Anyone can give me a good download link?

Thanks in advanced


texts:
How do install a Twig extension in Craft? Not write my own extension, but install an extension that exists. I want to install the extensions extension. There are a number of posts that describe how to write your own extension, but I can't see how to just install one. The Twig docs says add this: $twig->addExtension(new Twig_Extensions_Extension_Array()); but obviously I don't want to edit core Craft.

I found this - How do you add a core twig extension in plugins using addTwigExtension()?, but the responses just convince the poster that he doesn't need to use that extension. What if he wanted to use it? How do you install it?


texts: Not showing the entry somewhere else on the same page

texts:
In the footer there is a column showing the images of the most recent entries. How do you prevent the image from the main entry itself to be shown?

Do you test an url segment against the title or slug?

This cannot be too complicated, but I am not able to find an example to get me started.

Added Code (thank you Robin)

{% set recents = craft.entries.section('sectionName').id('not ' ~ entry.id).all() %}
{% for entry in recents %}

{% endfor %}

One more question:
How do you limited the output using the elementCriteriaModel? Invoking Limit(x) on the array is not possible.


texts: How do I send an email to multiple recipients?

texts:
In my plugin, I'm sending an email like this:

$recipients = 'person@example.com';

$email = new EmailModel();
$email->toEmail = $recipients;
$email->subject = 'My Email Subject';
$email->body    = 'My Email Body';

craft()->email->sendEmail($email);

Which works great! But when I'm sending to multiple people, the string would look like this...

$recipients = 'person1@example.com, person2@example.com';

... and it generates an error:

Invalid address: person1@example.com, person2@example.com

How do I properly send an email to multiple recipients?


texts: Add a second template field in section settings via plugin

texts:
I would like to add a second default template field for each section's Site Settings, via plugin. Where would I look to see how to do this?

How would I access this value in my plugin's code? How would I parse the template path to use to render an entry?


texts:
We're using Craft Commerce 3.2.11 and Stripe as the payment gateway.  We can put through a purchase using test cards no problem, but when we try with an actual card we get the message:
paymentMethodID payment method id cannot be blank
Is there anything else we need to do to put through a live card?


texts:
How can you change from instant search and faceting to a search bar with auto-completion? SearchPlus comes with an excellent sample template but this is set to instant search, which means all entries in the index are displayed. I want to have a search-bar only and when typing the search query the relevant entries start to appear (auto-completion).

Also, if there is no excerpt field available in the indexed entries, would it be possible to create one, with Twig split?

{% set paragraphs = entry.body|split('
') %}
{% set firstParagraph = paragraphs|first ~ '
' %}

{{ firstParagraph|raw }}


texts: Matrix field breaks backend Entries > 'page-name' page. "Endless" recursion error?

texts:
In backend Entries > 'page-name' I could only see the left nav side bar, and the top "header" bar (breadcrumbs + page name + save button), when ever there was a Matrix field on the page.
I noticed that the last line rendered (marked in blue) had a height of 0, so I started poking around in the CSS.

After disabling a display: none; (marked in green below) for the div immediately below the last div shown, I could see part of the page plus the error message shown in the screenshot below.

To me, it looks like some "endless" recursion error.

Does anyone have any idea on what might be going on here?

Thanks in advance for any light you might shed on this!

/Monkey

Edit: added the top screenshot to show what the page looked like before I changed the CSS.


texts: Select statement validating as true when no value selected?

texts:
I have a plugin with record and model both setting required to true for a frontend form entry:

'fieldName' =>  array(AttributeType::Name, 'required' => true),

However it is still validating the select option even when there is no value so:

<select id="fieldName" name="fieldName">
    <option>--select one--</option>

or

<option value=''>--select one--</option>

Still validates as true.

How can I get around this?


texts: Element query: find entries where a field's value is greater than, or less than another field's value?

texts:
I would like to do something like this:

craft.entries.section('mySection').field1('> field2').all()

And it should return all the entries in mySection whose field1 value is greater than their field2 value.

Is it possible?


texts:
For production site, the backend url is like - 'www.abc-prod.com'
While the actual live site url is - 'www.xyz.com'

When opening live preview for an entry, page never loads. Instead '301 Moved Permanently' is the status of response.

I have enabled CORS by adding following headers in response-

  Access-Control-Allow-Origin: https://www.abc-prod.com
  Access-Control-Allow-Headers: origin, x-requested-with, content-type
  Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
  Access-Control-Allow-Credentials: true

Still getting blank page for live review. What exactly I am missing?


texts:
Is it possible to allow certain payments per user in Craft Commerce and if so how and if not how would it be possible?

Just breaking my head around it.


texts: How can I determine if a user is logged in, and who that user is?

texts: I'm running some checks to see if there is a user logged in, and if that user is someone specific. When accessing user.isCurrent it's returning 1 when I'm logged in, but returns null when I'm not. Should this be returning 0 or false in that case, or should I be checking {% if user.isCurrent is defined %} ?


texts: Craft 3 Multi Site - Entries/categories/assets fields aren't translatable?

texts:
I'm testing out the Craft 3 beta's multi-site capability at the moment to see if it's suitable for an upcoming project.

My sample scenario is a school that runs out of multiple countries. They offer the same courses, but may want to tailor the content for different countries.

If we want different tutors assigned per site (country) to this course, we can't as an entries field (pulling from teachers section) is not translatable/multi site capable.

We run into the same problem with using matrix fields for content. We generally have a general content matrix field that allows the client to build their content with different pre-defined blocks (side by side images, text with image, full width text, video etc. etc.). But matrix fields aren't translatable either.

Same for images etc. There are a few other scenarios where this would raise its head just in this one example.

For this feature to be usable for how we use Craft, we'd need multi site support on those field types. Is this something that's coming or should I start thinking of another solution?


texts: Get entries by month, but not restricted by year

texts:
I'm building a calendar functionality and I need to get entries by month, but they cannot restricted by year (as, for example, the calendar might have entries that fall on both Jan 2017 and Jan 2018).

At the moment, I'm doing a for loop and incrementing to get the next 5 years:

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

{% if categoryParam %}
  {% set allDates = [] %}

  {% for i in 0..5 %}
    {% set year = now|date('Y') + loop.index0 %}
    {% set combinedDate = '1970-' ~ categoryParam ~ '-01' %}

    {% set startDate = year ~ '-' ~ combinedDate|date('m') ~ '-01' %}
    {% set dayCount = startDate|date('t') %}
    {% set endDate  = year ~ '-' ~ combinedDate|date('m') ~ '-' ~ dayCount %}

    {% set courseDates = craft.entries({ section: 'courseDates', limit: null }).order('courseStartDate').courseStartDate('and','>= ' ~ startDate, '<=' ~ endDate) %}

    {% for courseDate in courseDates %}
      {% if courseDate not in allDates %}
        {% set allDates = allDates|merge([courseDate]) %}
      {% endif %}
    {% endfor %}
  {% endfor %}

{% else %}
  {% set allDates = craft.entries({ section: 'courseDates', limit: null }).order('courseStartDate').courseStartDate('and','>= ' ~ now) %}
{% endif %}

I'm just wondering if there is a better way of doing this that doesn't rely on the year?


texts: In Commerce how can I have a customer update custom fields on an order after the order is completed?

texts: I'm using Commerce, and Orders can have a custom field on them. I need customers to be able to update that field from a front end form. I can't use the built in contoller for Orders because that requires Admin users.


texts: Calculating a score based on a drop down field value

texts:
I am storing a value (number 1-5) in a drop down field and would like to do a calculation based on the numbers filled in.  The only way I could get my calculation to work was to store the number (1-5) in a number field (not a drop down field) so I'm wondering if it's because the drop down content is seen as a string and not an integer. If so, perhaps I need to convert the string to an integer.  Although I have it working with the value (1-5) stored in a number field, I'd like to understand how I could make it work with a drop down.  I saw another post that sounded similar: How can I convert a dropdown field value to an integer within a hash?

Here is my template code that works with my number field:

        {% set imageQualityScoreAorta = craft.entries.section('logsQA').logGeneral_statusWorkflow('reviewed').search('logGeneral_studyType:aorta -logReviewer_imageQualityNumberTest:0').relatedTo(
            { targetElement: currentUser, field: 'logGeneral_sonographerName' }
        ) %}

        {% if imageQualityScoreAorta|length %}

            {% set additionAorta = 0 %}
            {% set countAorta = 0 %}

            {% for entry in imageQualityScoreAorta %}
                {% set additionAorta = additionAorta + entry.logReviewer_imageQualityNumberTest %}
                {% set countAorta = loop.index %}
            {% endfor %}

            {% set averageValueAorta = (additionAorta / countAorta)|round(1, 'floor') %}
        {% endif %}

This is the output:

            Aorta
            {% if imageQualityScoreAorta|length %}
                {{ averageValueAorta }}
            {% else %}
                N/A
            {% endif %}


texts: How do I clear deprecation errors for looping through element queries?

texts:
I am getting this depreciation messages.

  Looping through element queries directly has been deprecated. Use the all() function to fetch the query results before looping over them.

In the example below, the depreciation message refers to the 2nd loop for flag in country.  The message appears anytime I have a loop within a loop.

How do I template this to avoid the deprecation message?

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

{% for first in entries[0:1] %}

{% set country = first.countryName %}

{% for flag in country %}

{% endfor %}

{{ first.title }}

 {% endfor %}


texts:
I am getting an Apache 404 page when trying to install Craft after following all instructions. I've run out of ideas.

Set up a droplet running LAMP on Ubuntu 14.04 with Digital Ocean
'craft' folder is sitting in public at 'var/www' and index.php on
the same level is pointing to $craftPath = './craft';
.htaccess is running
set folder permissions
Created MySQL database with new user
Updated db.php
Have tried example.com/admin and
example.com/index.php/admin and
example.com/index.php?p=admin

Have tried moving craft folder above root and updating $craftPath but with no luck. Not sure what else to try?


texts: How is Craft able to reuse fields in different Sections? (As opposed to EE.)

texts: I'm a HUGE fan of Craft, but I'm wondering how specifically it's able to reuse fields in different sections. I'm very accustomed to an ExpressionEngine environment, where each field's shortname has to be unique. How did P&T build Craft so this is possible?


texts: P&T Contact Form plugin : how can I dynamically add multiple email recipients inside the form config file?

texts:
I don't want to show up the email recipients in the source code using this :

<input type="hidden" name="toEmail" value="{{ 'me@example.com,me2@example.com'|hash }}">

I want to manage multiple emails dynamically from the contactform.php config file in my craft/config folder.

<?php

return array(
    'toEmail' => (hash('firstemail@domain.com, secondemail@domain.com') ?: null),
);

This config file is not working and don't override the plugin settings in the CP. What would be the best way to achieve this ?

[UPDATE]

I ended to this, but while it is working fine in the front end, this is causing PHP errors in the CP :

<?php

return array(
    'toEmail'  => array(
        ('firstemail@domain.com' ?: null),
        ('secondemail@domain.com' ?: null)
     )
);


texts:
I have a matrix field with a category field. I need to group these matrix items by category and give them headings which I'll use for tabs.

This is how I'd do it for entries but is it possible for matrix?

    {% nav category in craft.categories.group('otherAppliances') %}

    {% set itemCount = craft.entries.relatedTo(category).total() %}
        {% if itemCount %}

{{ category.title }}

        {% endif %}
    {% endnav %}

I think my question may be similar to How to query with relatedTo of a Relationship Field in a Matrix Field block but I can't get my head around it.

Matrix setup:


texts:
I'm selling the same website build in Craft to multiple clients and was wondering if it is possible to clear all user generated content of an install.

So delete all the entries, categories, assets, globals, ...


texts:
I have a matrix field with a block called "employment", under this block are fields, one of those fields is a drop down.

I'd like to be able to output the drop down field as a select list so users can choose from it.

Note: that I'm NOT trying to output what a user has selected, I just want to output the options from which a user can select.

Thanks!

UPDATE

That's not really what I'm after. Let me be more clear.

The matrix field I'm speaking of is attached to the user model but I'm not trying to output the user's data saved for the matrix. What I'm trying to do is simply output a field of a given matrix.

I am able to load the matrix doing this:

{% set matrix = craft.fields.getFieldByHandle('employmentMatrix') %}

But I'm not sure how to access the matrix's blocks then fields. I tried this:

{% set matrix = craft.fields.getFieldByHandle('employmentMatrix') %}

{% set blocks = craft.matrix.getBlockTypesByFieldId(matrix.id) %}

But I get an error saying "matrix" is not a method.


texts: Login Page Logo and Site Icon with Project Config

texts: How does one configure the rebrand options (Login Page Logo and Site Icon) with project config enabled? The fields to upload these files usually appear under Settings > General. This is only visible on environments where allowAdminChanges is set to true. How does one configure these on production environments where 'allowAdminChanges' => false is the norm?


texts:
Got Imager running great on my S3 hosted images. However it's cacheing transforms locally on my server. I'd like to save some disc space and have the transforms on S3 too, but struggling to get my config right. I've created a couple of folders on S3 (imagertransforms) and added the following to my imager config:

'imagerSystemPath' => 'imager/',
'imagerUrl' => 'https://myaddress.s3.amazonaws.com/_imagertransforms/',

Doesn't seem to be working though and not sure how best to debug. Am I missing something?


texts:
Is there a way to pass value of an entries field into category URI format?

{% if object.level == 1 %}

{slug}-{entries.one().slug}

{% else %}

{slug}-{parent.uri}

{% endif %}

Thanks.


texts: getHeadHtml() not outputting CSS included with {% includeCss %}

texts:
I think there is a bug in the getHeadHtml function of craft. In the Documentation (https://craftcms.com/docs/templating/includecss) it says:

  Your CSS snippet will be output by the getHeadHtml() function. If you aren’t calling that function anywhere, Craft will insert it right before the HTML’s < /head> tag.

But in my templates it works only, if the tag getHeadHtml() is placed after the includeCss Tag.
So the following simple Example does not work as expected:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Title</title>
    <!-- Here should the CSS start -->
        {{ getHeadHtml() }}
    <!-- Here should the CSS end -->
  </head>
  <body>

      {% set myCss %}
        .content {
            color:  red;
        }
      {% endset %}

      {% includeCss myCss %}

  </body>
</html>

It outputs the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Title</title>
    <!-- Here should the CSS start -->

    <!-- Here should the CSS end -->
  <style type="text/css">
  .content {
            color:  red;
        }
  </style></head>
  <body>
  </body>
</html>

It outputs the CSS before the closing < /head> Tag and not between the two comments. Is there any workaround/fix for this?


texts: How to render a Twig template in the element-api plugin (v2.5)

texts:
I want to render a Twig template in an API endpoint. Specifically I need HTML for the JSON Feed field "content_html".

My attempts until now (inside the transformer function):

$view = Craft::$app->getView();
$template = $view->resolveTemplate('_blog-entry');

// first attempt:
$html = $view->render($template, ['entry' => $blogpost]);

// second attempt:
$controller = Craft::$app->createController('templates/render')[0];

$html = $controller->render($template, ['entry' => $blogpost])

But in both ways it says "Template not found" even if the path after the "resolveTemplate" is correct.

Has anybody an idea how to do it? Thanks!


texts: How to perform a redirect and pass on data?

texts:
I have a Controller Action which should pass on some data from one (CP) template to another:

Template 1 (plugin/form): Form sends data
Controller redirects data to Template 2
Template 2 (plugin/): Shows data

I don't want to just load the template but redirect to plugin/ and show the data, any ideas?

public function actionTemplate()
{
    $data = 'Something';
    $this->redirect( 'plugin_handle' ); //Pass on $data to 'plugin/'
}

Edit 1:

Or is there a way to send a post-request to a "route" rather then an actionController?


texts: How can I determine which user triggered an update?

texts: Recently a user, using the admin panel, triggered a Craft CMS update. I would like to determine which user it was.  Is there any log of these actions where I can check for this?   If it's in craft/storage/runtime/logs/craft.log, can you please tell me what to search for?


texts: Is there any way to set a default status for Entries, either globally or per Section?

texts:
The subject more or less covers it — is there any way to set the default status for Entries, either on a Section by Section basis, or globally?

I have a client that doesn't want to accidentally set something live when they save something without deliberately setting it to published.

At the moment it looks like I have two options:

Create an un-Crafty "Publish" checkbox field that I check for in my templates.
Use User Groups to keep some users from publishing — this is a little overkill for them, though. They don't want to keep these people from publishing, just try to limit people publishing content without meaning to.


texts:
I have an Events section on my site, and to display upcoming and passed events (entries with a status of pending or expired) I manually set the entry in the template:

Where the URL is /events/my-event-title

{% set entry = craft.entries({
    section: 'Events',
    slug: craft.app.request.segment(2),
    status: ['live','pending','expired']
}).one %}

<h1>{{ entry.title }}</h1>

{{ entry.body }}

This works great except when I go to publish a new Event and use the Live Preview. Since the new entry doesn't have a slug yet, the craft.app.request.segment(2) variable returns null, and so entry returns the last-published Event entry instead. So all of my template variables are pre-populated with a different entry's content.

How do I set this up so my Live Preview displays blank until I enter content?


texts: Check for errors (any) on guest entry form (Craft 3)

texts:
I have a guest entry form that's working fine. I'm using Craft-supplied code:

{% macro errorList(errors) %}
  {% if errors %}
    {% for error in errors %}
      {{ error }}{% if not loop.last %}, {% endif %}
    {% endfor %}
  {% endif %}
{% endmacro %}

And it works fine - field by field:

{% if entry is defined %}

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

{% endif %}

But I can't figure out how to check if there are any errors (and error in any field) so I can display a notification at the top of the page: "There were some problems with your submission".

{% if errorList(entry.getErrors())|length }}

doesn't work.


texts: Dynamically load craft entries based on twig variable

texts:
I am looking for something quite simple, but I still can't find a way to do it in twig syntax. So basically here is my code:

{% set upperlimit = 3 %}
    {% for entry in entry.getChildren() %}
        {% if loop.index0 < upperlimit %}
            <button type="button" class="btn btn-default ma-category-btn {% if loop.first %}first{% endif %} {% if loop.index == upperlimit %}last{% endif %}">{{ entry. title }} </button>
        {% endif %}
    {% endfor %}

<button type="button"  class="btn btn-default ma-more-category-btn">VIEW MORE CATEGORIES</button>

Basically when I click on the button "VIEW MORE CATEGORIES", it should load the next three children and create three more buttons like the ones in the for loop if there are enough children for that entry.

Is it possible to have this dynamic behaviour in craft and twig?


texts: I'm new to using craft cms and have been using this site to answer several questions. I decided I should give back. I have been using the Embedded Assets plugin but could not figure out the "for loop" code in a Matrix field to display links to all selected YouTube videos.


texts: Feature Stages with Craft CMS and Project Config

texts:
We plan to use Feature Stages in the Future to have the possibilities to decouple features better on our stage environments. Currently we have one stage like:
stage.domain.com and any branch can deployed there.
In the future we plan a system like:
master.domain.com
issue-1.domain.com
issue-2.domain.com
issue-3.domain.com
My question is if someone have experience with setups like this especially with project config.
We have a shared Database across all this stage environments. When someone do changes in the project config this has concerns to all other stages. Is there a way to handle that or is the one and only solution to have a own database for each stage environment?


texts: Locale URL segment being duplicated, eg https://website.test/en/en/

texts:
Problem

I have a problem on a local Valet setup: the locale URL segment is appearing twice in URLs.

Eg from a page at URL of en/about/approach, {{ url('about/approach')}} outputs https://website.test/en/en/about/approach

(And you only get the correct URL if outputting this from /about/approach)

Guessing I've missed something obvious but no idea what... thanks!

Setup

Base URLs are set to @web/en/ and @web/de/.

In the web folder we have two index files, eg de/index.php and en/index.php

Running valet which reports This site is served by [CraftValetDriver].

In general.php I've got:

'test' => [
// Base site URL
'siteUrl' => 'http://website.test'

The Entry URI Format for the Pages section is {parent.slug}/{slug}

Contents of /web/en/index.php:

<?php
/**
 * Craft www bootstrap file
 */

// Set path constants
define('CRAFT_BASE_PATH', dirname(__DIR__, 2));
define('CRAFT_SITE', 'english');
define('CRAFT_VENDOR_PATH', CRAFT_BASE_PATH.'/vendor');

$root = dirname(__DIR__).'/en';

// Load Composer's autoloader
require_once CRAFT_VENDOR_PATH.'/autoload.php';

// Load dotenv?
if (file_exists(CRAFT_BASE_PATH.'/.env')) {
    (new Dotenv\Dotenv(CRAFT_BASE_PATH))->load();
}

// Load and run Craft
define('CRAFT_ENVIRONMENT', getenv('ENVIRONMENT') ?: 'production');
$app = require CRAFT_VENDOR_PATH.'/craftcms/cms/bootstrap/web.php';
$app->run();

Contents of /web/index.php:

<?php
/**
 * Craft web bootstrap file
 */

// Set path constants
define('CRAFT_BASE_PATH', dirname(__DIR__));
define('CRAFT_VENDOR_PATH', CRAFT_BASE_PATH.'/vendor');

// Load Composer's autoloader
require_once CRAFT_VENDOR_PATH.'/autoload.php';

// Load dotenv?
if (file_exists(CRAFT_BASE_PATH.'/.env')) {
    (new Dotenv\Dotenv(CRAFT_BASE_PATH))->load();
}

// Load and run Craft
define('CRAFT_ENVIRONMENT', getenv('ENVIRONMENT') ?: 'production');
$app = require CRAFT_VENDOR_PATH.'/craftcms/cms/bootstrap/web.php';
$app->run();


texts: In Craft 3 how do I find the title of the previous and next entry when looping through a channel?

texts:
{# Set parameters for prev/next elements list #}
{% set params = craft.entries.section('nieuws').all() %}

{# Get the prev/next elements #}
{% set nextEntry = entry.getNext(params) %}

This used to work in Craft 2 in v3 I get an unknown property error. I can retrieve the prev and next links via the paginate tag but how do I retrieve the titles of the prev and next entry??


texts: Query entries by matrix date fields for event calendar

texts:
I have a section Events with a matrix field (let's call it dates). The matrix features a single block type with a single date field. One Event can have multiple dates. Think theatre plays with multiple show dates.

Now I'd like to create a list of all events, ordered by the date field. This means that the same entry could show multiple times in the list (once for each date in the matrix field). I want to query all future dates in the matrix, fetch related entries, limit the number of items displayed and support pagination.

Ideally there is something like craft.entries but for matrix fields.

Example

The following example shows three different Event entries, ordered by their dates. Notice how the same entry can appear multiple times.

14/12/01 @8pm - The Great Gatsby (ID #1)
14/12/01 @8pm - Moby Dick (ID #2)
14/12/02 @3pm - Snow White (ID #3)
14/12/02 @5pm - Snow White (ID #3)
15/12/05 @7pm - The Great Gatsby (ID #1)

Can anyone point me in the right direction? I'm not afraid to dive into plugin development (already created a simple "Address" field type with geocoding support) but is there an easier way? Thanks for your time!


texts: Error declaring TLS Version wrong in Charge plugin

texts:
I am getting an error notice in the Squarebit Charge plugin saying This server doesn't support TLS 1.2. but when I check with the hosting provider (Arcustech, the best!) they assure me that the server does indeed support TLS 1.2

Further, I do not see any errors when I look at a charge detail in the connected Stripe account. This has just recently popped up on a few of my projects.

Make sense to anyone?


texts: Is it possible to add additional fields to the image popup in redactor? In addition to Title, Caption and Link.


texts:
I will build a group site in craft which will have the main domain and multiple sub domains.
e.g.
domain.com
property.domain.com
connect.domain.com

The news feed on each sub domain will be different but it will all display on the main domain news feed. The site build etc for each will be similar but content will be different.

What is the best way to set this up in Craft?

Is the following something which can be done.

Use Multi Environment Config to set the SiteURL for each domain.
Point all the domain/sub domains to the 1 public folder.

Within my main _layout.html template file detect what the siteurl is and based on that include different header and footer files for each sub domain?

The same news template files can then be used.
And just use a different structure for the nav on each sub domain.

Is that workable and the best way to do it or should I be having different root folders for each sub domain?


texts: Try out Craft Client and Pro on multiple development URLs?

texts:
I'm aware that running craft locally from "craft.dev" or "ontherocks.dev" will enable you to try out the Client and Pro versions (which is a super-cool feature!) - but just wanted to ask if there are any plans to allow any domain at *.local or *.dev.

Obviously totally understand not wanting to open it up too much, but just working on a few projects under development, which is a little hard to juggle on the one domain.


texts: Custom status based on chosen payment gateway

texts:
We're working on our first Craft Commerce site and are in need of your good advice. This might be related to a similar question (Craft Commerce: send notification emails when setting status dynamically?) but I can't comment there.

We have a Craft Commerce setup with two payment gateways for credit card and bank transfer (Manual payment). We'd like to achieve the following scenario:
1) If the customer pays with Credit Card, the order status is "Approved". They receive an email with the invoice and confirmation.
2) If the customer pays via bank transfer, the order status is "Pending" and they receive a different email.

We can't find any clues on the docs on how to pass a specific status on checkout. Is there anything obvious we might be missing? I appreciate any input. Thanks!


texts:
I created a section on a site that shows a two-month calendar. The calendar has links to entries based on a release date. The release dates are created using a date/time filed. (Dates are different than the entry release date)

I'm very happy with the results so far. I took some ideas from this answer and a little flexbox magic. Everything is working great for the current/next month to show.

What I'm looking for is some ideas on how to display past dates. I want to create an "archive" section of the calendar where people can navigate to a month in the past to see the events that took place in that specific month.

Should I create a category group called "months" and then manually add months as they pass, changing the DateTime object?

Any ideas on the best way to display months in the past would be greatly appreciated.


texts: Is there a way to check if entry is selected in relationship?

texts:
This project has a lot of user stuff. I need to display display different sections based on if the current user is in a field.

Is there a better/faster way than looping through and checking if every user matched the current user?

{% for approve in entry.docsApprovedBy.all() %}
   {% if approve.id == currentUser.id %}...{% endif %}
{% endfor %}


texts:
I'm using Feedme to import users from one Craft site to another via an XML feed. I'd like to include users passwords too. I thought that {{ user.password|hash }} would do the trick but when I test this out after import using one of the imported accounts I get the "Invalid email or password" error msg. I know the account has ported across, email address
is correct, and it's live. So must be something with the password. Can anyone help me out?


texts: Admin pages request a broken version of the craft.css file

texts:
We’re using Craft over SSL and everything is working fine apart from the admin fonts:

This is due to a mixed content, because craft.css is requesting the fonts from non-ssl URLs:

The CSS file requesting these non-ssl assets is:

/admin/resources/css/craft.css?d=1478612388

When I clear caches, everything works for one page load, then reverts to broken fonts on the next page load. This is because for one page load after clearing caches, the CSS file is requested with a different query string:

/admin/resources/css/craft.css?x=EVPBt6yJn

This file uses the correct SSL URLs for font files, as does any other variation on the query string.

I’ve tried completely emptying the storage directory.

I can’t find anything in the docs about how Craft generates these CSS files, or the query strings. Can anyone give me any pointers?


texts:
So, I'm building a portfolio site for a client, and I'd like to know if it's possible to hide fields on a parent entry. Essentially, I've created a structure for portfolio items, and they are all children of the main "Works" page. I've built a set of fields for each portfolio item, but I don't want those fields to show up on the parent entry, as they are unnecessary and therefore distracting. Is there a way I can do this?

Thanks in advance!


texts: How can I list previously viewed entries?

texts:
What approach should I take to create a list of previously viewed entries? Including the ability display the list, remove an entry from the list or delete the whole list.

The previously viewed entries list would only exist for the duration of a visit.


texts:
Here is my situation: I have a bunch of different series (which are each stored in a channel), and there are a bunch of sermons related to each series.

What I need to do is display the most recent entry of each series. Typically I would do this in a SELECT DISTINCT SQL query; How should I go about doing it in Craft?


texts:
The blog post should display the posts created but when I got to the slug /blog it says 404 not found as well as the press news should be displayed here /press-news but same thing happens.

If i access the posts directly : site.com/blog/blog-post-name it is displayed correctly.

an you help me giving me some probable causes so that i can check how to fix it? thanks


texts: Is it possible to use percentage values for width and height in image transforms?

texts: I'm working on creating an image transform to handle retina images. I upload the 2x assets and need an image transform to create my images at 50% their original size. Since images on the site can be varying widths and heights I am currently forced to create a new image transform for each image ratio. Percentage values would cut this down to a single image transform for everything.


texts: Freeform Email Notification HTML template not found

texts:
I have set up Freeform Email Notifications, but I need them to be HTML templates within my templates folder to access the entry that the form is attached to. The problem is that Freeform keeps giving me the following error when loading the template:

  Email notification template with ID test.html not found
  {"form":"Accepted"} []

My test.html is within /templates/ in my Craft Folder.
My form lies within the folder /templates/submissions/
It has the default header config from the docs.

This is how I'm calling my dynamic Notification:

{{ craft.freeform.form("accepted", {
  overrideValues: {
    entry: entry.id,
  },
  dynamicNotification: {
    recipients: entry.author.email,
    template: "test.html"
  }
}).render() }}


texts: How to output transforms for retina images from one upload?

texts:
I have a slide show that shows logos of different dimensions working well in HTML/CSS - the image output looks like below. I'd like to only upload one retina/hdpi image once for the entry where the asset is. I'd like to use image transforms to output the retina images but need to preserve the width and height of the original as they vary in look and dimensions. I can't find an example. I have read this post
10 times but not really seeing if this holds a solution.

HTML code:

[image tag srcset01] srcset="
    /assets/images/logos-sponsors/company1_logo.png 1x,
    /assets/images/logos-sponsors/company1_logo@2x.png 2x,
    /assets/images/logos-sponsors/company1_logo@3x.png 3x" alt="company1_logo" width="130" height="12">

[image tag srcset01]
 src="/assets/images/logos-sponsors/company2_logo.png" srcset="
    /assets/images/logos-sponsors/company2_logo.png 1x,
    /assets/images/logos-sponsors/company2_logo@2x.png 2x,
    /assets/images/logos-sponsors/company2_logo@3x.png 3x"
alt="company2_logo" width="52" height="30">

[image tag srcset01]  src="/assets/images/logos-sponsors/company3_logo.png" srcset="
    /assets/images/logos-sponsors/company3_logo.png 1x,
    /assets/images/logos-sponsors/company3_logo@2x.png 2x,
    /assets/images/logos-sponsors/company3_logo@3x.png 3x"
    alt="company3_logo" width="130" height="11">

The goal is to have the image uploaded once and then


texts: Craft Commerce 2: PayPal Express not working - Correlation id: unknown

texts:
I try to get PayPal Express running but have quite some difficulties.
I use the default templates for testing and can get through the whole checkout and payment process, but then PayPal closes and in the console I see the following

http.js:114 PaypalUncaught Error: Request to post http://xxx.local/index.php?p=actions/commerce/payments/complete-payment&commerceTransactionHash=xxx&token=xxx&PayerID=xxx failed with 400 error.
Correlation id: unknown
{"error": "Es ist nicht möglich, Ihre Dateneingabe zu prüfen."}

The error message can be translated to: It's not possible to check your data input.

In my Craft config, I changed the token name, as described here: https://github.com/craftcms/commerce-paypal

Any ideas what the reason for this could be?


texts:
I have an entry type called people which has a superTable field called programmeAffiliations, with three fields, jobTitle, researchProgramme, primary where:

researchProgramme is a category field (calling a category called programmes)
jobTitle is just a string
and primary is a lightSwitch.

A person can have multiple programmeAffiliations.

I've worked out how to get people via their programmeAffiliation.researchProgramme category:

{% set filterByProgramme = craft.categories
  .group("programmes")
  .slug("some-slug")
 %}

{% set people =  craft.superTable.getRelatedElements({
      relatedTo:
        {
          targetElement: filterByProgramme,
          field: 'programmeAffiliation.researchProgramme'
        }
      ,
      section: 'people',
      criteria: {
        "section": "people",
        "orderBy": 'lastName asc',
        "with": ['portrait', 'programmeAffiliation']
      }
}) %}

But I'm struggling to work out how:

1) To get all people who where primary == 1 on their programmeAffiliation

2) To get all people who have no programmeAffiliation at all

I can of course loop over the records returned and check, but it feels a bit hacky, and that ideally I really should be able to do this somewhere in the craft.superTable.getRelatedElements call. Thoughts?


texts: Problems while setting up a cross region Craft website in AWS

texts:
In order to create a cross region setup for my craft website, I've created a read-only replica of my RDS DB from North Virginia region to Canada Central region.

I'm facing the internal server error every time Craft is trying to update the session related info in the read-only database.

I could have used the same DB of N.Virginia but, if the N.Virginia region is down, then there will be no DB to support the server in the Canada region.So for this reason I've created a read only replica of the RDS at N.Virginia.

Why I'm choosing read-replica? Because AWS updates it automatically if we update the master DB. So I'll have to update in only one place and the slave RDS across regions will be updated as well.

How can I resolve this?
Or, what is the best approach to AWS cross region setup for Craft website?


texts:
I'm trying to build a filter and for that I want my client to be able to select a few options, which I use as classes for in my filter.

I chose for a checkbox field and set it up in the backend. Now I'm trying to retrieve the data on the HTML side, but I can only retrieve ALL values, instead of only the selected ones.

This is how my HTML/twig markup looks like

{% for option in entry.offerMinimumPrice.options %}
  {% if option.selected %}
    {{ option }}
  {% endif %}
{% endfor %}

With this code none of the values gets displayed in the front end. When I remove the conditional statement, all values get displayed (instead of only the selected ones).

Can anyone tell me what I'm doing wrong? Thanks!