texts: How to pull a single podcast source, using the Matrix field and loop?

texts:
{% if block.type == "podcastBlock" %}
    {% for category in block.podcastChannel %}
        {{category.title}}

        <audio class="mp3" controls>

        {% for entry in block.podcastChannel %}
            <source src="{{ entry.audioFile.one.url }}" type="audio/mp3">
        {% endfor %}
    {% endfor %}
{% endif %}`


texts:
Is possible to dump a query made on a twig template for a statement like this one for example:

craft.entries.section('homepage')

Can we some how see the actual SQL query ?


texts: Craft Commerce — Update order status from frontend?

texts:
Following on from this question Commerce: How to update an order status via the frontend
We'd like to make it easy for delivery drivers to update the status of a craft commerce order, from a frontend page. Doing it via the CP on mobile is a bit cumbersome as it involves multiple steps.
We've created a user group call couriers.
{% extends '_layouts/_logistics' %}

{% block logistics %}
    {% if currentUser and currentUser.isInGroup('courier') %}
        {% include 'logistics/_orders' %}
    {% else %}
        {% redirect 'account' %}
    {% endif %}
{% endblock %}

In the _orders include we'd like to show a list of orders, each with a 'Mark as Delivered' button, which can be clicked as the orders are fullfilled.
<dl>
    {% if order.shippingAddress %}
        {% include 'shop/_includes/addresses/address' with { address: order.shippingAddress } %}
    {% endif %}
    <dt>{{ order.reference }}</dt>
</dl>
<form method="POST">
    <input type="hidden" name="action" value="">
    {{ redirectInput('logistics') }}
    {{ csrfInput() }}
    <input type="hidden" name="orderStatusId" value="4">
    <input class="button button--primary" type="submit" value='Mark as Delivered'>
</form>

I'm wondering if this can be done, without the need to build a plugin or module? Else is there a plan to include the ability to do this in a future Craft Commerce release.
Many thanks,
Andrew


texts:
I'm trying to use the Craft Commerce example template code to show a progress bar throughout the checkout process. It currently doesn't correctly display the % value of progress through the checkout. It is just blank.

The url for my checkout is page is: website.com/shop/test/checkout

To see if it was a styling issue I did a test and set a manual override on the span's width with 50% - the styling then comes into play.

Has anyone else encountered this issue? I don't want to assume anything but the equation to make it kick in doesn't seem to be working.

    {% for key, step in steps %}
      {% set class = '' %}
      {% if craft.request.requestUri|slice(1) == step.url %}
        {% set width = ((key + 1) * 100 / steps|length) - 20 %}
        {% set class = "sel" %}
        {% set currentStep = key %}
      {% endif %}

      {% if currentStep is not defined %}
        {% set class = "done" %}
      {% endif %}

{{ step.label }}

    {% endfor %}


texts: __PHP_Incomplete_Class retrieved from session

texts:
I am storing a plugin model in session:

$sessionModel = My_Model::populateModel([
    'token' => 'someData'
]);

craft()->httpSession->add('someKey', $sessionModel);

When I retrieve that later:

$sessionModel = craft()->httpSession->get('someKey');

Craft::dd($sessionModel);

I get this:

__PHP_Incomplete_Class#1
(
    [__PHP_Incomplete_Class_Name] => 'Craft\\My_Model'
    [*:classSuffix] => 'Model'
    [*:strictAttributes] => true
    [Craft\BaseModel:_classHandle] => null
    [Craft\BaseModel:_attributeConfigs] => array
    (
        'token' => array
        (
            'type' => 'string'
            'required' => true
        )
    )
    [Craft\BaseModel:_attributes] => array
    (
        'token' => array
        (
            'token' => 'someData'
        )
    )
    [Craft\BaseModel:_extraAttributeNames] => null
    [CModel:_errors] => array()
    [CModel:_validators] => null
    [CModel:_scenario] => ''
    [CComponent:_e] => null
    [CComponent:_m] => null
)

Is there a better way to store a model in session? Should it be serialised and unserialised in some way?


texts:
have update craft and when uploading an SVG to Assets nothing happens? The upload bar pops up but the file is not uploaded and is not on the server?

Any ideas?  Thanks


texts: Protect entry so that only a "relatedTo" user can see it

texts: I would like to protect the viewing of an _entry.html page so that only a user related to that entry can view it.


texts: Adding a drop-down to Contact Form plugin

texts:
The GitHub page shows how to add additional fields as input fields or checkboxes. But I can't figure out how to add drop-down fields. Is this possible?

<select>
  <option value="——" selected="selected">Please select...</option>
  <option name="message[model][]" value="volvo">Volvo</option>
  <option name="message[model][]" value="saab">Saab</option>
  <option name="message[model][]" value="mercedes">Mercedes</option>
  <option name="message[model][]" value="audi">Audi</option>
</select>

Thanks!


texts: User registration form with checkbox field

texts:
Hi I have user registration form with multiple custom fields. They all work fine except for the field I have as a checkbox. It returns an error of 'my-field' is invalid. Any ideas anyone? code below (field in question is towards the bottom)...

<form method="post" accept-charset="UTF-8" class="login-form">
            {{ getCsrfInput() }}
            <input type="hidden" name="action" value="users/saveUser">
            <input type="hidden" name="redirect" value="{{ url('collection/') }}">

Register

To browse our collection please register your information below.

Already registered? Login.

            {{ entry.contentBeforeForm }}

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

                        {% for error in errors %}

{{ error }}

                        {% endfor %}

                {% endif %}
            {% endmacro %}

            {% from _self import errorList %}

First name

            <input id="firstName" type="text" name="firstName" {%- if account is defined %} value="{{ account.firstName }}"{% endif %} placeholder="First name">
            {{ account is defined and account ? errorList(account.getErrors('firstName')) }}

Last name

            <input id="lastName" type="text" name="lastName" {%- if account is defined %} value="{{ account.lastName }}"{% endif %} placeholder="Last name">
            {{ account is defined and account ? errorList(account.getErrors('lastName')) }}

Company

            <input id="company" type="text" name="fields[company]" {%- if account is defined %} value="{{ account.company }}"{% endif %} placeholder="Company">
            {{ account is defined and account ? errorList(account.getErrors('company')) }}

Phone

            <input id="phone" type="text" name="fields[phone]" {%- if account is defined %} value="{{ account.phone }}"{% endif %} placeholder="Phone">
            {{ account is defined and account ? errorList(account.getErrors('phone')) }}

Username

            <input id="username" type="text" name="username" {%- if account is defined %} value="{{ account.username }}"{% endif -%} placeholder="Username">

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

Email

            <input id="email" type="text" name="email" {%- if account is defined %} value="{{ account.email }}"{% endif %} placeholder="Email">

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

Password

            <input id="password" type="password" name="password">

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

            {# HERE IS THE FIELD CAUSING THE ERROR #}

            <input type="checkbox" id="termsAgreement" name="fields[termsAgreement]" {%- if account is defined %}value="1" checked{% endif %}>
             I agree to terms and conditions above

            {{ account is defined and account ? errorList(account.getErrors('termsAgreement')) }}

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

        </form>


texts: Craft directory 403 Access Forbidden with XAMPP

texts:
I've been using xampp for a long time and have never encountered a 403 error. I have many projects in my xampp/htdocs/ folder, none of them have ever had any problems until now. I have the craft files in a /craft folder inside htdocs but any time I try to visit files within this directory I am met with the 403 error.

I have been searching a solution for hours now, I edited httpd-vhosts.conf with the following but it didn't help:

<Directory "C:/xampp/xampp/craft/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order Deny,Allow
    Allow from all
    Require all granted
</Directory>

Again, no other folders within my htdocs directory has ever had any 403 errors. Anyone got a clue as to what is causing this and how to solve it?


texts: {{ entry.image.first().url }} won't show image

texts:
I am on my first Craft CMS test site. Have some problems showing a simple image.
<img src="{{ entry.hero.first().url }}" title="{{ hero.title }}">

I get the title but can't get the URL. The src attr is always empty. Tried a couple of variants like:

entry.hero.first().url()
entry.hero.first().getUrl()
with and without ()
etc.

But entry.hero.first().filename gives me "my_testfile01.jpg"
I can't see what is wrong.
File is local with path set to "./"
Image field has no sub path.
MAMP (Apache + PHP 7)


texts: MySQL ColumnType::Time does does not populate model from setAttribute()

texts:
I have a record with a time field set like this:

'startTime'         => array(AttributeType::DateTime, 'column'=>ColumnType::Time, 'required' => true),
'endTime'           => array(AttributeType::DateTime, 'column'=>ColumnType::Time),

The data is stored in the database as a string like this:

10:45:53

When I populate models from an elementCriteria query, the string value "10:45:53" does not work with creating a new DateTime object so I get false returned.

I would need to supply a full date in order to get a valid DateTime object back.

How should I deal with this? Is this i a bug in core? Why have ColumnType::Time if its not going to work correctly when pulling the value from the database?


texts: How to include twig in the editor? e.g. Shortcodes for dynamic content

texts:
I would like to display dynamic content in the middle of a text block. For example, a list of entries pulled in from the backend, in the middle of content.

In Wordpress we can use Shortcodes. Does Craft have something similar?

Can I just add an include statement to include a template? (I cant get this working using normal twig include code).

I could create a new field for someone to add in in between two other text block fields, but its quote over the top for what should be a simple include statement to include a template.

Thanks!


texts:
I have a section of "video" entries which are related to another section via an "area" field in the "video" section. When you do a search  on the front end by area then the related video displays as expected. What I also have in the area section is a text field full of postcodes, what I would like to happen is when you then do a search by postcode then the video displays that is related to that area, is that possible?

Here is my code that works for searches by area:

{% set query = craft.request.getParam('search') %}
{% set searchEntries = craft.entries.search(query).order('score') %}

{% for entry in searchEntries.video(':notempty:') %}
  {% set video = entry.video %}
  {{ video.embed({ width: 340, height: 191, showinfo: false }) }}
{% endfor %}


texts: Correct syntax for an OR conditional within a Matrix block

texts:
I have a dropdown Matrix block and need to check whether a selected value is either one or another.  If either value is selected I want to display some text on the front end.  At the moment I have {% if block.wellFormattedContent =='toBeActioned' OR block.wellFormattedContent =='partiallyActioned' %} but it errors.  Hopefully you can see what i'm trying to do.

Thanks

Martin


texts: Error on upload: "Impossible to create the root directory..."

texts:
In Craft 3.2.10, I'm getting this error message when I try to upload an image asset:

  Upload failed. The error message was: “Impossible to create the root
  directory "/Users/me/Work/Client/repo/web/craftcms-assets/project-slide-photos". mkdir():
  Permission denied”

I've made the permissions for project-slide-photos to 777 and 774, and likewise tried both for the parent directory. Is it trying to create a directory that's already there? I tried removing project-slide-photos also, and it still doesn't work.

What do I need to do to make my assets upload into this directory?

Edit: Wondering if using Docker Compose could have something to do with this:

docker-compose.yml:

version: '3'
services:
    web:
        image: 'flipbox/php:72-apache'
        ports:
            - '80:80'
            - '443:443'

        volumes:
            - '.:/var/www/html/'
        environment:
            ENVIRONMENT: dev
            DB_SERVER: db
            DB_USER: craft
            DB_PASSWORD: craft
            DB_DATABASE: craft
            XDEBUG_ON: "yes"
            XDEBUG_HOST: "host.docker.internal"
            XDEBUG_IDEKEY: "PHPSTORM"
            APACHE_DOCUMENT_ROOT: "/var/www/html/web"
    db:
        image: 'mysql:5.7'
        restart: always
        ports:
            - '3306:3306'

        volumes:
            # Location to import a database dump.
            - ./src:/docker-entrypoint-initdb.d
            # Location of the generated mysql files.
            - ./mysql:/var/lib/mysql

        environment:
            MYSQL_ROOT_PASSWORD: password
            MYSQL_DATABASE: craft
            MYSQL_USER: craft
            MYSQL_PASSWORD: craft


texts: Setting a field search variable after main entries variable changes values

texts:
Kind of hard to explain but here's an example:

{{entries.all()|length}} {# outputs 88 #}

{% set hasTopic = entries.search('dataTable_topic:*').all() %}
{{entries|length}} {# outputs 7 #}

How can I keep entries the same below the search variable.


texts:
I want to assign a wildcard domain to every entry from a specific type. For instance:

client.example.com

Where client is the slug of an entry. Is that possible? If yes, how?

Thanks!


texts: Is it possible to configure redactor so it will only accept a single line of text and not wrap it's content in a paragraph tag? Essentially, I'm looking to allow an editor to submit some formatted text (bold, italic, links) but place that inside an existing paragraph tag that is coming out of my templates.


texts: How do I use dynamic variables for plugin settings?

texts:
I would like to use a "dynamic" variable (for lack of better words) in my plugin settings. I am sending whomever fills out my contact form a welcome email. I'd like to be able to include the persons name if I could.

Here is my settings file:

_settings.html

{{
forms.textareaField({
    label:        "Welcome email Message"|t,
    id:           'welcomeEmailMessage',
    name:         'welcomeEmailMessage',
    instructions: "The email message that is sent to that the person who filled out the contact form."|t,
    value:        (settings.welcomeEmailMessage ? settings.welcomeEmailMessage : "Thank you {firstName} from {siteName}"|t({ siteName: craft.app.siteName })),
    errors:       settings.getErrors('welcomeEmailMessage')
    })
}}

I know {siteName} is a variable that's available everywhere. {firstName} is the name of my form input that I'd like to somehow hook into.

I have all of the information I need to send the email to the user - just not sure how to connect the dots between the service that sends the email and the settings so I can use {firstName} and it will get replaced with the value of the firstName input field.

Here is my service if it helps to see what I'm trying to do...

MyService.php

...
    $email->toEmail = $contact->email;
    $email->subject = $settings->guestSubject;
    $email->body = $settings->welcomeEmailMessage;
...

EDIT
Sorry, this is kind of hard to describe. I'll keep going maybe that will help.

I have a contact form plugin, that has a setting of welcomeEmailMessage. That setting allows the admin to set the text to the email that is sent to whomever filled out my form. Think of it like a confirmation email.

But, instead of just saying "Hi there..." I was trying to grab the value of the firstName input and inject that into the email message that resides in the plugin settings.

The email could then read: "Hi there Bob..."

I have attached a screen shot of my settings page.

So you can see in the image I have {firstName} in the textarea. I'm struggling on how to grab the value from the contact form - and inject it into that template variable.

It looks like it's very similar to the "Email Settings" area within the CP. Only instead of getting the dynamic parts from the install settings, I want to get the values from the form that was submitted.

Hope that helps?

EDIT

Reading though the comments, I'm struggling a little about how to implement them.

Here is my welcomeEmailMessage. It's located in my plugin's directory/templates

html

<html>
    <body>
        <div>
            Hello, {{ firstName }}
        </div>
    </body>
</html>

Then in my service I now have this:

php

$email = new EmailModel();
craft()->templates->renderString($settings->welcomeEmailMessage, ['firstName' => $contact->firstName]);

So now it seems like I need to tell my plugin how to get to that template?


texts: How to add attr to redactor 2 formattingAdd object config

texts:
I have searched all over the web for the documentation that fits into my working usecase for redactor 2, The working solutions I have gotten off the web and works for me isn't on the redactor documentation for redactor 2, what is on the documentation does not work and throws an error,
      "green-title-1": {
        "title": "Green header 1",
        "api": "module.block.inline",
        "args": ["h1", {"class": "coriandr-green-text"}, "toggle"],
      }
    };

This is the only formating that works for me, but my challenge now is how to add attr to the args, so I could add an ID attribute to the object...


texts: Enabling Assets Image Edit Option for Assets in Amazon S3

texts: What do I need to do in order to enable Image Edit option for Assets stored in Amazon S3?


texts:
I have this loop

{% paginate craft.entries.section('sermons').limit('10') as pageInfo, entries %}

        {% for sermon in entries %}
        ...
        {{ loop.revindex }}
        ...
        {% endfor %}

That outputs a count from 10 to 1 - however, there's more entries than just the 10.

How can I output the count of what would be absolute total results?


texts:
Me and my coworker work on the same Craft project.

We work locally with MAMP but access the database online, which works fine.

For the assets I'd like to define separate localhost basepaths, since we don't have the same folder structure.

Is there a way to make this work or do I need to work with IP's instead of localhost?

I'd also be open to set the assets relative instead of absolute to make this work.


texts: Single not loading correctly with additional segments

texts:
I've got a single set up to point to /calendar on my site. the single has only one field, SEOmatic so I can add meta title, description etc.. the rest of he page is loaded with content from the photoblog channel.

The issue is that I've got things organized by months and if there are no month segments in the url I redirect to the current year and month so that for example today the site would redirect to /calendar/2016/08 and when it does this the meta tags are getting pulled from the homepage single and I don't know why.

I also have a template route set like this

If I remove the redirect code for the year/month the meta tags come through correctly, but if it's there no luck.

How can I fix this.

simplified template code here:

{% if craft.request.segment(2) == "" %}
  {% redirect "/calendar/" ~ now.year ~ "/" ~ now|date("m") %}
{% endif %}

{#
  // take month digit and convert to date format so we can output
  // the full month name below next to the year
  // if this isn't done will only output 08 or 09 for august or september etc...
#}
{% set viewMonth = '00-' ~ month ~ '-01' %}

{% set entryAfterDate = year ~ '-' ~ month %}
{% set entryBeforeDate = year ~ '-' ~ (month + 1) %}

          {% set entries = craft.entries.section('photoblog').limit(null).after(entryAfterDate).before(entryBeforeDate) %}

          {% for entry in entries | reverse %}

            more code here

          {% endfor %}

{% endblock %}


texts: Loading javascript on specific sections/pages

texts:
What  is the recommended way to add section specific javascript to entry pages?
I need to make some 3rd party api calls front end for currency conversion but I want to only use it on a specific section entry.


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

texts:
Here's the error I get: "You have an insecure version of crypt installed. Please update PHP to 5.3.7 or later". I have PHP Version 5.3.2 installed on my Ubuntu server and cannot switch to a new version no matter what I do. I also tried to php5enmod mcrypt and it gives me command not found. I did the classic

sudo apt-get update;
sudo apt-get install php5;
sudo apt-get install php5-mcrypt;

Can you guys help? My phpinfo() doesnt show mcrypt as being installed even though it is installed actually. I am out of ideas


texts:
I'm only using Globals for the editable site footer content. Explaining to the user they need to look in "Globals" is a minor thing, but one extra step toward making a system less user friendly. If I can rename the tab to Footer it'll be a lot easier for the user to find by themselves.

I don't want to mess with the Craft build itself as I like to keep it up to date. Any ideas, is this something I can do with a plugin?


texts:
I'm gonna probably find another way around this, but I'm still very new to Craft and want to ask if I'm missing something obvious. This is a commerce site that needs a front-end login.

I have an account template folder with some templating that looks like this (it's an extended layout, leaving out unnecessary lines):

{# account/index.html #}
{% block main %}
    {% if craft.session.isLoggedIn %}
        {% include 'account/account.html' %}
    {% else %}
        {% include 'account/login_signup.html' %}
    {% endif %}
{% endblock %}

And an excerpt from my general.php

{# excerpt from my general.php file #}

'loginPath' => 'account',

'postLoginRedirect' => 'account',

When a logged-out user goes to website.com/account the login_signup.html page is spit out and a user can sign in (ignore the sign-up part). If they type in their info correctly, it leads to an ERR_TOO_MANY_REDIRECTS of account redirecting to account. This doesn't make sense to me, as both the login url and the post-login url point at the same path and load the same template, but the template should obviously handle the two situations differently. It should spit out the account.html template if the user is logged in, and if not, the login_signup.html template. These two template files have nothing in them right now, so it's not some other templating mistake.

If I remove either of the two config variables I presented in my general.php file, everything works but the routes I want aren't there.

I want a logged out user to visit account, get a sign in (login_signup.html) form they then use, and get redirected to account and the template will spit out the account.html template.

Edit Basically, if a user is logged in with my general.php having those two configs set to the same path (account), this always results in too many redirects:

{% block main %}
    {% if craft.session.isLoggedIn %}
        I'm logged in!
    {% else %}
        I should log in!
    {% endif %}
{% endblock %}


texts:
is it possible to retrieve for example 50 entries. Show 10 entries on my template and with "more" loading 10 more entries and so on and show them on the same page?

Whats the best practice for this? Do I need a plugin for this?


texts: How to get the order index of a structure entry?

texts:
I have a structure with 3 levels.
The first 2 levels are for structuring the content and most of the content comes from the 3.rd level.
This 3.rd level are the entries which are written by different authors.
I now want to display all entries written by a certain author.
The output i’m looking for would be like this:
2017 / 01 / 3rd Level entry title
2017 -> title of 1st level entry
01   -> Index of 2nd level entry
title -> title of 3rd level entry
I struggle with displaying the index of the 2nd level entry. I didn’t find a field in the database which stores the index of an entry.
Does anyone know how to get the index of a certain entry?


texts: What configuration does Craft need to enable Live View on hoster CloudFlare with SSL/https CP?

texts:
In a previous question and answer, I've laid out recent experience in bringing up Craft on the combination of CloudFlare and Railgun offered as a free feature for VPS hosting at Arcustech.

The Pingdom-tools-verified performance results are very good, especially in the combination of North American and European customers that the present site is going to serve.

It was natural to test also Craft features, and only one was found to need some help to operate in this environment. This is to have the very client-useful Live View operate properly when using the Craft CP under SSL/https as the secure.domain.com DNS allows from the previous article.

What actually happens at present is that the Live View pane comes up unexpectedly blank. A look at HTTP headers on the iframe ajax loading that pane along with console messages shows why. The CP runs on https://secure.domain.com, while the Live View iframe is called at https://www.domain.com, which can never be possible on free CloudFlare, as it does not support https. It will simply be silent, and then in a long interval time out. As well, there is a CORS error in the console, which suggests that an Access-Control-Allow-Origin header needs to be present.

In fact, experiment shows that besides the unavailability of https on the www site, such an CORS header from a template (general _layout inclusion) isn't accepted, either from Craft header() or from embedded http-equiv. Perhaps this is because other CORS headers would have to be introduced within the Craft side to allow it. There may be other reasons, but clearly the situation isn't remediable from outside, at least as far as I can see. If CORS would work, still the https accesson the www CloudFlare-free coupling never will by design.

However, experimentation proves a solution. I temporarily modified the siteUrl array for some languages (in general.php) to point to the secure.domain.com site, instead of www.domain.com.

Now Live View worked perfectly for each of the languages so modified, because the iframe calls went to a url that could answer, and which was on the same path as the CP ajax caller. Success as tested, but the real site itself would no longer work through CloudFlare/Railgun, as it would no longer be sent as www.domain.com.

The evident solution is to have the CP iframe ajax load Live View pages by the exact same full URL base as it uses for its own pages. Now everybody would be happy, and there would be no need to entangle CORS as the Live View iframes would be on the same basis as their Ajax loader.

If there were any question whether this internal solution would work in all possible cases, it could be introduced by a general.php config element, so that it could also be turned off.

I would happily spend the hour to build a plugin to arrange this, but I think we are not allowed access by code framework or by license to modify Craft's internals in this area.

If anyone can see a solution from outside, to save effort at Craft, that would be a great answer.

In lieu, I'm hoping to have analyzed this problem in a way to make it very easy for our friends to provide what it needs - and if  they don't with better insight than any of us intuit something the matter with such a solution, or realize that there's a better one.

Many very good surprises have indeed come that way, but not necessary here ;)


texts: Having an issue where the "Update Order Status..." menu option is not available on order list pages. This is true both for admins and for users who have permissions set to manage commerce orders. Any ideas as to what might cause this? Thanks!


texts:
working with the Shortlist plugin for Craft.

I'm trying to set the return URL after someone adds an item to their shortlist.

i assume thats what this parameter is for...

add item

however that takes the user to a 404 page with the url of

mydomain.com/index.php/actions/shortlist/item/my-page-i-want-to-go-to

any ideas?


texts: Plugin dev with Sendinblue mailer integration

texts:
I am trying to integrate with sendinblue API and I installed it with composer as a third party library.
But it still does not work:
Fatal error: Class 'Mailin' not found in /localfolder/www/craft/plugins/stepsprogram/controllers/StepsProgramController.php on line 225

Here is the composer.json file at the root of my plugin:

{
    "name": "/stepsprogram",
    "description": "Steps Program.",
    "type": "craft-plugin",
    "require": {
        "composer/installers": "~1.0",
        "mailin-api/mailin-api-php": "^1.0"
    }
}

The init function of my plugin:

public function init()
{
    // If using composer
    require_once __DIR__ . '/vendor/autoload.php';
}

And the error happen here when trying to call the mailin class in my controller:

        $mailin = new \Mailin('https://api.sendinblue.com/v2.0', 'dqsdsapicode', 5000);    //Optional parameter: Timeout in MS
        var_dump($mailin->get_account());


texts: How to access a previous matrix field value

texts:
I have a case where I need to access a previous matrix field's value (if it exists) in the next matrix loop result.

{% for contentBlock in entry.contentBlocks %}
    {% if contentBlock.prev %}
        {% if contentBlock.getPrev().matrixField | length %}
            {{ contentBlock.getPrev().matrixField }}
        {% endif %}
    {% endif
    ....
{% endfor %}

I know that my issue is with {{ contentBlock.getPrev().matrixField }} but I am not sure how to access the field value after trying several methods.  I'm sure it's something simple.

Thanks :)


texts: Can we hide version number in control panel for certain user groups?

texts:
Usecase: the site I'm building has public registration, the publicly registered users have access to only their own specific entry in the back-end (which makes use of many complex fields, such as Matrix, which is why I'm not trying to put this form on the front-end for them to manage).

While everything else is hidden from them already, it'd be nice to hide the Craft version just to hinder any neer-do-wells from easy bug-hunting and hacking shenanigans.

It'd still be useful to have that info displayed for other admin groups though.

Is that possible?


texts: What are the differences between an elementCriteriaModel and fetched elements?

texts:
I am a little confused about the differences between an elementCriteriaModel and fetched elements.

Why do I sometimes have to fetch elements with first(), last(), find():

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

and in other cases the elementCriteriaModel is enough:

{% set params = craft.entries.section('cocktails') %}
{% set prev   = entry.getPrev(params) %}


texts: Email Before Membership / Subscription Renews via Charge / Stripe?

texts:
I've got a client requesting that their subscribers get an email notification before their membership is renewed (via Stripe / Charge).

Having glanced over Stripe's documentation, it doesn't look like there's a webhook to handle this, nor does it look like something that Charge supports out of the box.

Is there a solution out there more straightforward than rolling my own plugin (which I haven't done before, but am certainly willing to attempt)?


texts: MatrixBlockModel error - "Call to a member function on a non-object"

texts:
I'm having some trouble trying to write a plugin. I'm trying to create a simple fieldtype that I'm going to use inside a matrix block.
So far the public function getInputHtml of my fieldtype class, contains only:

var_dump($this->element)

And it shows me, as expected:

object(Craft\MatrixBlockModel)#1121 (25){["elementType":protected]=&gt; string(11) "MatrixBlock" [.......]

The problem is that, as I try to change the previous

var_dump($this->element)

with a

var_dump($this->element->getOwner())

(or any other method/property of the MatrixBlockModel class), I obtain:

  "Call to a member function getOwner() on a non-object"

Any suggestion? Could it have something to do with the magic methods (maybe __call) inherited by CComponent class?


texts: 504 error on home page of Craft 3 website

texts: Recently, I developed a Craft 3 website. Its working perfectly on development server. But after deploying to another server, I am getting 504 error for home and all front end pages while Craft dashboard is working perfectly. I looked into logs but didn't find anything related to it.


texts: Including plugin javascript on the client side

texts:
I've created a simple plugin based on the Craft docs with the following directory structure...

/craft
    /plugins
        /eforms
            /resources
                /js
                    public.js
            /templates
                /public
                    index.html
/public_html

In the index.html template of my plugin I'm using the following line to try to include the public.js file...

{% includeJsResource "eforms/js/public.js" %}

Which attempts to include the following resource in the browser

http://mydomain/eforms/js/public.js

Unfortunately this just gives me a 404. Does anyone have an idea of what I'm doing wrong?


texts: Is it possible to use _includes/forms outside of the Control Panel?

texts:
From working on plugin development, importing (I believe the correct term for this is macro) the 'forms' to quickly generate text areas, selects and etc. is incredibly useful. Adding the import now fails as '_includes' is only accessible from the control panel.

So in my template I could add this line:

{% import "_includes/forms" as forms %}

Then use something similar to this to output my forms fields?

{{ forms.textField({
    label: "First Name"|t,
    id: 'firstName',
    name: 'firstName',
    instructions: "First name (i.e John)",
    placeholder: "John",
    first: true,
    autofocus: true,
    required: true
}) }}

I know when using Symfony and Twig you can specify the namespace on where to grab the template from. Does Craft include a way to access those templates from the front end? Has anyone managed to perform this outside of the control panel?

Edit: if this is not possible, or p&t doesn't plan on making this possible (for security concerns) is there a way for a plugins template path to allow anonymous access? This way the developer could create an '_includes' and allow people to access it in the same manor?


texts: How to use a dynamically defined field handle in a plugin?

texts:
I'm trying to make a plugin more generally usable (so others could use it). For my own use, it uses a category field called 'mainCategory' but I'd like that the field handle could be specified in the plugin settings.

What I imagine is:

$url = $entry->mainCategory->last()->uri;

becomes:

$plugin = craft()->plugins->getPlugin('myPlugin');
$settings = $plugin->getSettings();
$fieldHandle = $settings->categoryFieldHandle;

$url = $entry->getField($fieldHandle)->last()->uri;

Any suggestions?


texts: Output coupon in the code back end using Craft Commerce

texts:
I use the plugin Craft Commerce. I can not find how to output the coupon code used by the customer in the back end on the order page.
Anyone would know how to?
Thanks a lot!


texts:
Is it possible to build categories with a list of entries that have different styling, like

{% for entry in entries %}
    Row 1 - Entry 1 - full-wide
    Row 2 - 3 entries with (1/3 width of each)
    Row 3 - 2 entries (1/3 and 2/3 width)
    ....
{% endfor %}

Thank you


texts:
I would like to create a Craft site with a basic theme and some configuration already made. Like a home- and contact page, a matrix field with predefined components, certain plugins already installed, ...
For every new site, I would clone/fork from that repository and push relevant updates from that repo to the custom sites in the future.
Is this possible/doable? I'm thinking my my project.yaml file might be the biggest problem when merging new changes from the template repo to the custom site repo.


texts: How do I get the right entry data based on locale and slug?

texts:
My site has 2 locales: en_us and nl_nl. I also have a Structure section called Pages, which targets both locales. For each locale, the section has an Entry URL Format:

en_us: en/{slug}
nl_nl: nl/{slug}

The Entry Template setting for the section is pages/_entry, and there is a template there.

Now, for an entry with the slug home for both locales, the URI nl/home gives me the correct page, but en/home gives me a 404.

Is my setup wrong? Do I need to explicitly create nl and en template folders?


texts: Best approach for Craft Commerce 3 - Variants & Custom Text

texts:
I'm working on a Craft Commerce 3 project and for something I initially thought would be easy to do with variants seems to have completely thrown me off course so any feedback would be great.
I have a site we're building that has one single product - a car registration plate maker. The user needs to input their reg and select from a few options such as styles, colours, badges etc. Some of these options change the price and some don't.
I've built many sites in Craft CMS but only one previously with Craft Commerce 1. For this Craft Commerce site we built a plug-in that updates the product price and worked great so I'm thinking - do I need to go down the plug-in route or am I missing something with variants?
Variants - when I added variants, ideally I wanted a separate field for each variant option (text style, then one for size and then one for colours and so on) - not just one select field with the possible combinations.
Single Purchase Element - I've also been thinking just build the whole thing completely separate from Commerce so I'd in effect just have JS calculating the final price based on options selected. Then when added to cart, a form would just add the price, all the options selected and the custom text (car reg) to the line item.
Any pointers on this would be really appreciated. I've tried many things but nothing seems to be a solid direction yet.


texts: Postpone sending activation codes; Creating a user as "Inactive"

texts:
I'm finding the user activation process a bit confusing...

I was trying to create a handful of users, but I didn't want to send out the activation emails yet.

I incorrectly assumed if I unchecked "send activation email" when creating, it would create the user and I would be able to send the activation later.

Instead, Craft creates the user as "active" with no password, and the "Resend activation email" isn't available.

At this point I'm stuck, as you can't set a user to inactive. I'm left with these choices:

having to set a dummy password, require reset, and manually email my users
email my users the control panel url, and instruct them to click "Forgot password" and enter the same email I've created their user with.

Neither options are great, unless I'm missing something.

Thoughts?


texts: Craft/Yii not garbage collecting session?

texts:
I want to store a session value and have that cleared after a set timeout.

I’ve got PHP's session.gc_maxlifetime set at 60 seconds for development and am using Craft’s HttpSessionService to set a session value craft()->httpSession->set('foo').

I’m then checking that after 60 seconds and would expect it to be cleared by PHP’s session garbage collector but it’s still there: craft()->httpSession->get('foo').

I'm aware of how PHP's garbage collection works in that it's not run on every request (1/100 chance by default, defined by other PHP session settings).

What's the best way to force garbage collection on each session? Is there anything under the hood that we can leverage or do we need to write something custom?


texts: Store Hours: show current open/closed state

texts:
I'm wanting to do two things with this great plugin, but am having a bit of a mind-melt...

1) I'd like to show the current state; e.g. Closing soon; Open now; Closed; Opening Soon

2) I'd like to show the current day highlight:

Sunday:    11:00 AM - 05:00 PM

Monday:    10:00 AM - 08:00 PM

Tuesday:   10:00 AM - 08:00 PM

Wednesday: 10:00 AM - 08:00 PM

Thursday:  10:00 AM - 08:00 PM

Friday:    10:00 AM - 08:00 PM

Saturday:  10:00 AM - 07:00 PM

Thanks!


texts:
I have a custom field enabled on a product - it is a user field that associates a product with a user.

What would the correct setup be to only display products that pertain to the currentUser - as this would match the custom user field?


texts:
I'm looking to be able to return the info from a field(s) from a Matrix row where I know which row I want (long story). I had a guess at various ways of doing this, but in the end the only way that worked was to run the loop with an if statement to limit the output to a given row's id, e.g:

{% for block in entry.bodyRepeater %}
    {% if loop.index==2 %}
    <h3>{{ block.heading }}</h3>
    {% endif %}
{% endfor %}

Guessing there might be a better way though?


texts: Entry Form - Multiple Entries & Entry Type & Parent

texts:
I'm building an MVP for a project, I'm using Craft and would like to:

Create an experiment (/experiments/)
Create multiple cages for the animals within the previous created experiment eg. 5 cages - (/experiments//cages/)
Add a number of rodents to each of those cages e.g. Create 5 cages with 5 rodents in each. (/experiments//cages/)
Add measurements to a specific mouse e.g., weight / tumour size (/experiments//cages/)

I was thinking this would be possible by using an entry form to add entries to a structure that looks like this-

--Experiments
----Cage 1
------Rodent 1
------Rodent 2
------Rodent 3
----Cage 2
------Rodent 1
------Rodent 2
------Rodent 3
...

My question is -

Is it possible to create multiple entries per form eg.
Create 5 cages with 5 rodents in each. from a single entry form submission?
Is it possible to assign the entry type in an entry form? (eg. Cage or Mouse entry type?)
Is it possible to assign the parent to an entry via the entry form?

If these aren't possible with an entry form + structure what would be the best way to approach it?

Thanks!


texts: How to reference specific asset subfolders in Craft 3

texts:
I am having trouble referencing specific subfolders in Assets in Craft 3 using Twig.  The query that I've written is still showing all content, when I only want it to show content from a specific subfolder.

The folder layout: /files/asset-volume/subfolder/file.txt

When I try this query code, I still get all of the files from the volume, when I only want the subfolder.  How do I only reference the specific subfolder?

{% set subFolders = craft.assets()
                    .volume('asset-volume')
                    .includeSubfolders('subfolder')
                    .all()
%}


texts: Add Checked Attribute to Custom User Fields on Frontend User Form

texts:
I have a multi-select for users to sign up for newsletters.
When they edit their profile they need to be able to see which newsletters they are already signed up for. I have the code to output the entire options list or just the ones that they have selected but I haven't figured a way to add the selected attribute to the ones the user has selected.

{% set newsletters = craft.fields.getFieldByHandle('newsletters') %}
<select multiple>
    {% for opt in newsletters.settings.options %}
        <option value="{{ opt.value }}" >{{ opt.label }}</option>
    {% endfor %}
</select>

The "for opt in newsletters.settings.options" can be changed to "for opt in newsletters.settings" to show just the ones the user has already selected.


texts: Updating an entry after an event action within onSaveEntry

texts:
I have written a plugin that checks if an entry has been saved and sends the user an email from within an onSaveEntry event. This works fine. But I now need to also update this entry to flag that an email has been sent so that subsequent saves do not fire the event. I have tried adding the following but these lines do not work and cause an infinite loop.

$entry->setContentFromPost(['emailSent' => '1']);
craft()->entries->saveEntry($entry);

Is there a way to re-save the entry after the email has been sent so as just to update the emailSent field?

Full function:

public function onSaveEntry(Event $event)
{
    $entry = $event->params['entry'];
    if($entry->sectionId == '12345') {
        if($user = craft()->users->getUserById($entry->authorId)) {
            if($entry->enabled && !$user->admin && !$entry->emailSent) {

                // Send Approved Mail
                $email = new EmailModel();
                $email->fromEmail = 'me@mydomain.com';
                $email->toEmail = $user->email;
                $email->subject = 'Email Subject';
                $email->body    = '
Email Body
';
                craft()->email->sendEmail($email);

                $entry->setContentFromPost(['emailSent' => '1']);
                craft()->entries->saveEntry($entry);
            }
        }
    }
    return $event;
}


texts: What's the best way to manage a large number of uploaded photos?

texts:
I have a news website build with free version of Craft 2.3. It's obvious that a news website will have a lots of entries and lots of photos per entry. It will have at least one per entry and could go up to 10 or more.

So after few months I will have 100s of photos and I was thinking how I can manage this? Will this slow down the system when accessing the assets folder?

Should I use a field with a subfolder which contains variables like {slug} or {author.username}? But the problem is that I cannot search on assets subfolders or see all the subfolders at the same time so I can search within folder and its subfolders.

Anyone came accross to this problem? I'm coming from EE and I love craft just trying to make the transition. In EE I was using devdemon channel images which was creating a subfolder per upload but it had the option to search the subfolders.

Thanks in advance


texts:
I'm looking to paginate and array with multiple filters.

The current url would be: www.example.com/search?filter=shorts&type=leather&brand=sams

Clicking on the next next link returns: www.example.com/search/p2 effectively removing the search params.

Is there a way to paginate the full url without removing the search params?

{% paginate test.limit(4) as entries %}
    {% for entry in entriesOnPage %}

{{ entry.title }}

            {{ entry.body }}

    {% endfor %}

    {% if paginate.prevUrl %}
        Previous Page
    {% endif %}

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


texts: How can I conditionally resave entries based on the value of an entry's field in a Craft 3 Module/Plugin?

texts:
Scenario: I want to programatically bulk resave entries in a certain Site in a certain Section of a certain Type.

I have a Craft 3 Module with a Console Controller containing following code:

public function actionResaveEntries()
{
    $site = Craft::$app->sites->getSiteById(self::SITE_ID);
    $section = Craft::$app->sections->getSectionById(self::SECTION_ID);
    $entryType = Craft::$app->sections->getEntryTypeById(self::ENTRY_TYPE_ID);

    Craft::$app->getQueue()->push(new ResaveElements([
        'description' => Craft::t('app', 'Resaving {section}, {type} entries', [
            'section' => $section, 'type' => $entryType->name,
        ]),
        'elementType' => Entry::class,
        'criteria' => [
            'siteId' => $site->id,
            'sectionId' => $section->id,
            'typeId' => $entryType->id,
            'status' => null,
            'enabledForSite' => true
        ]
    ]));

    $result = 'something';
    echo "Resaving entries\n";
    return $result;
}

This works as expected when running ./craft resave-entries-module/resave-entries/resave-entries from the command line & also via a cron job.

However, I now want to modify my code to run Craft::$app->getQueue()->push(new ResaveElements() only under certain conditions. Specifically, when a deadline (custom date/time field in entry type) has passed.

I tried following, but it doesn't run at all regardless if before or after deadline date. The conditional seems to be ignored.

public function actionResaveEntries()
{
    $site = Craft::$app->sites->getSiteById(self::SITE_ID);
    $section = Craft::$app->sections->getSectionById(self::SECTION_ID);
    $entryType = Craft::$app->sections->getEntryTypeById(self::ENTRY_TYPE_ID);

    $entries = Entry::find()
        ->siteId(self::SITE_ID)
        ->sectionId(self::SECTION_ID)
        ->typeId(self::COMP_ENTRY_TYPE_ID)
        ->all();

    foreach ($entries as $entry) {
        // Set deadline
        $deadline = $entry->competitionJudgingEnd;
        // Check if after deadline
        $now = new DateTime();
        if ($now > $deadline) {
            Craft::$app->getQueue()->push(new ResaveElements([
                'description' => Craft::t('app', 'Resaving {section}, {type} entries', [
                    'section' => $section, 'type' => $entryType->name,
                ]),
                'elementType' => Entry::class,
                'criteria' => [
                    'siteId' => $site->id,
                    'sectionId' => $section->id,
                    'typeId' => $entryType->id,
                    'status' => null,
                    'enabledForSite' => true
                ]
            ]));

            //$result = 'something';
            echo "Resaving entries\n";
            //return $result;
        } else {
            //$result = 'nothing';
            echo "Not resaving entries\n";
            //return $result;
        }
    }

In an effort to troubleshoot, I changed the conditional to if ($entry->title == "A known title"), but it also seems to be ignored. I.e. resave not occurring.

What am I doing wrong, and what can I do to get this working?

UPDATE 01: The conditionals are actually working. There are 3 entries that meet criteria in $entries = Entry::find(). However, the loop seems to be stop at the first entry. This entry changes if I change the criteria.

UPDATE 02: It looks like the return $result; was breaking the loop. Updated code above by commenting out return statements.


texts:
I'm trying to create a field group in a plugin that fires onAfterInstall. I'm getting the error below but after install the field group does exist and seems to have been created successfully.

2015/10/21 21:57:17 [warning] [application] [Forced] Failed installing XXXXXX: An exception was thrown: CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`craft`.`craft_fieldlayoutfields`, CONSTRAINT `craft_fieldlayoutfields_fieldId_fk` FOREIGN KEY (`fieldId`) REFERENCES `craft_fields` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `craft_fieldlayoutfields` (`required`, `uid`, `layoutId`, `tabId`, `sortOrder`, `dateUpdated`, `dateCreated`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6). Bound with :yp0=0, :yp1='b68bdc0b-647d-45fd-afa1-dbadffb973b8', :yp2=427, :yp3=263, :yp4=2, :yp5='2015-10-21 21:57:17', :yp6='2015-10-21 21:57:17'

Here is what the code look like which is creating the field group:

// XXXXX field group
Craft::log('Creating the XXXXX field group.',
 LogLevel::Info, true, 'application', 'XXXXX');

$group = new FieldGroupModel();
$group->id   = '';
$group->name = 'XXXXXXX';

if (craft()->fields->saveGroup($group))
{
  Craft::log('XXXXXX field group created successfully.',
   LogLevel::Info, true, 'application', 'XXXXXX');
}
else
{
  Craft::log('Could not save the XXXXXX field group.',
   LogLevel::Warning, true, 'application', 'XXXXXX');
}


texts: What files need to be moved for Craft3 plugins?

texts:
I'm trying to get the redactor onto my site. I've successfully moved over plugins from the store and a custom plugin I created. But I did those towards the start and had migrated the entire project onto the site. I don't want to move 4,000 files over just to get one plugin to show up.

I've tried moving composer.json, composer.lock, and manually moving the specific vendor folder in as well. I also migrated the database from the dev site to the production site.


texts: Why does field value get updated on $element->getContent()->fieldHandle but not when accessed directly $element->fieldHandle?

texts:
I am trying to update a custom field on an EntryModel.  I'm having half success, and I don't understand why. I've looked at other posts such as this one by Brandon which discuss how to assign these values and I'm still not having any luck.

The EntryModel I'm trying to update is available in my field type in the onAfterElementSave method via $this->element.  The handle for the field I want to be updating the value of is available via $this->model->handle.

I have tried using setContentFromPost(), setContent(), getContent()->setAttributes() and they all seem to return the same results.

$fieldHandle = $this->model->handle;

$this->element->setContentFromPost(array(
    $fieldHandle => 'changedValue'
));

// Accessing the value via getContent returns the update value 'changedValue'
$changedValue = $this->element->getContent()->fieldHandle;

// Accessing the value directly returns the 'originalValue'
$originalValue = $this->element->fieldHandle;

Why am I able to successfully update the value for the getContent() method but not when I access it directly on the model?


texts: Creating an archive page with full year and month list

texts:
Trying to create an archive page for each of my blog types within Craft. The page sorts by year and by month. (year and month are coming from my routes in this code.)

By using the following, I can print out each month with posts and the number of posts the month has. My problem is that I also need to print out the months with no post count and can't seem to figure out how to do that.

{% set entriesInYear = craft.entries.section('pressReleases').limit(null).after(year).before(year+1) %}

{% for month, entries in entriesInYear | group("postDate|date('F')") %}

{{ month }}&nbsp;({{ entries|length }})

{% endfor %}

That will yield me a printout of:

April (7)
March (4)
February (1)

I just need to also print out all the months in between with a (0) indicator.


texts:
I'm writing a customer portal plugin that will have 3 types of users.

Organizations
Organization members
Private

I would like to use Craft's built in UserRecord for front end login, backend management, ..?, and extend it to handle these three user types.

The way I have it set up so far, is that I have a proxy user record, which handles the relations to the organization profile and user profile records. Below I have listed the relevant attributes/keys and relations for each of the records:

MyPortal_ProxyUserRecord:
Acts as a middle man between the Craft UserRecord and the two records further below.

id
craft_user_id
organization_id  (# | null if private user)
user_id  (# | null if organization)

'craft_user' => array(static::BELONGS_TO, 'UserRecord', 'craft_user_id'),
'organization_profile' => array(static::HAS_ONE, 'MyPortal_OrganizationProfileRecord', 'proxy_user_id'),
'user_profile' => array(static::HAS_ONE, 'MyPortal_UserProfileRecord', 'proxy_user_id'),

MyPortal_OrganizationProfileRecord:

id
proxy_user_id
contact_user_id

'proxy_user' => array(static::BELONGS_TO, 'MyPortal_ProxyUserRecord', 'proxy_user_id'),
// Organization members:
'user_profiles' => array(static::HAS_MANY, 'MyPortal_UserProfileRecord', 'organization_id'),
// Contact user:
'contact_user' => array(static::HAS_ONE, 'MyPortal_UserProfileRecord', 'organization_id'),

MyPortal_UserProfileRecord:
Handles both private users and organization members.

id
proxy_user_id
organization_id  (# | null if private user)

'proxy_user' => array(static::BELONGS_TO, 'MyPortal_ProxyUserRecord', 'proxy_user_id'),
'organization' => array(static::BELONGS_TO, 'MyPortal_OrganizationProfileRecord', 'organization_id'),

Questions:

Is it possible to extend the Craft UserRecord itself with the
necessary attributes and relations to handle the
OrganizationProfileRecord and the UserProfileRecord, and ditch the
proxy user record? If so, how do I do that?
If not possible, should I structure my records and relations differently than I have done so far?
Are there any pitfalls I should be vary of?

Please let me know if I should provide any further information! :)

Many thanks in advance for any help you can provide!  bowing

/Monkey


texts: Entries relations with additional fields

texts:
I'm searching for a way to have additional fields on relations.
The simplest exemple would be; you have stores entries and products entries, and you want to create a many to many relationship with the price as additional information.

How could it be done ?

Thanks in advance,


texts:
I've been hunting through questions here, Discord, Craft docs for solutions for a boilerplate Craft CMS install. Because I want to include section & field configurations, I'm planning on importing an export of the boilerplate database into a new database for the project.
It's documented in a few places that you can run craft setup/security-key (or craft setup/app-id) to generate a new key and store it in .env, but nothing says how that impacts a database that's already established. They all seem to assume you'd run that step before creating the database.
If you clone a project & existing database that's already used that first project's security key, and you want to have a unique security key for the new project, are you breaking the ability to decrypt data that was in the initial project when you generate a new security key? I don't see any indication that Craft updates the database when you generate a new key. It just updates .env.


texts: Remove $_SERVER and DB Queries from logs in 3.4+

texts:
How can we disable Craft from logging MySQL queries and $_SERVER object into the logs?
For our team, this creates additional noise that's not needed for us to debug issues.
Thanks :)


texts: Is there a way to retrieve discounts for a product in Craft Commerce v2?

texts:
I would like to retrieve all available discounts for an eshop using the Craft Commerce v2.
In Craft Commerce v1, I could use the following:

craft.commerce.discounts.all()

However, I can't find an equivalent method for Commerce v2

Can anyone please help?


texts: Using elements-api, how do i create a geojson structure with Features within a FeatureCollections

texts:
I am trying to output, from a single request, a geojson structure like so:

    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {},
            "geometry": {
                "type": "MultiLineString",
                "coordinates": [
                    [
                        [-1.102108, 52.671813],
                        [-1.142189,52.620366]
                    ],
                    [
                        [-1.102108, 52.671813],
                        [-1.447277, 52.939653]
                    ],
                    [
                        [-1.102108, 52.671813],
                        [-1.447277, 52.914816]
                    ],
                    [
                        [-1.102108, 52.671813],
                        [-1.884783, 52.509112]
                    ]
                ]
            }
        },
        {
            "type": "Feature",
            "properties": {},
            "geometry": {
                "type": "MultiPoint",
                "coordinates": [
                    [-1.102108, 52.671813],
                    [-1.142189, 52.620366],
                    [-1.447277, 52.939653],
                    [-1.447277, 52.914816],
                    [-1.884783, 52.509112]
                ]
            }
        }
    ]

I have the multilinestring part sorted, and i know how to get the data for the multipoint part, bit i cant find a way, from the single elements api endpoint, how to add the multipoint feature onto the end of the returned array / json.

Here is my elements api endpoint :

    'geojson' => function() {

        function getCoordinates(UserModel $user){
            $return = array();
            foreach ($user->connections as $connection) {
                $return[] = array(array($user->longitude,$user->latitude),array($connection->longitude,$connection->latitude));
            }
            return $return;
        }

        return [
            'elementType' => ElementType::User,
            'paginate' => false,
            'transformer' => function(UserModel $user) {
                return [
                        "type" => "Feature",
                        "geometry" => array("type" => "MultiLineString", "coordinates" => getCoordinates($user)),
                        "properties" => array("name" => "Test")
                ];
            },
        ];
    },

I know i can probably do this using two requests, but i want to do it in one.


texts:
Trying to sort products by price.

Since the price of a product in Commerce isn't a textual custom field it's attached to a variant, I'm having trouble working out the syntax to make this happen.

{% set products = craft.commerce.products({
     relatedTo: (category),
     order: defaultPrice,
}) %}

This seems close but delivers "Variable "defaultPrice" does not exist"

Appreciate any direction.


texts: Delete CSRF cookie on submit form success

texts:
I need to delete the CRAFT_CSRF_TOKEN cookie when a form submission reaches certain/success page. I'm using CSRF stripped cookie's value to store entry title like this:

{% set token = craft.request.csrfToken[:10]|replace({'~':'P', '_':'B', '|':'T'})|upper %}

Upon succesful form submission I'd like to erase cookie name CRAFT_CSRF_TOKEN and it's value so on next form load there is a new cookie value set for CRAFT_CSRF_TOKEN name to prevent next entry to be stored/updated in the same entry.

Trying to achieve this I've failed right after accessing to csrfTokenName.

Neither the property "csrfTokenName" nor one of the methods
"csrfTokenName()", "getcsrfTokenName()"/"iscsrfTokenName()" or "__call()"
exist and have public access in class "Craft\HttpRequestVariable"


texts: Adding alt tag to image in a rich text field via its Edit button, within a matrix - breaks code link to the image

texts:
Craft 2.4. Unusual bug. Adding an alt tag to an image within a rich text field via its Edit button, that's in a matrix, works just fine the first time the entry is saved. However, re-saving the entry breaks the code to the image.

This:

img alt="test" src="/resources/images/someimage.png#asset:1844:url"

Becomes this:

img alt="test" resources="" images="" someimage.png#asset:1844:url"=""


texts:
I am having issues with the Smart Map infoBubble pointer position...

As you see the shadow is positioned correctly, but the white overlay triangle is too low down. Or the other way of thinking about it would be that the white overlay triangle is correct and the rest is too high. However, I think the problem can best be described as the former, that the white triangle is too low, knowing that the marker it is attached to is hidden away just showing behind the white triangle.

After inspecting this in Chrome, I cannot see the element / pseudo-element that generates this pointer visual... so cannot debug. Can anybody offer any assistance on how to fix this anomaly?

Thanks in advance,

Adam.


texts: 6 month old site is suddenly throwing 404s

texts:
http://denizen.tv/work/2011-kca-image-campaign

http://denizen.tv has been up and running well since June, but it's suddenly throwing 404s. It looks like the same /index.php/ problem I was recently having with my own Craft install. The coincidence makes me think it must be a bug with a recent release.

Anyone else getting this error?


texts: Carbon 1 is deprecated - migrate to Carbon 2

texts:
Is anyone getting this when running a composer update command?

Local install: Craft CMS 3.1.31

update --no-interaction --ansi
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Nothing to install or update
    Generating optimized autoload files
    Carbon 1 is deprecated, see how to migrate to Carbon 2.
    https://carbon.nesbot.com/docs/#api-carbon-2
        You can run './vendor/bin/upgrade-carbon' to get help in updating carbon and other frameworks and libraries that depend on it.
    All packages for ./composer.json have been updated.


texts: Getting Twig_Error_Runtime when trying to open the website

texts:
I am trying to set up a Craft CMS website with Twig. I have done all the setup but getting the following error when I try to open the website-

Twig_Error_Runtime

Variable "global" does not exist in "503" at line 9 (C:\wamp64\www\west\craft\app\vendor\twig\twig\lib\Twig\Template.php:436)

#0 C:\wamp64\www\west\craft\storage\runtime\compiled_templates\00\0009102817a5d89769207212bd179d422974c0400e0d4db894ad4fd45f35fd9d.php(29): Twig_Template->getContext(Array, 'global')
#1 C:\wamp64\www\west\craft\app\vendor\twig\twig\lib\Twig\Template.php(381): __TwigTemplate_37e5d62204d15e3586ae79a226d2d0e58f18084c697fef1d38e94cf3b75f8fb0->doDisplay(Array, Array)
#2 C:\wamp64\www\west\craft\app\etc\templating\BaseTemplate.php(26): Twig_Template->displayWithErrorHandling(Array, Array)
#3 C:\wamp64\www\west\craft\app\vendor\twig\twig\lib\Twig\Template.php(355): Craft\BaseTemplate->displayWithErrorHandling(Array, Array)
#4 C:\wamp64\www\west\craft\app\vendor\twig\twig\lib\Twig\Template.php(366): Twig_Template->display(Array)
#5 C:\wamp64\www\west\craft\app\vendor\twig\twig\lib\Twig\Environment.php(347): Twig_Template->render(Array)
#6 C:\wamp64\www\west\craft\app\services\TemplatesService.php(248): Twig_Environment->render('503', Array)
#7 C:\wamp64\www\west\craft\app\controllers\BaseController.php(74): Craft\TemplatesService->render('503', Array)
#8 C:\wamp64\www\west\craft\app\controllers\TemplatesController.php(200): Craft\BaseController->renderTemplate('503', Array)
#9 C:\wamp64\www\west\craft\app\framework\web\actions\CInlineAction.php(49): Craft\TemplatesController->actionRenderError()
#10 C:\wamp64\www\west\craft\app\framework\web\CController.php(308): CInlineAction->runWithParams(Array)
#11 C:\wamp64\www\west\craft\app\framework\web\CController.php(286): CController->runAction(Object(CInlineAction))
#12 C:\wamp64\www\west\craft\app\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#13 C:\wamp64\www\west\craft\app\framework\web\CWebApplication.php(282): CController->run('renderError')
#14 C:\wamp64\www\west\craft\app\framework\base\CErrorHandler.php(368): CWebApplication->runController('templates/rende...')
#15 C:\wamp64\www\west\craft\app\etc\errors\ErrorHandler.php(281): CErrorHandler->renderError()
#16 C:\wamp64\www\west\craft\app\framework\base\CErrorHandler.php(351): Craft\ErrorHandler->renderError()
#17 C:\wamp64\www\west\craft\app\framework\base\CErrorHandler.php(218): CErrorHandler->renderException()
#18 C:\wamp64\www\west\craft\app\etc\errors\ErrorHandler.php(145): CErrorHandler->handleException(Object(Craft\HttpException))
#19 C:\wamp64\www\west\craft\app\framework\base\CErrorHandler.php(131): Craft\ErrorHandler->handleException(Object(Craft\HttpException))
#20 C:\wamp64\www\west\craft\app\framework\base\CApplication.php(750): CErrorHandler->handle(Object(CExceptionEvent))
#21 [internal function]: CApplication->handleException(Object(Craft\HttpException))
#22 {main}

Here's the code from where the exception is thrown-

<title>
    echo twig_escape_filter($this->env, $this->getAttribute((isset($context["global"]) ? $context["global"] : $this->getContext($context, "global")), "siteName", array()), "html", null, true);
    </title>

Template 503 -

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="robots" content="noindex">

    <title>{{ global.siteName }}</title>

{{ global.siteName }}


texts: Craft 3: Searching within back-end & front-end isn't giving all entries/results

texts:
Searching within Control Panel as well as the front-end is not going through all entries. When I try searching in the Content tab I see the pages are listed but when I try to search for the entry it won't give it as a result.

It seems to be only on entries that were created a long time ago.

It seems also that a re-save fixes the problem, but doing that for 10K+ entries is a pain. Hope you can help me to do something like Rebuild Search Indexes that was possible before 3.2.2.

Thank you!


texts: Passing Entry to craft()->templates->render()

texts:
In looking over the docs on template rendering I am not seeing a way to pass in an Entry model. It seems more efficient to pass in an existing model rather than have the template do another lookup. Something like:

$html = craft()->templates->render('path/to/template', $myEntry);

Here is my use case. I want to use the craft template rendering engine to compose email messages.


texts: Use twig's {% spaceless %} tag only under certain conditions

texts:
Is there a way to use Twig's {% spaceless %} tag only under certain conditions?

For example, say you wanted the HTML to be spaceless in the live environment but wanted it uncompressed in the dev environment. I tried something like:

{% if isDev %}
    {% spaceless %}
{% endif %}
{# Some code... #}
{% if isDev %}
    {% endspaceless %}
{% endif %}

But this just throws a Twig error.


texts: How to exclude all Singles entries with Twig query?

texts:
In my site-wide search module I like to exclude any entries that are a Single.
Since we cannot do this by checking for a type, I found that Singles entries do not have an author ID. So the easiest way in my scenario is to exclude entries with no authorID.
In my setup there is only one author with the ID of 1.
According to the docs this should work:
{% set entryQuery = craft.entries(queryParameters).authorId('not 1').orderBy(orderBy).limit(10) %}

But no matter what I set for authorId I always also get all entries that have no author ID set. Setting a non-existing author ID also gives me results.
All forum entries point to this working, so my only conclusion is that because I'm using Craft's Solo edition (3.4.23) maybe the whole user-related section is not active?


texts: How can I export or move content from one Craft system into another? (with exactly the same configuration)

texts:
Our client build tons of articles in our craft system instead of his. Both systems have the identical structure, in fact, his system is a exact copy of ours, which runs on a different server. How can we move all his content on  our  craft system into  his  system?

(As you may have noticed I am not a developer. I hope you get what my problem is here ... )


texts: How can I send email notification to different addresses using Sprout Forms

texts:
I know I am able to send to multiple recipients for any given form submission.
I am curious if there is a way to send to different addresses given user input.

For example, I have a drop-down on my site that chooses the department. If I choose "support", I would like to send the notification to "support@mysite.com". But, if the users chooses "other", I'd like to send the email to "other@mysite.com"


texts: ElementAPI endpoint routing syntax for multi-level structure

texts:
Would like to be able to handle requests for structured requests so that it may be handled in one endpoint

    about.json
    about/the-team.json
    about/contact/london.json

Presumably a form of regex would be required for this to work?
Contemplating:

    pages/about.json
    pages/about/the-team.json
    pages/about/contact/london.json

All though how would you prepare a check for 'pages' as your first node?

Currently have this but not fees able.

   '<slug:{slug}>*.json' => function($slug) {

thanks


texts:
Finally making progress into a production environment (Pro license installed) and I see that the SEOMATIC has an update - 1.1.45 - I followed the instructions but am lost, as SEOMATIC is already installed in my instance of Craft; instructions want me to install it...is there a step I am missing to get this update complete?

Please let me know what I am I missing here -- thank you a ton! =)

Edit @10:00 03/29/2017

Thank you everyone for your answers! =)

If I am reading all the comments/answers correctly, I should do the following:
rm -R /var/www/html/craft/plugins/seomatic
cp -rv /home/psa/Zips/seomatic /var/www/html/craft/plugins
service apache2 restart

Is that correct? Thanks again for the assistance here!


texts:
I'm trying to follow along with the guide on creating custom notification events in a plugin found here: https://sprout.barrelstrengthdesign.com/docs/email/custom-notification-events.html#register-event

I used their example Manual class as my notification and now I'm trying to register it, however, I get an error of:

Class barrelstrength\sproutbase\app\email\services\NotificationEmailEvents' not found.

I checked and made sure that the sprout email is installed and enabled and also my plugin is installed and enabled.

Below is what is in my main plugin file:

namespace mycompany\plugin;

use myname\company\notifications\Manual as PluginManualNotification;

use barrelstrength\sproutbase\app\email\services\NotificationEmailEvents;
use barrelstrength\sproutbase\app\email\events\NotificationEmailEvent;

use Craft;
use craft\base\Plugin;
use craft\services\Plugins;
use craft\events\PluginEvent;

use yii\base\Event;

class MyPlugin extends Plugin
{
    public static $plugin;
    public $schemaVersion = '1.0.0';

    public function init()
    {
        parent::init();
        self::$plugin = $this;

        Event::on(
            Plugins::class,
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
            function (PluginEvent $event) {
                if ($event->plugin === $this) {
                    // We were just installed.
                }
            }
        );

        Event::on(
            NotificationEmailEvents::class,
            NotificationEmailEvents::EVENT_REGISTER_EMAIL_EVENT_TYPES,
            function (NotificationEmailEvent $event) {
                $event->events[] = PluginManualNotification::class;
            }
        );
    }

    /* Create settings modal and other unrelated stuff */
}


texts:
I'm embarking on my first plugin build.

The docs are OK, but lacking in some areas or maybe I'm just looking in the wrong place.

The settings page allows you to define any settings and when rending out the template view, pass through those settings.
http://buildwithcraft.com/docs/plugins/plugin-settings

It makes sense that all of the settings are going to be form fields. Where's the documentation for form helpers?

Looking around at other plugins I can see an include to Craft's form templates.

{% import "_includes/forms" as forms %}

Where's the docs on how to use these form fields? Is this a Twig thing and I should be looking at those docs? Any help would be appreciated.


texts:
is there a way to add a field to a global set by code ? I figured out how to create a global:

$global = new GlobalSetModel();
$global->name = 'GlobalName';
$global->handle = 'globalHandle';
craft()->globals->saveSet($global)

But I can't figure out how to add a field to this newly create global.


texts:
I'm using the following Event hook :

Event::on(Entry::class, Entry::EVENT_REGISTER_PREVIEW_TARGETS, function ($event) { }

The $event variable contains an array with the current $previewTargets as well as the entry that fired the event

I would like to modify the $previewTargets and then save them to the entry they belong to.

If I simply modify the $previewTargets the changes are lost at the end of the request

How can I save those changes ?


texts: When I import using JSON with FeedMe Pro and need to import more records into an entry that has a Matrix field. I find it deletes the previous and adds the new data only.  Is there anyway to append to the Matrix field leaving the previous data intact?


texts: Using elementSelect for third-party elements

texts:
I'm writing plugin to extend Craft Commerce and I want to present a good way to select products in CP.

I know I could use dropdown select for this, but using Craft's elementSelect would make the UI much nicer. Is there a way to use elementSelect dialog / fieldtype not just for entries or assets, but for custom data set (in my case, Commerce Products)?


texts: Using user-selectable timezones to show localized post dates

texts:
In my user profiles, I have a text field where the user's timezone is set, in the standard America/New_York format.

Craft's timezone is set to New York, and the server's timezone is set to UTC.

I'm trying to use the Twig date filter to localize the times using the user profile timezone field, but it doesn't seem to be working.

For example:

{{ message.postDate | date('n/d/Y g:ia') }} outputs 12/11/2016 1:00pm

I'm hoping that for a user in the pacific timezone, this time will display as 10:00am. But this is what happens:

{{ currentUser.userTimezone }} outputs America/Los_Angeles

{{ message.postDate | date('n/d/Y g:ia', currentUser.userTimezone) }} still outputs 12/11/2016 1:00pm

I've also tried just hard-coding a different timezone in, to no avail:

{{ message.postDate | date('n/d/Y g:ia', 'America/Los_Angeles') }} still outputs 12/11/2016 1:00pm

Am I doing something wrong? Or is there a different way to do this?


texts: Redactor source plugin working on Text field but not on a Text field in Matrix

texts:
I'm on 2.6.2988, I have a text-block in my entry with standard Redactor settings enabled showing the source-button in the menu.

In the same entry I have a Matrix field with text-block with standard Redactor settings but the source-button is not showing.

Is Matrix using a different config?


texts: How long does the share link on the entry edit screen last?

texts:
We're noticing that links to hidden entries that are shared via token (share button) eventually expire.

How long do these links last? Is there a setting to adjust how long the token will last?


texts: How can I test if a field has been assigned to a channel?

texts: I've got a generic template that can display entries from different channels. How in the template can I test if a field has been has been assigned to any given channel?


texts:
admin/commerce/store-settings/paymentcurrencies

There is no Croatia on currency list HRK
How to solve that...

Is it possible (in Craft Commerce V2) to have multi STOCK location fields for products

1 product can be on different locations in same time


texts:
I am attempting to delete a commerce line item with ajax request but nothing ever deletes. Am i doing something wrong? Vue function below:

removeLine(id) {

            axios.post('', {
                    [this.csrfName]: this.csrfToken,
                    action: 'commerce/cart/update-cart',
                    lineItems: {[id]: {'remove': true}}
            },
            {
                headers: {
                    'X-CSRF-Token': this.csrfToken
                },
            }).then(function (response) {

            }).catch(function (error) {
                // handle error
                console.log(error);
            }).finally(function () {
                // always executed
            });
        }


texts: Logged in admin, can't see front end site when system is off

texts: This just started happening. When I am logged in as admin and system status was off I could still see the front end. Now I can't. I need to set the system status to on in order to see the front end. This isn't ideal for development. Any thoughts?


texts: Craft install failed with error php7 not found, but server has php 7 installed

texts:
I'm trying to install a backup from production site which is running craft 3.0.26 to a UAT site. While installing, faced an error regarding PHP versions. Since both the sites are in the same server, where server shows php71 as the version, but while trying to install craft on UAT site using ssh, its showing error since PHP is running on 5.6.0.

Please help need regarding this.


texts: How to search/filter in CP by date range?

texts:
Is there a way in the control panel to list all entries with a date field between two dates? For example, last updated between 12/16/2019 and 2/15/2020.
Interested in doing this for both automatic date fields (created, updated, postDate) and custom.


texts:
I have redactor with plugin code mirror installed
however i want to put code mirror read only.

How can i do that the read only?
Thanks in advance.
Carlos Vieira


texts: How to Deploy CraftCMS to Dreamhost w/Github

texts:
I was recently able to get Craft CMS installed on my local server and I am using MAMP to host locally as I develop the site.

I have never set up a site on my own, so I was hoping someone could give me some instructions on how I eventually post my site.

I already have a domain registered through DreamHost and I am prepared to set up a managed server or VPS, but how will this work in the end?

Ideally, I would have things set up so that I could push everything to github and the site would update automatically. I've used GitHub pages before, so this is the process I'm most familiar with.

Thanks


texts: Craft 3 Controller - Redirect with errors

texts:
I cant get this to work.

I'm doing a post to a controller action. From that action I'm doing a lot of validations, db insert, file uploads etc.

Coming from Laravel Im used to is doing like this: (example with no real variables or methods. Just for visual presentation)

if(!$something->success){
  return redirect("controller-url")->withErrors([$model->errors]);
}
// Next steps...

From what I can read in the docs Craft recommend posting to the same page to handle errors and pass the model down to the view, but then doing a page refresh will do the same again so I dont like that.

My Controller is like this :

Index (Renders index template)

public function actionIndex()
{
    $this->renderTemplate("plugin/settings");
}

Post

public function actionPost()
{
  if(!$model->validate()){
    Craft::$app->getSession()->setError($message);
    return $this->redirect("url-to-index-action");
  }
}

So the setError() works fine but I want to the pass all the errors from the model to the index action after a redirect and then down to the twig template. How?


texts:
The Admin login screen for my site is not working.

The button to submit my credentials is greyed out and submission by pressing enter is not working either.

Not sure how to go about solving this one or updated the site to fix it if there is a bug?


texts: Building a DbCommand to compare two columns on Variants

texts:
I am trying to compare two fields located on Variants in Commerce. One is the price field and then I also have an original price field which is a custom field. I want to compare and get all variants where the price is less than the original price.

$query = craft()->db->createCommand()
            ->from('commerce_variants')
            ->where("price < field_originalPrice")
            ->queryAll();

return $query;

This is what I have so far but could be way off on this since that custom field is actually on the content table.

Any help would be awesome! Thanks!


texts: Amazon S3 folder path doesn't seem to affect file uploads

texts:
I'm using the amazon s3 asset source which all connects and works very well, the only trouble is that the assets field folder path is not respected.

I have a bucket called 'client' and in there we have three folders:

audio
documents
images

In my asset field which i want users to upload audio to, i set the file path as 'audio', '/audio', '/client/audio' but when i upload a new file via the entry form, it puts the file at the same level as the three folders.

Any clues as to why this might be happening?


texts: Is there any known way to get all the entries from a certain channel? I dont want to do this in a view but in PHP since i need to do a bulk update of an attribute to all the entries in a certain channel.


texts:
i wanted update a new installed craft3 and got this message:

I took a look in the web.log file. The first line from today gives an error:
2018-04-25 03:39:23 [85.7.133.198][-][-][error][yii\base\InvalidConfigException] yii\base\InvalidConfigException: Unsupported DB driver value:  in /home/velolade/craft3/vendor/craftcms/cms/src/config/DbConfig.php:187

What's wrong here?
Thank you in advance for help!


texts: Using a GraphQL mutation to append a block to a Neo field

texts:
I know how to update simple fields on an entry using a mutation:
mutation updateRecipe($recipeId: ID, $slug: String) {
  save_recipes_recipe_Entry(id: $recipeId, slug: $slug) {
    id
    title
    slug
  }
}
Variables:
{
  "recipeId": 8614,
  "slug":"new-slug"
}

Is there a way to append a block to a Neo field using mutations? I can retrieve the field data in a GraphQL query but have not found a way to update a Neo field with a mutation.
Does anybody have any experience implementing this?
Thanks ...


texts:
I added a nginx config rewrite rule to remove static asset numbers from file names. It works great on the server config file.

    # enable static file caching
    location ~* (.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif|webp)$ {
     try_files $uri $1.$2;
    }

However I'm now trying to use a custome serve-craft.sh on my homestead local to replace the default serve.laravel.sh. (to prevent losing my nginx config every time I do a reload --provision).

I'm not familiar with sh syntax and the following doesn't seem to work when I load the sh by adding a "type:craft" to my homestead.yaml
I suspect the try_files line has syntax error

How could I rewrite this in shell script?

Any idea anyone?


texts: Displaying entires by year from a custom date field

texts:
I have a date field (date) in my entry and I wish to get all entries of a specified year.  Can’t figure it out at all.  Here’s what I have now, to sort them by that field:

craft.entries.section('evenements').order('date desc')

My "year" is passed to the page through routing and is named "year".  I can get that.

Thanks


texts: Set duration of 'newpassword' link validity via config/general?

texts:
Is it possible to modify how long the 'newpassword' links are valid for via a setting in config/general.php?
(I've found defaultTokenDuration but it sounds like this might only be for the live preview tokens?)


texts:
I need to get data from fields from another section.
My code is:

        {% for kontaktEntry in craft.entries.section('kontakt').entry.kontakter %}

                    {% set image = kontaktEntry.bilde.first() %}
                    {% if image %}

                    {% endif %}

{{ kontaktEntry.navn }}

                    {{ kontaktEntry.stilling }}

        {% endfor %}

kontakter is a matrix. I get nothing in output. What is wrong here?


texts:
In Craft Commerce 2, we have two shipping categories:

PostNL, which is one of the Dutch main shipping methods, which we use for packages that fit in the mailbox.
For this category we use the weight as a measurement, and the consumer pays the whole shipping price based on the total weight of the order.
Shipped by courier, for products that don't fit the mailbox we send them by courier.
For Courier the shipping costs are different per product per zone and the consumer pays the shipping per product.
So when we have 10 crates, the consumer pays the shipping cost 10 times.

I am looking for a way to add the shipping costs per product per zone and when someone orders a product in both categories only the courier category will fit.

I could think of two routes:

creating multiple shipping categories that fit each product separately; then the question would be how would I set this up best.
create a plugin that reads a specific field(s) per product and zone; then the question would be what would be the best place to hook this in.


texts: Why can I view images assets if the asset link is broken?

texts:
I just uploaded my site to a live server.  My image assets all show a grayed-out broken image icon.  I assume this is because the image assets settings are not set to the correct new path.

If so, why can I view the image when I select it and the images appear on all pages and posts?


texts:
Is there a kind of “search in results after you retreived all entries” thing? Thing is: I have this query:
craft.entries.section('players').limit(null)

I want to show all entries where playerPosition = goalie. And on the same page, I want to show all players where playerNationality = Nederlands. And on the same page I want to show the longest player (sorted by playerHeight).

I can off course run a query 3 times:

goalies = craft.entries.section('players').playerPosition('goalie').limit(null)
nationalplayers = craft.entries.section('players').playerNationality('Nederlands').limit(null)
longest = craft.entries.section('players').order('playerLength desc').first();

That would work, but I'm running a query 3 times on the same section. There must be a better way, right? – Some have told me about the SuperSort plugin (which was indeed the right solution for my previous question), but that only sorts results. It's not a real filter.


texts: my vendor/craftcms/cms folder delete automatically after every update or install

texts:
I was on version 3.1.22. As usual, I wanted to install the update on Craft CMS 3.1.23.
So I clicked Install and got this error:

  Status: Error

But that was not all ... My complete vendor/craftcms/cms folder has been deleted. The solution to get back to the CP and the frontend, was to manually upload 3.1.22 back to the folder. When I started the update again - same error. In the while, I have manually updated to 3.1.24. However, I can no longer update plugins or install new ones. The CMS folder is deleted every time.

Does anyone have a similar problem or idea how to solve this? Thanks!


texts: User data segregation for multi-sites in Craft 3?

texts:
How will data be handled in Craft 3, when it comes to the 'multi-site' feature?

Will most structured data will be accessible across sites?

What about user data?

If I have 'Site A' and 'Site B' running off the one install and someone creates an account on Site A, will they also have an account on Site B?

Will we be able to restrict which CP users see data from which site?


texts:
What I'm doing is fairly simple:

{% cache %}
    {% set jobs = craft.entries.section('job').find({ order: 'dateCreated asc', limit: 0 }) %}
    {% for job in jobs %}
        {{ macros.jobProfile(job) }}
    {% endfor %}
{% endcache %}

... where the macro simply renders a block with a couple of things in it. I need to display all 200 entries I have, but Craft usually times out on that query (128MB RAM set).

Is there a way to tell Craft to not fetch all fields of that query, so I can optimize it directly at that point? I believe I have some content blocks in there, which probably go into RAM and eat it up, but are not needed at that time.

Any other recommendations are highly welcome. (I don't wanna write a plugin, or paginate at this point.)

Update:

{% macro jobProfile(job) %}

    {% import _self as macros %}

        {% cache %}
            {% set attributes = job.jobProfileAttributes %}
            {% set attributeStr = "" %}
            {% set counter = 0 %}
            {% for attr in attributes %}
                {% if counter == 0 %}
                    {% set attributeStr = attr.slug%}
                {% else %}
                    {% set attributeStr = attributeStr ~" " ~attr.slug%}
                {% endif %}

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

{{ job.jobProfileDesignation|raw }}

        {% endcache %}

{% endmacro %}


texts:
I have a number of different models that have custom validation methods, some of which are shared across models.

Due to the combinations I can't use class inheritance to share those methods, so I wondered if traits are supported and if so, what the convention would be?


texts: Is there a guide for using Craft Commerce headless?

texts:
I’m trying to figure out the work involved in using Craft Commerce in a headless setup. Is it possible? I think so. How do I expose the Commerce functionality via an API, instead of through Twig templates? I don’t know.

I’ve done a general Google search, skimmed the Commerce docs, checked NY 17, and checked CraftQuest. I may have missed something. Can anyone point me in the right direction?


texts: Is it possible to insert items into specific positions in an array (rather than at the beginning or at the end), a bit like javascript splice? Say, if I wanted to add a value between items 2 and 3? Please note I want to add keys to the array rather than replace anything.


texts: How to Template Grid for Entries that Switch from Horizontal to Vertical?

texts:
How do you template to output across a grid that switches between vertical and horizontal posts?  I left the Craft/Trig off.

I know how to loop through and print entries using one orientation.  But how do I get it to change direction after every 2 and then switch back again, repeat...


texts: Using formattingAdd for custom  adding multiple  tags

texts:
Using Redactor in CraftCMS I've added the following to the redactor/Standard.json file:

{
    "formattingAdd": {
        "pre-php": {
            "title": "PHP Code",
            "args": ["pre", "class", "language-php", "add"]
        }
    }
}

The option appears in the format menu as expected.

The problem: When applying this new format, multiple

 tags are created (one set per block of code), where-as the default Format->Code option properly creates a single

 around the selected blocks of code.

Is there a way to get redactor to properly add

 tags with a custom class name?

Formatted with built-in Format->Code option:

Formatted with custom format option:


texts:
I'd like to create a variable from another variable. What I got right now is something like this:

{% set language = fr %}
{% if language == "en"  %}
   {% set fooAddress = en_foobar.globalAddress %}
{% if language == "fr"  %}
   {% set fooAddress = fr_foobar.globalAddress %}
{% if language == "de"  %}
   {% set fooAddress = de_foobar.globalAddress %}

What I'd like to do is:

{% set fooAddress = language  ~ "_foobar.globalAddress" %}

No problem with plain PHP (http://php.net/manual/en/language.variables.variable.php) but is this possible to do with Twig?


texts: baseCpUrl doesn't seem to work as I'd expect

texts:
We have a couple of different repos doing various things all on the same URL. All of these have a web folder equivalent and want to be above the root. With that in mind, I've set up the following directory structure:
public_html
│
└───files
│   └───craft
│   │   │   Craft stuff
│   │   │   ...
|   |   └───web
|   |
│   └───othersite
│       |   other framework
|       |   ...
|       └───web
|
└───public
    |   .htaccess

In my vhosts, I've set up aliases like so:
DocumentRoot "/var/www/public_html/public"
Alias /othersite/ "/var/www/public_html/files/othersite/web/"
Alias /craft/ "/var/www/public_html/files/craft/web/"

Then I have a htaccess file in public with the following logic
# Redirect specific URLs to the other framework
RewriteCond %{REQUEST_URI} ^/othersiteurl/?(.*)$ [NC]
RewriteRule ^othersiteurl/?(.*) /othersiteurl/index.php [QSA,L]

# Default to Craft if not already redirected
RewriteRule (.*) /craft/$1 [QSA,L]

For all the frontend code, this works perfectly, but I'm struggling with the control panel. It all works on the expected URLs, but all the nav links include craft, like domain.com/craft/admin/dashboard
I've got the cptrigger config set
    'cpTrigger' => App::env('CP_TRIGGER') ?: 'admin',

which all works as expected, other than adding the /craft/ bit into the URL.
I assumed that setting the baseCpUrl would get around this like so:
    'baseCpUrl' => App::env('SITEURL'),

But now if I go to domain.com/admin or domain.com/craft/admin I just get a 404.
I'm completely stumped. Any ideas what I'm doing wrong?
Thanks!


texts: CraftCMS: Search entries by title in CMS

texts:
In the CraftCMS admin page at /admin/entries/, there is a search bar at the top:

This search bar appears to only search the Body field of Entries.

Is it possible to make this search bar match against the Title field too?

Eg. I have an Entry titled "Example Entry" with a body of "Testing 1 2 3". If I search for "Testing", my Entry will show in the search results. If I search for "Example", my Entry will not show. I would like my Entry to show for the search term "Example"