texts: Craft Commerce - explain transaction types and statuses to me

texts:
Commerce transactions have multiple possible types and statuses:
    const TYPE_AUTHORIZE = 'authorize';
    const TYPE_CAPTURE = 'capture';
    const TYPE_PURCHASE = 'purchase';
    const TYPE_REFUND = 'refund';

    const STATUS_PENDING = 'pending';
    const STATUS_REDIRECT = 'redirect';
    const STATUS_PROCESSING = 'processing';
    const STATUS_SUCCESS = 'success';
    const STATUS_FAILED = 'failed';

Can someone explain to me what each of them means?


texts: Simple user query with orderBy not working

texts:
Craft 3.3.13

This query does not order users correctly.

{% set users = craft.users.groupId(3).orderBy('lastName asc') %}

Bug?


texts: How to transform German umlauts when creating slugs?

texts:
First of all, I want to thank you for creating Craft. It's really one of the best content management systems I have ever worked with.

I encountered an issue while working on a multilingual site: German Umlauts are not automatically transliterated (Ä -> Ae) for slugs. In other parts of Craft (e.g. field handles) Umlauts are transliterated automatically.

Personally, I would prefer if this behavior could be controlled by a config variable (e.g. slugExpandUmlauts).


texts: Contact Form Plugin how to send to different recipients based on country selected?

texts:
I'm trying to build a plugin that fires on the Contact Form Plugins contactForm.beforeSendwhat the plugin needs to do is add a recipient email if certain countries are selected. So far I have created the below which checks for the countries and checks against an array to see if they are in it. This works, so far so good. What I need to do now is somehow add to the contact form plugins $toEmails variable if a country is in the array but I'm not sure how to do this from within the event listener. Is this even possible?

public function init() {
    craft()->on('contactForm.beforeSend', function(ContactFormEvent $event) {
        $message = $event->params['message'];
        $ukArray = array('United Kingdom','Wales','Scotland','Ireland');
        $country = '';
        foreach ($message as $key => $field) {
            if($key == 'messageFields') {
                $country = $field['Country'];
            }
        }
        if (in_array($country, $ukArray)) {
            // add an email address to the contact form $toEmails array
        }
    });
}


texts:
I've got a working sort dropdown on my front end, but I'm after the dropdown keeping the chosen sort method option instead of resetting to the default top of the dropdown option.

e.g. User clicks sort by Name A - Z > Sorted by name > Dropdown option stays as 'Name A-Z' instead of 'default'.

    <select class="sort-web w-select" data-name="Sort" id="sortQuery" name="Sort">
        <option value="postDate asc">New - Old</option>
        <option value="title desc">Name Z - A</option>
        <option value="title asc">Name A - Z</option>
    </select>

Craft Code

{# Either get the order from the query or use a default #}
{% set order = craft.request.getParam('order', 'title asc')  %}

{% for category in craft.categories.group('university').order(order) %}
  {{ category.title }}
{% endfor %}

JS

{% set orderJs %}
  $(function(){

    $('#sortQuery').on("change", function(e){

     // Get the value from the select
     var filter = $(this).val();
     document.location.href = '{{ craft.request.getUrl() }}?order=' + filter;

   });

  });
{% endset %}
{% includeJs orderJs %}

Any help would be greatly appreciated!


texts: How to pull the first block of its kind from a Matrix?

texts:
This is a news feed with a title, image and short blurb beneath. The entry content is built with the Matrix. An entry can be made up of a single 'textEditorBlock' or multiple 'textEditorBlock'.

I just want to return the first 'textEditorBlock' from Matrix. Currently, all existing 'textEditorBlock' blocks get returned.

{# Count the number of Matrix Blocks; type: textEditorBlock  #}
{% set blocks = post.buildStory.type('textEditorBlock') %}
{{ blocks | length }}

{% for block in post.buildStory.all() %}
   {# the text #}
   {% set paragraphs = block.textEditor %}
   {% set teaser = paragraphs | length > 75 ? paragraphs | slice(0, 250) ~ '...' :  paragraphs %}
   <p>{{  teaser  | striptags | raw | typogrify  }}</p>
{% endfor %}

Note: the {{ blocks | length }} tells me the number of 'textEditorBlock' that exist for each entry (1, 4, 4, 2 and 2).


texts:
I am working on an intranet in Craft CMS.
Front-end editing is a very important part of this, and I want to get it perfect.

As it is now, the live preview is perfect for what I want, it provides markup and styling for all field types. If I where to make a custom front-end form for each entry type, including advanced matrix / neo fields etc. the workload would be huge, and I would probably end up doing something similar to what live preview already do.

Therefore I am trying to get live edit to work in front-end, or make it look like it does.

At the moment I just have a link to the CP when pressing "edit" on an entry. And have made use of a hook on afterSave to pick up the front-end url and send the user back to front-end when the entry is saved. This works semi seamless, but I cant figure out a way to trigger the live preview from php, or maybe how to inject some JS when editing an entry after pressing the link in front-end.

So the main question;
Should I keep going with the "trick" to just send the user back and forth between front-end and CP, or should I get the live preview to work front-end? If so, what is the best approach here, I could expose the CP recourses to the front-end, but that sounds like a horrible idea with many concerns.

-- Mathias


texts:
I am trying to get all entries from my events section in Craft 3 that occur after 17:00.

My current code is:
{% set events = craft.entries.section('events').eventStartTime('>= ' ~ '17:00'|time ).all() %}

The >= is being ignored as far as I can tell. The query just returns all events.

The eventStartTime field is a Date/Time field that is set to just show the time (I know that behind the scenes Craft still treats this as a DateTime object but I was hoping that the |time filter would help with that.

When I have created similar queries on a DateTime field but looking at the date rather than time, they have worked as expected - maybe I am missing something when it comes to the time portion of the object?

Any help would be appreciated.


texts: Missing field validation on user account edit

texts:
I've been implementing a user account page with Craft Commerce and copied over the template found here: https://docs.craftcms.com/v3/dev/examples/user-profile-form.html#simple-profile
The issue is though that the form doesn't seem to show any errors for individual fields, you just get the generic error message in the flash response.
If you take the example from the above link and enter an intentionally invalid email address (e.g a random string) theres no error response for the email field, just a generic "Couldn't Save User." response.
I've tried dumping out {{ craft.app.session.get('error') }}  in an attempt to see if theres some extra data and its just the above error.
Am I missing something here, or is it just not possible to get field based error messages out of Craft CMS / Craft Commerce?


texts: Can Craft easily be hosted across multiple servers?

texts:
We are looking at Craft as our CMS but would love to be able to scale the installation across multiple Amazon EC2 instances.

Is this possible?

Can all assets uploaded to Craft be pushed to S3?

Is there any other data (eg sessions) that are stored on local storage that would likely cause a problem?


texts: Variable 'foo' does not exist in template

texts:
I've uploaded my site to the live server and i'm getting

Template Error

Variable "heading" does not exist

On a couple of pages. This is only happening to 2 sections, the rest are all fine.

and it then goes onto identify the template and template var that it claims is missing.

But, there is no db or file difference to the local or dev sites!

I've cleared caches, double checked permissions, changed php versions to no avail. Any ideas?

Update, i had devmode set to true, and have set it to false now, but, now the page renders, it does not output any text content from the cms. Just an image. Odd.


texts:
This is definitely a noob question, but I can't seem to find an answer to this. (Completely new to GraphQL).

I'm trying to simply return entries:

query test {
  entries(section: "vacancies", limit: 20) {
    title
    expiryDate
    description
  }
}

Since the description is a custom field, this gives an error. How do I get a custom field value?


texts:
Are there any plugins like this Expression Engine feed parser?

https://devot-ee.com/add-ons/feed-parser

Temporarily cache an XML file from a website or API and list the results using standard Twig templating tags.


texts: Contact Form Plugin - Not sending/receiving emails?

texts:
I'm developing my first website on Craft 3 and I'm essentially a front-end designer so my PHP/MySQL/AJAX knowledge is extremely limited.

I installed the Contact Form plugin as explained here https://github.com/craftcms/contact-form and used the code example on the page (minus the redirectInput).

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

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

Your Name

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

Your Email

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

Subject

        <input id="subject" type="text" name="subject" value="{{ message.subject ?? '' }}">
        {{ message is defined and message ? errorList(message.getErrors('subject')) }}

Message

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

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

But when I submit my form, the page reloads then zwoooosh, nothing happens! I can't tell if I'm not receiving the email or if it's not even being sent. I checked pretty much everywhere for similar issues but can't tell what's happening or not happening.

I didn't install any mail server on Ubuntu, I don't even know if that is necessary. I checked my Spam folder... I'm a bit lost at this point!

Any help would... help!


texts: Freeform AJAX submission not working when two forms are on same page

texts:
I have two Mailchimp subscribe forms on the same page – one in the sidebar and one in the footer. They are created as separate forms in the admin, albeit one a duplicate of the other, with different IDs on the forms and different IDs on the Mailchimp field. "Enable AJAX" is selected on both forms.

When I submit the first form from the sidebar, it submits successfully but reloads the page (No AJAX). The second form works correctly, submitting via AJAX.

Is this a known limitation of Freeform Pro or simply a matter of a duplicate ID or class that I'm missing somewhere? I'd like to have AJAX work on both.


texts: Craft 3 Custom Field Type with a File Uploader

texts:
I have a custom field type I am porting from Craft 2 to Craft 3.

This field type used prepValueFromPost to grab a reference to a just uploaded file and then saves said file to an appropriate place for temporary storage (the file is sent on to a ticketing system which keeps its own copy so really it's only needed here for a few seconds).  The actual field value is jsut set to the full file path/name as a record.

I'm really struggling to port this across to Craft 3 as this area has seemingly been re-factored a lot...

I think I need to use serializeValue in place of prepValueFromPost, but I can't grab the actual filename from input in there and the value received is null (I expected it to be the filename..but it's not).  I used to use getContentPostLocation(); for this.

My specific questions are - is serializeValue() the right place to do this?  I want it to occur, once (per field - this is in a matrix), when the element (a Commerce Order) is saved.

And - how do I get the name of the uploaded file (i.e. what has replaced getContentPostLocation).

Here is the code that worked in Craft 2.

    public function prepValueFromPost($value, $element)
{

    $finalFilePath = null;

    //Weird function that works out the dynamic name of this field
    $filename = $this->getContentPostLocation();
    $file = UploadedFile::getInstanceByName($filename);

    //Save the file where we want it, delete the temporary file
    $outputDir = craft()->path->getTempPath() . "BusinessLogicPlugin_upload_" . time();
    IOHelper::ensureFolderExists($outputDir);
    //Was needed on dev, can't really hurt...leave it here.
    chmod($outputDir, 0775);

    $finalFilePath = $outputDir ."/" . $file->name;

    if(!($file->saveAs($finalFilePath, false))){
        BusinessLogicPlugin::log("Unable to save actual file [$finalFilePath], file will not be attached");
        $finalFilePath = "";
    }

    //Save the pathname of the file, if we were able to save it, otherwise empty string.
    return $finalFilePath;
}


texts: What's the function of the Stalled Tasks menu option?

texts:
Just wondering...

What is the function of the Stalled Tasks menu option?
What is it supposed to do when clicking on it?
Is it normal for it to be there... all the time?
Is it normal for the browser to freeze when I click on it?


texts: Remove subdirectories from admin URL with .htaccess

texts:
I have Craft public files set up within subdirectories of a primary domain’s web root.

public_html/ # default web root
public_html/example.com/public_html/ # Craft public files here

The following .htaccess rules allow for the public_html subdirectory to act as the new web root. This is the .htaccess within the first public_html directory.

RewriteEngine on

RewriteCond %{HTTP_HOST} ^example.com$
RewriteCond %{REQUEST_URI} !^/example.com/public_html/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /example.com/public_html/$1

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule ^(/)?$ example.com/public_html/index.php?p=$1 [QSA,L]

It works until I go to example.com/admin.

I can login and cp works, but the URL is http://example.com/example.com/public_html/admin/dashboard

I'd like to remove the subdirectories from the above admin URL for mere aesthetic reasons, but can’t seem to nail it down.

Note: When going directly to http://example.com/admin/dashboard, for example, the URL remains as is, but all the internal links have the subdirectories.


texts:
Have read this article, but still having issues.

Craft 3.0.4
Imager 2.0.0

My template code is:

{% set image = block.image.one() %}
{% set focalPoint = image.focalPoint | default("50% 50%") %}

{#
  // set transform for floated images
  // override in full width
#}
{% set transformedImages = craft.imager.transformImage(image,
    [
        { width: 400, ratio: 4/3, jpegQuality: 85 },
        { width: 640, ratio: 4/3, jpegQuality: 85 },
    ],
    {
        format: 'jpg',
        allowUpscale: false,
        mode: 'crop',
        jpegQuality: 80,
        interlace: true,
        position: focalPoint,
    }
) %}

{# determine if image floats or not #}
{% if block.imageFormat == "left" %}
  {% set imageClass = "floated-left" %}
{% elseif block.imageFormat == "right" %}
    {% set imageClass = "floated-right" %}
{% else %}
    {# full width #}
    {% set imageClass = "full-width" %}
{% endif %}
{# end floats or not #}

{# full width image here #}
{% if block.imageFormat == "fullWidth" %}

{% else %}
{# floated images here #}
  <img
    src="{{ craft.imager.base64Pixel(16, 9) }}"
    sizes="(max-width: 640px) 640w, (min-width:641px) 400w"
    srcset="{{ craft.imager.srcset(transformedImages) }}"
    class="{{ imageClass }}"
    >
{% endif %}

What I expect to happen is that at widths smaller than 640px an image with a width of 640px is served up, at widths 641px and larger and image of 400pxs is served up.

However at large widths I see the 640px width image.

The outputted code on the front end is:

<img
  src="data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20width%3D%2716%27%20height%3D%279%27%20style%3D%27background%3Atransparent%27%2F%3E"

  sizes="(max-width: 640px) 640w, (min-width:641px) 400w"

  srcset="/imager\uploads\32\love-letters-in-pink-hearts_4460x4460-1_d5a1008e3f8fb9f7c44fa92474183c3e.jpg 400w, /imager\uploads\32\love-letters-in-pink-hearts_4460x4460-1_3edaa49114a08f6f3438bb6daad2e68a.jpg 600w, /imager\uploads\32\love-letters-in-pink-hearts_4460x4460-1_7c3d51f40436135917e37f29c276802d.jpg 640w"

  class="floated-left">

Not sure what I'm doing wrong. Please advise.


texts:
Several visitors, over the course of weeks, have mentioned receiving the following error when viewing the site:

CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

The log file shows the error (below). Not just once, but multiple times within a short time span.

Has anyone seen this error?

Any insight as to what's going on here is appreciated.

2014/12/24 13:57:46 [warning] [application] The request to freegeoip.net failed: Server error response
[status code] 502
[reason phrase] Bad Gateway
[url] http://freegeoip.net/json/182.171.233.223
2014/12/24 13:57:46 [error] [system.db.CDbCommand] CDbCommand::fetch() failed: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away. The SQL statement executed was: SELECT  'elements'.'id', 'elements'.'type'
FROM 'craft_elements' 'elements'
JOIN 'craft_elements_i18n' 'elements_i18n' ON elements_i18n.elementId = elements.id
WHERE (elements_i18n.uri = :uri) AND (elements_i18n.locale = :locale) AND (elements_i18n.enabled = 1) AND (elements.enabled = 1) AND (elements.archived = 0).
2014/12/24 13:57:46 [error] [exception.CDbException] exception 'CDbException' with message 'CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/framework/db/CDbCommand.php:543
Stack trace:

#0 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/framework/db/CDbCommand.php(415): CDbCommand->queryInternal('fetch', Array, Array)
#1 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/services/ElementsService.php(147): CDbCommand->queryRow()
#2 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/etc/web/UrlManager.php(278): Craft\ElementsService->getElementByUri('', 'en_us', true)
#3 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/etc/web/UrlManager.php(137): Craft\UrlManager->_getMatchedElementRoute('')
#4 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/framework/web/CWebApplication.php(140): Craft\UrlManager->parseUrl(Object(Craft\HttpRequestService))
#5 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/etc/web/WebApp.php(264): CWebApplication->processRequest()
#6 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/framework/base/CApplication.php(180): Craft\WebApp->processRequest()
#7 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/craft/app/index.php(62): CApplication->run()
#8 /nfs/c06/h06/mnt/187742/domains/obozfootwear.com/html/index.php(14): require_once('/nfs/c06/h06/mn...')
#9 {main}

REQUEST_URI=/HTTP_REFERER=http://www.google.co.jp/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCAQFjAA&url=http%3A%2F%2Fobozfootwear.com%2F&ei=8MWaVKfVBtGE8gWz-oKIBg&usg=AFQjCNGF_NGGtGdApatcXOoA3BYgIYOnZg&sig2=mmDpzpWjXopxNLsBnUTj6g&bvm=bv.82001339,d.dGc

2014/12/24 13:57:46 [error] [application] CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
2014/12/24 13:57:46 [error] [system.db.CDbCommand] CDbCommand::fetchAll() failed: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away. The SQL statement executed was: SELECT `id`, `groupId`, `name`, `handle`, `context`, `instructions`, `translatable`, `type`, `settings`
FROM `craft_fields`
WHERE context = :context
ORDER BY `name`.


texts: Can't set structured entry parentId in BEFORE_SAVE event using field data

texts:
I have created an event that is called on beforeSave within my plugin. Code below:

Event::on(
        Entry::class,
        Entry::EVENT_BEFORE_SAVE,
        function(ModelEvent $event){
            /** @var Entry $entry */
            $entry = $event->sender;

            if($entry->section == 'Question' && $entry->type=='reply') {
                if($entry->newParentId != $entry->question->id[0]){
                    $entry->newParentId = $entry->question->id[0];
                }
            }
        });

I can change things like title and that works fine but the parent will never set. I have even added the following to see if this helps but it doesn't

if ($entry->newParentId) {
    $parentEntry = Craft::$app->getEntries()->getEntryById($entry->newParentId, $entry->siteId);
    if (!$parentEntry) {
         throw new Exception('Invalid entry ID: ' . $entry->newParentId);
    }
} else {
    $parentEntry = null;
}

$entry->setParent($parentEntry);

Please Note: This is not a custom element!


texts: What is the future for the Craft rich text editor?

texts:
I can (almost) appreciate the recent impositions of Redactor 2, but when it comes to handing off the site to a client, Redactor 2 is virtually unusable for anything more than paragraph text.

Are there any other rich text editors being considered as core replacements in the future? If so, +1 for an implementation of Froala into Craft. I see there is already a Yii2 implementation available.


texts: Neater way to merge this conditional entry query?

texts:
I know there's a better way to do this - eg by merging in the relatedTo parameter if categorySlug is defined rather than defining 2 different queries, but I can't for the life of me figure it out... how would you simplify this?

{% if (categorySlug is defined) and (categorySlug != null) %}
   {# GET CONTENT FROM ONE CATEGORY #}
   {% set contentQuery = craft.entries
   .section(contentSection)
   .isFeatured('not 1')
   .relatedTo(craft.categories.slug(categorySlug))
%}
{% else %}
   {# GET ALL CONTENT #}
   {% set contentQuery = craft.entries
   .section(contentSection)
   .isFeatured('not 1')
   %}
{% endif %}


texts: How can I show a list of product options as checkboxes in the cart?

texts:
In my cart (Craft3/Commerce2), I need to show a line item's possible options from a checkbox field called "productOptions", and allow the user to select the desired options.

Based on the Craft Docs, I can manually test if an item.options exists, but this means hard-coding the list of possible options(35+) into the cart, and keeping that updated as available options change:

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/update-line-item">
    {{ redirectInput('cart') }}
    {{ csrfInput() }}
    <input type="hidden" name="lineItemId" value="{{ item.id }}">
    <span {% if item.getFirstError('qty') %}class="has-error"{% endif %}>
    <input type="number" name="qty" min="1" value="{{ item.qty }}"></span>

{#  Manual List of Options to Test if Exists #}
    {% if item.options.optionOne is defined %}
        <label class="checkbox">
            <input type="checkbox" name="options[optionOne]" checked> Option One
        </label>
    {% endif %}
    {% if item.options.optionTwo is defined %}
        <label class="checkbox">
            <input type="checkbox" name="options[optionTwo]" checked> Option Two
        </label>
    {% endif %}
            ...

OR, I can output the list of product options available for a given product, and use that to update the cart:

{#  To access the product options, set a variable "product" #}
    {% set product = item.purchasable.product %}
    {% for key, value in product.productOptions %}

        <label class="checkbox">
{#          <input type="hidden" name="options[{{ value }}]" value=""> #}<!-- uncheck it if not checked -->
            <input type="checkbox"  name="options[{{ value }}]" value="on"
            {% if item.options.value is defined %}checked{% endif %}> {{ value }}
        </label>

    {% endfor %}

    <input type="submit" class="button" value="Update"/>
</form>

But I can't seem to figure out how to test if the checkbox is selected/value =="on" from the cart array. I know that
{% if item.options.value is defined %}checked{% endif %}
is not the correct way to access this value if it even can be accessed in this for loop.

Help? Many thanks in advance!


texts: Show the best sellers and the most visited products - Craft Commerce

texts:
I´m working on a new online shop and want to show the best sellers and the most viewed products.

Is this possible to do with craft commerce? I guess so, since it´s a basic functionality, but I could not find how to do this in the docs.

thanks.
Sebastián.


texts: Auto add Images to entry after ftp to server

texts:
I have a potential client (car dealership) where in their existing 12 year old site they daily upload an Excel file to add/update/delete vehicles in stock. One file for new vehicles and one for used.

However the excel file does not have a column for images and they are unwilling/unable to add one. Instead they want images to be added in the same way they currently are.

All images are ftp'd up to the server and are named ##_stocknumber so 01_12345, 02_12345, 03_12345 would be attached to the same entry but 01_4455, 02_4455, 03_4455, 04_4455 would be attached to a different entry. After upload the go to a link that processes the images and then emails any stock numbers that are missing images.

Is there some way that this can be achieved in Craft?


texts: What are the best-practices for useful logging messages?

texts:
I'm currently adding messages to the log when an error occurs in my plugin.

Now I'm wondering what such a message should contain, to provide useful information to developers and end-users?

.

Currently my logged errors/warnings look like this:

  "functionName": A simple explaination of the error:
  "$related_var"

Actual example:

  "_getUserGroupUsers": No Users found in UserGroups with ID: "1, 2"

.

Is this something a developer/user checking the logs would find useful, or should more information be passed? If so, what else?

Also are you just logging errors/warnings or also valid operations (something like a StackTrace)?


texts: Getting info on the currently logged in user

texts:
Trying to get the currently logged in user's groups. Trying to get at that by using the user ID. I am currently testing as Admin - user number 1.

Craft::$app->getUser()->id

Returns a user ID (11) that does not exist in the Users table. The Users table has ID's of 1, 20, 21.

How do I get user ID or more specifically, the currently logged in user's groups?


texts: How do you save custom fields along with the user/saveUser action?

texts:
We are building a simple user import plugin, saving the basic user is easy enough but how does one save data to the custom fields added to users

Basic exmaple:

$user = new UserModel();
$user->status = UserStatus::Active;
$user->firstName = 'Fruit';
$user->lastName = 'Studios';
$user->email = 'email@domain.com';
craft()->users->saveUser($user);

This all works great but i cant work out how I add the custom fields?? The following will abviously not work because 'postCode' is not part of the User Model:

$user->postCode = 'SO23 9UG';

Where am I going wrong?


texts: Modify ElementCriteria and use it for paginate

texts:
First some context. I'm using Smart Map for Craft to display some location based events in a listing. My structure is as follows:

Events channel
Locations channel

Each event can occur multiple times, so I created a matrix field for this, where they can add blocks with a time and select a location.
The problem occurs when I want to filter the list of results based on the city of the location. Smartmaps doesn't support filtering by cities and I do want to use pagination, so I went with the custom plugin solution mentioned in that question. Unfortunately I can't comment yet on that answer, so therefore I created my new question.
The problem is that Craft {% paginate %} doesn't work with the Array result of EntryModel::populateModels. I'm getting the following error in my search results page:

Argument 1 passed to Craft\TemplateHelper::paginateCriteria() must be an instance of Craft\ElementCriteriaModel, array given

So my question is, how can I modify the ElementCriteriaModel to join content from different tables (in this case Smartmaps') and still return an ElementCriteriaModel to be used by the Craft pagination?
I also have read some more explanation about ElementCriteriaModel and some similar issues like this one and this one, but without any luck. Maybe there is a much simpler solution, but I'm out of options for now.


texts: How do I use the Element API to search via entry title?

texts:
I can't seem to find this anywhere. Thanks.

Update:

'api/entry/search.json' => function() {
    return [
        'elementType' => 'Entry',
        'criteria' => [
            'search' => (craft()->request->getParam('search')) ? craft()->request->getParam('search') : ''
        ],
        'first' => true,
        'transformer' => function(EntryModel $entry) {
            return [
                'title' => $entry->title,
                'url' => $entry->url,
            ];
        },
    ];
},

Using the url: api/entry/search.json?search=title:test did not work.

This code works, but the title needs to be exact:

'api/entry/search.json' => function() {
    return [
        'elementType' => 'Entry',
        'criteria' => [
            'title' => craft()->request->getParam('title')
        ],
        'first' => true,
        'transformer' => function(EntryModel $entry) {
            return [
                'title' => $entry->title,
                'url' => $entry->url,
            ];
        },
    ];
},

Using this url: api/entry/search.json?title=Test%20Article, works, but not api/entry/search.json?title=Test


texts: Commerce: How to implement/save 'Use shipping for billing' field for future orders

texts:
There is a 'Use shipping for billing' field in the Craft Commerce sample templates but it is unclear to me how to use that in the CP or for an account user in their account or for a future checkout.

I cannot find any documentation regarding this field in the Commerce documents. Is this only being used on the sample templates to handle front end display logic?

We want to be able to save this field so that when an account holder logs into their account, we can show their Shipping and Billing address in the correct state (ie. Billing address fields hidden and 'use shipping' checked). This would also apply to future checkouts too.

Is there a way to do this with the Commerce address fields? Or would we have to add a non-Commerce custom field to Users to save this and then add logic accordingly based on that field? And if yes, would that mean a separate ajax post to save that non-Commerce field during a checkout - or would it get saved to the User profile along with everything else?


texts: Upgrade C2 to C3 Uncaught TypeError involving Dotenv

texts:
I am just trying to upgrade and get the following error message:

Fatal error: Uncaught TypeError: Argument 1 passed to Dotenv\Dotenv::__construct() must be an instance of Dotenv\Loader, string given called in (…) /html/index.php on line 17 (…)

Which is completely new to me. Never happened before and my setup is pretty standard. Is this a hosting Problem? Can’t make anythiong of it.

Craft version seems to be 3.3.4 according to the name of the zip (Craft-3.3.4.1.zip).


texts: Commerce: How can I dynamically create a discount for any given product?

texts:
I am inspecting my cart when the user visits /commerce/cart and if the cart contains a specific product, I want to alert the user that they can redeem a credit for "x" item. If the users chooses to use the credit, I would like to assign the qualifying product a discount.

...
if ($lineItems) {
    foreach ($lineItems as $lineItem) {
        foreach ($lineItem->purchasable->product->foo as $bar) {

            ...
            // qualifying product found - return json to javascript
            ...
        }
...

$discount = new commerce_DiscountModel();
...
??
// apply discount to cart/update ui via javascript to reflect discount

I'm able get all the way up to creating a new discount. I assume I start by creating a new discount model and populate it with the price of the product I am wanting to discount? I'm not really sure where to start - thank you for any suggestions!

EDIT

First off, thank you, Jeremy for your help. I (think) I am slowly starting to understand. I don't understand how or why the handler is or isn't getting called.

Here is my updated main plugin file:

MyPlugin.php

public function init()
{
    error_log(__FUNCTION__); // this is logged

    craft()->on('commerce_discounts.onBeforeMatchLineItem',
        [
            craft()->myPlugin,
            'onBeforeMatchLineItemHandler'
        ]
    );
    ...
}

Then my service file looks like this:

MyPluginService.php

class MyPluginService extends BaseApplicationComponent
{
    public function onBeforeMatchLineItemHandler($event)
    {
        // this method never gets executed

        $cart = craft()->commerce_cart->getCart();
        $lineItem = $event->params['lineItem'];
        $discount = $event->params['discount'];

        error_log('line item: ' . $lineItem);
        error_log('discount: ' . $discount);
    }

    ...
}

If I change the name of the handler to "myPluginz" or something that doesn't exist, it throws an error, so I know I have the right syntax at least.

The handler was actually called once, but now it never gets executed. The product I have in my cart is promotable, and is not excluded from any sale. So it seems I am matching the criteria needed.

I also tried this straight from the docs.

public function init()
{
    error_log(__FUNCTION__); // this is logged
    craft()->on('commerce_discounts.onBeforeMatchLineItem', function ($event) {
        error_log(print_r($event, true)); // this is not executed

    });
}

I don't understand what I've done wrong to cause the event not to fire.

EDIT 2

Well, I think I have finally managed to get out of my own way. I'll update this thread as I progress through.


texts: Get and display a product's variant fields in twig

texts:
I'm working on a product template that can display products of any type.

Various product types have varying numbers of variant fields each with their own options as other products. (All of my variant fields pull in other product types.)

I want to display each variant field's options as a separate dropdown on the product page.

Can I dynamically fetch the product's variant fields and field options in my product template? I would need, for a given product, to be able to get:

Its product type's variant fields to loop through
Each field's:

Options (and I'd want the option of starting the option list with a "None" option)
Or product type source(s), so that I could display those in an option list directly.


texts:
I am looking to see if there is an easy way or already a plugin available that would replicate the entries structure layout.  I plan on creating a plugin that would allow an admin to mass update a select set of fields.

I notice it does an ajax call to index.php?p=admin/actions/elementIndex/getElements to get the first 50 entries and then subsequent calls to get more as you get near the end of the results.

I see one of 3 potential ways to do it and wondering which way would be ideal.

Try and call this same ajax call as it returns the html and do some manipulation to the html to add additional functionality I need.
Find methods that are being called from craft core and copy them into my plugin and modify as needed then do similar ajax call to my plugin.
Just write my own custom code to grab what I need.

I am leaning on number 2 as the ideal scenario but have not looking to see if this  is unreasonable as it may be tied to a lot of different areas of the core code.

Looking to get some opinions as I am guessing others have already gone down this road.

Thanks

UPDATE with more info

I want to mimic the entries admin structure layout page for a specific section.  Once I mimic it I will add a little different functionality to it.  So currently you can select multiple entries and mass update the status or delete those entries and that is it.  I plan to add some additional options to change some custom fields that are associated with that section.  So if I am in the admin and I go to /admin/entries/meetings and meetings is a section with a type of structure I would see the tree layout of all the meetings in my case it is 5 levels deep.  There are 3 custom fields that change monthly and when they change about 30% of the meetings setup need to be changed.  The idea is they could select all of them that need these 3 fields updated and can do a mass update.  Currently they have to go into each meeting and make the change which is very time consuming.  Hope that makes more sense.


texts: Exclude a block from appearing on a specific page

texts:
I'm currently trying to make my navigation be not included on my index page due to my loading a different style of page - but - include it on every other page. My current layout looks like so:

_layout.html

{% set exclusions = ['index'] %}
{% if craft.request.firstSegment not in exclusions  %}
    {% include '_navigation' %}
{% endif %}

But this seems to not work on my "index.html" page. Do I need to set it a title? or set an exclusion name here?


texts: Allow registered end-user to update entry, but limited only to specific fields (Craft 3)

texts:
I want to allow end-users (registered as users in Craft) to update only specific fields of an entry. I know that only those fields included in the form are being updated; but this isn't secure enough.

I'm looking for a way to manipulate the form POST request sent to the 'entries/save-entry' controller so that only specific fields will be updated. I know how to access the onBeforeSave event so that I can manipulate the entry object that will be saved to the database. I already use this to make sure that the user can only update one specific entry (because including the entryId in a hidden form field isn't secure enough).

However, I don't find a clever way to include only certain fields. The only way that comes into my mind is to overwrite all fields in the entry object that the user is not allowed to update with the current values from the database. This way is cumbersome because that entry type has so many fields.

Any idea how to filter the element so that I can supply an array with field names that will be included in the save process?

Best regards,
Mischa


texts: How to list all existing values for a field across site

texts:
I have a huge set of entries which have a lot of fields. Say, the entry type is a 'book' and fields are 'keywords', 'year', 'authors', etc.

Now I'm building a filter form which would allow user to output entries by field values. On frontend side this form contains generally inputs with datalist tags which should contain all of a specific field's values. For example, the datalist for the 'Year' search input should contain all years ever set for all the books on the site.

How do I do this efficiently, how do we list all existing values for a field? This answer proposes to loop through each entry every time and collect the field values used in entries in an array - but when I tried to do it I hit the memory exhausted problem.

An example code of the approach which leads to memory being exhausted:

{% set years = [] %}
{% for book in craft.entries.section('books').year.order('year desc').limit(0) %}
    {% if book.year not in years %}
        {% set years = years|merge([book.year]) %}
    {% endif %}
{% endfor %}

{% for year in years %}
    <li>{{ year }}</li>
{% endfor %}


texts: Localization - How do we manage multilingual, multi-environment on multiple domains?

texts:
I read this KB article about localization though, the examples are for sub-folders.

I'm wondering how to handle the same concept but, for different language based domains e.g.

example.com
example.mx
example.es

Currently I'm not sure if the different sites will be based on language or country though, let's assume country for this question. For example we'll have Mexico and Spain sites, both will be in Spanish but, will have different content which relates to each country.

I asked CraftCMS about this on twitter and this was their reply.

Am I right to think that each site will have an install of craft, with the config/ general.php setup accordingly (in this case using domains instead of sub-folders?)

And then we'll just link to the db in it's settings on each copy of config/db.php

With that said, I'm hoping for some elaboration on this topic. Bonus points for including a multilingual, multi-domain and multi-environment for git workflow/setup in your answer ;)


texts:
As someone relatively new to Craft I'm constantly switching between a content type and /admin/settings/fields so that I can see the handles for that content type. It just occurred to me that it would be relatively simple to show the handle right next to the field's name on the edit content screen. Might there be a setting for this somewhere, or would I have to (or be able to) create a plugin to do this?

In case it's unclear, I'm looking to turn this

into this


texts: How to call two separate images from Matrix field

texts:
I'm new to Craft and using Matrix fields.

I've got a matrix field called imageDouble with two child fields called firstImage and secondImage.

The template code I have is returning a 500 error. I want it to display firstImage and secondImage each in their own separate div. Any help with my structure here?

{% for block in entry.body %}

    {% if block.type == "text" %}

{{ block.textContent }}

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

        {% set image = block.image.first() %}

            {% if image %}

            {% endif %}

        {% set image = block.image.first() %}

            {% if image %}

            {% endif %}
 {% endfor %}


texts: Allow user to mark entry as favorite, starred, or saved for later

texts: We're building a site with a recipes catalog and we'd like to allow logged in users to "star" an entry/recipe and then be able to view a list of their "starred" or "favorited" entries. Any suggestions on how to go about this?


texts: Searching multiple queries using CraftCMS search function

texts:
As you can see in the code below I'm currently searching for the keyword but how can I make it so it picks up on entries that have a matching keyword, location & salary or if they don't fill out one of the fields then just search using the remaining fields.

{% set keywordQuery = craft.request.getParam('keyword') %}
{% set locationQuery = craft.request.getParam('location') %}
{% set salaryQuery = craft.categories.getParam('salary') %}

{% set entries = craft.entries.search(keywordQuery).order('score') %}

<form action="{{ url('jobs/list') }}" class="submit-this">

             <input type="text" name="keyword" placeholder="Keyword">

             <input type="text" name="location" placeholder="Town, City, Postcode">

              <select name="salary">
                   {% for category in craft.categories.group('salary') %}
                         <option value="{{ category.slug }}">{{ category.title }}</option>
                   {% endfor %}
              </select>

              <input type="submit" name="search" value="Search" class="form-submit">

</form>

{% for entry in entries %}

                {{ entry.title }}

            {{ entry.jobsExcerpt }}

                    {% for block in entry.location %}

                                {% for category in block.category.limit(1) %}
                                    {{ category.title }}
                                {% endfor %}

                    {% endfor %}
                    {% for block in entry.salary %}

                                {% for category in block.category.limit(1) %}
                                    {{ category.title }}
                                {% endfor %}

                    {% endfor %}
                    {% for block in entry.keyword %}

                                {% for category in block.category.limit(1) %}
                                    {{ category.title }}
                                {% endfor %}

                    {% endfor %}

                Apply

{% endfor %}

I just can't seem to figure it out, any help would be much appreciated.

Thanks.


texts:
Would it be possible to have a cleaner site setup without all those 'locale' subfolders in the webroot? Somehow it looks like there's something similar already done here (https://github.com/craftcms/cms/tree/master-v2/src/services/HttpRequestService.php#L99) if I'm not wrong, wouldn't it be nicer to also just remove the locale if one is detected?

Bonus question :) :
Where in the hell is the actual Entry Slug -> Template resolving done? I know there's a lot of stuff happening with filters, action and resource requests. The closest I could get is that here the template/render controller gets triggered (https://github.com/craftcms/cms/tree/master-v2/src/framework/web/CWebApplication.php#L274) which in the end resolves to the action render method in the TemplatesController (https://github.com/craftcms/cms/tree/master-v2/src/controllers/TemplatesController.php#L50), already with the correct $template parameter set.

Could someone guide me in a direction here?


texts: How do you set a user's group on a registration form?

texts:
In a registration form with public signup possible, how do you set the user group for a particular form?

As a stop-gap I am attempting to use the following code:

function init()
{
    craft()->on('users.saveUser', function(Event $event)
    {
        $user = $event->params['user'];

        if( $user->leader == true )
        {
            craft()->userGroups->assignUserToGroups($user->id, array(2));
        }
    });
}

I created a field (lightswitch) called leader to enable me to check the value after saving the user and adding them to the group. The above code is not working though.

Using var_dump($user->leader) I can see the true and false being returned on user, and also the $user->id is returning the user's id, but the group (2) is not being assigned. Think I am missing something obvious. Thanks.


texts: Database: Syncing "craft_fields" table through SQL dumps not possible?

texts:
I've been trying to simply sync an addition to a matrix field building block from my local dev server to the live environment database by doing a SQL dump of the "craft_fields" table. I now have the same entry appearing in the remote database, however in the CP fields setup the additional field is not showing up in that particular matrix field.

What am I doing wrong? Or in other words: How can I optimize the workflow without having to do everything twice, in each CP (dev/live), for each field added later in the project's process?

Manually adding fields in both CPs is very prone to errors …


texts:
I just had some problems with an update exhausting my memory. But I already had the PHP memory limit at 512 MB, and I had to take it up to 1024 MB! I know this is relative but, is this too much?

How can I know if this is within normal range or if I should be working to improve it?

This is the site for a newspaper in a small province (~10 posts/day). After the latest update, the database is at ~600mb.


texts:
I'm trying to get all the entries which have tags associated with them.

At the moment I'm doing:

$entries = Entry::find()->with('tags')->all();

and then filtering the results in PHP as follows:

$filteredEntries = array_filter($entries, function($entry) {
    return count($entry['tags']) > 0;
});

This works fine, but I am still fetching all the entries, even without tags from the DB - I think this can be more efficient if I can specify in my query that I only want the entries with tags associated to them. How can I do this?


texts: Related to entries in categories in a plugin

texts:
Ok I can do this in twig but after searching high and low I can't find a good example of how to do it in a plugin.

I have a user profile field called interests which holds an array of what they are interested in. I want to pull out all entries that are related to the category id's held in the interests array. So in twig I do this:

{% for interest in userinterests %}
    {% for entry in entries.relatedTo(craft.categories(interest)) %}

{{ entry.title }}

    {% endfor %}
{% endfor %}

In my plugin function I currently have this but it is not returning anything in the array so I'm currently stuck:

$userinterests = craft()->users->getUserById($userid)->getContent()->getAttributes();
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->relatedTo = array(
    'sourceElement' => $categories
);
$relatedEntries = craft()->elements->findElements($criteria);

I'm not sure what I am supposed to be adding to the relatedTo array but it also could be something else as I'm still trying to get my head around craft.

Any help much appreciated.


texts: Is there a way to remove the admin panel logout timer?

texts: Having to log in again every few minutes while on a local development environment significantly slows your workflow.


texts: I'm wondering how I can dynamically generate a JPG fallback image from an SVG. Can image transforms be modified to handle this?


texts: Set the application name for Craft in New Relic

texts:
Like many of you, we've started to use New Relic to deep dive into performance of our websites.

Right now, we have a client's production server that has a version of Craft, ExpressionEngine and Wordpress.

Right now WP and Craft get lumped together as a 'PHP application'. Is there any config setting to allow us to set 'Craft CMS' as a thing to differentiate?

We've been able to do this with EE.


texts:
I am trying to use the FeedMe plugin to append data to existing entries.

My existing entries have a field that is a unique ID.  It is named Line Id.   They also have a blank field named Program Justification.

The .csv file I am importing has only 2 fields Line Id and Program Justification.   They should sync with the existing entries.  But, FeedMe keeps throwing an error

*justAPAF Justification: Unable to match an existing element. Have you set a unique identifier for ["lineId"] and does this have a value? - Element.php:104*

I do not know what I am doing wrong.  I use Line Id as a unique identifier in multiple database, data parsing and data visualization tools with no issues.

I am sure this is a simple 30 second explanation - but it has stopped me cold in my tracks for 5 days now.

Thanks


texts: Routing templates thats start with an underscore

texts:
More of a question than problem; I see this often - templates that start with an underscore. For example, _entry.html.

Reading the Craft docs:

  Note that if any of the URI segments begin with an underscore ('_'), Craft will return a 404, since template path segments that begin with an underscore are considered "hidden" from direct access

I guess I'm confused as to what I am hiding from. Is it so I can't directly browse right to the full path of that template?

mysite.com/something/something/_template.html

If you move the craft folder outside of the site root, I can't really get to that file can I? It just isn't obvious to me (yet) what the benefit is and when/where/why I need to start a template with and underscore.

Thank you!


texts:
I wanted to include some uploaded assets (images) in an entry. The .url property in twig outputs the proper URL, in my case:

  http://localhost/craftcms/web/image/photo-2017-04-02-16-20-53-1.jpg

However, that link is broken. Following it leads to a 404 error page:

  Template not found: image/photo-2017-04-02-16-20-53-1.jpg

Viewing it in the admin panel preview also displays a broken image sign.

If I disable the Public URL switch in the asset settings, the image display fine in the admin panel, but obviously I cannot use them in public pages.

I wasn't able to find a working fix for this. I tried the multiple-environment config solution from these forums just in case, but it did not help me.

Update: here is a screenshot of my Assets volume settings:


texts: Is it possible to translate the name of a field in the CP?

texts:
I have content editors that speaks different languages. Is there a way to translate the name and introduction of a field in the control panel? A simple {{ "value"|t }} seams not to work.

Example: English content editors should see "surname" as field name and german speaking editors should see "Nachname".


texts:
I am trying to run craft inside a homestead box. The box boots and installs everything correctly, and when I navigate to http://localhost:8000/admin I see the install screen and can click through the prompts. However, after clicking through the final screen I always get "Install failed  Please check your logs for more info.".

Here are the details for my setup:

Host OS: Windows 10 1809
Vagrant version: 2.2.4
Virtualbox version: 6.0.8
Homestead version: 8.5.5 (vagrant box 8.0.0-alpha2)
Guest OS: Ubuntu 18.04.2
Guest PHP version: 7.3.5-1

phperrors.log has this to say:

[03-Jun-2019 19:56:07 UTC] PHP Fatal error:  Uncaught yii\base\ErrorException: unlink(/home/vagrant/code/storage/runtime/mutex/a78d6a4ecc5877cd5617ca990a2be38b.lock): Text file busy in /home/vagrant/code/vendor/yiisoft/yii2/mutex/FileMutex.php:161
Stack trace:
#0 /home/vagrant/code/vendor/yiisoft/yii2/mutex/FileMutex.php(161): ::unlink()
#1 /home/vagrant/code/vendor/yiisoft/yii2/mutex/Mutex.php(88): yii\mutex\FileMutex->releaseLock()
#2 /home/vagrant/code/vendor/yiisoft/yii2/mutex/Mutex.php(57): yii\mutex\FileMutex->release()
#3 {main}
  thrown in /home/vagrant/code/vendor/yiisoft/yii2/mutex/FileMutex.php on line 161

I've googled this error message but didn't find anyone with the same problem. The referenced line of code (FileMutex.php:161) offers the clue that it may be an issue with operating systems (a different file unlock/delete procedure is used on windows).

In the vagrant box, the permissions on that file are wide open and I can delete the file with no problem.

vagrant@craftycoffee:/vagrant/storage/runtime/mutex$ ls -al
total 8
drwxrwxrwx 1 vagrant vagrant 4096 Jun  3 02:39 .
drwxrwxrwx 1 vagrant vagrant 4096 Jun  3 02:35 ..
-rwxrwxrwx 1 vagrant vagrant    0 Jun  3 02:35 4f99fda3d17d57459c4105d023bcba69.lock
-rwxrwxrwx 1 vagrant vagrant    0 Jun  3 02:35 52fa75c9044f6df80d2103fad929036e.lock
-rwxrwxrwx 1 vagrant vagrant    0 Jun  3 19:56 a78d6a4ecc5877cd5617ca990a2be38b.lock
vagrant@craftycoffee:/vagrant/storage/runtime/mutex$ rm a78d6a4ecc5877cd5617ca990a2be38b.lock
vagrant@craftycoffee:/vagrant/storage/runtime/mutex$ ls
4f99fda3d17d57459c4105d023bcba69.lock  52fa75c9044f6df80d2103fad929036e.lock

My best guess is that there is some weird interaction between windows and ubuntu when vagrant mounts that folder. However, I use vagrant for several other projects (all with windows host and linux guest) and have never seen any problems like this. I'm a complete noob with homestead/craft/php so I'm not really sure where to go from here; Any guidance on troubleshooting is appreciated. If there is any more info I can provide please let me know.

EDIT: I tried using SMB to do the file mounting (I believe NFS is the default?) and it worked. However, this isn't an optimal solution because I have to put in my username and password every time I boot the box.


texts: How to change the locals name in Localized Sites

texts:
I am developing multi-sites with the locals. Everything is fine. Is it possible to change the name of locals. I 'd like to give some other names to locals so that those can be more clear while managing the contents.

Please guide me for it.


texts: craft()->urlManager->setRouteVariables() loads the correct template but does not pass in the variables

texts:
everybody!

setRouteVariables() doesn't appear to be working for me.  If I boil my controller function down to just this:

public function actionSubmitForm() {
    craft()->urlManager->setRouteVariables([
        'foo' => 'bar'
    ]);
}

and my <form method="post" action="" accept-charset="UTF-8"> contains the following (among other inputs):

<input type="hidden" name="action" value="directoryForms/submitForm">

it hits the correct endpoint and then reloads the appropriate template, but it doesn't give me access to the {{ foo }} variable in that template.  It just tells me Variable "foo" does not exist.  I know it's hitting the right controller endpoint because if I die() there it dies as expected.

Any thoughts?  I've really boiled this one down as far as I can.  I must be missing something obvious.  Thanks!


texts: Performance and cache when using entry type templates and getSegment

texts:
I'm working on a site that will end up having 30-40+ structure sections which are sharing templates and will be using about 10 different entry types.

(This would probably be much easier if I used categories instead of this many sections, but I need different user privileges for each 'project' and it seems there's no simple way to restrict users to editing specific categories. Creating a plugin is beyond my skills at the moment, so I have to make do with what I have...)

At the moment I'm using URL segments with getSegment to figure out which section is requested and I'm following this advice from the Craft help site to assign templates to entry types and I'm wondering if this practice has any effect on performance.

Basically it goes like this:

First I need to figure out which section I'm in based on the URL so I can fetch the correct entries. The beginning of my index.php looks like this:

{# Figure out which project/entry type is requested: #}

{% set projectSegment = craft.request.getSegment(1) %}
{% set entryType = craft.request.getSegment(2) %}

{% switch projectSegment %}
  {% case "myproject1" %}
    {% set projectSection = 'myProject1' %}
    {% set projectName = 'My Project 1' %} {# To be used later in templates #}
  {% case "myproject2" %}
    {% set projectSection = 'myProject2' %}
    {% set projectName = 'My Project 2' %}
  ...
{% endswitch %}

{# Fetch entries in the correct section using these variables: #}

{% set typePath = craft.entries.section(projectSection).type(entryType) %}

So now in my templates I can use this:

<h1>{{ projectName }}</h1>

{% for entry in typePath %}
  ...
{% endfor}

Then I have to assign each entry type to its own templates, so in the CP I'm pointing each section to a single entry.html template which looks like this:

{% block content %}
  {% include "_projects/entry-types/" ~ entry.type %}
{% endblock %}

and in some cases I'm using even more conditionals in a particular entry type template to point to other templates:

{% switch entryType %}

  {% case 'entryType1' %}
    {% include '_project/entry-types/entryType1-listing' %}

  {% case 'entryType2' %}
    {% include '_project/entry-types/entryType2-listing' %}

{% endswitch %}

So here's my question:

Will the use of this many structures/entry types and the use of getSegment variables affect performance in any way, and will cache still perform efficiently?

From what I figured out, the {% cache %} tag should be placed inside the {% block %} tag, but since everything is 'dynamic' inside the {% block %} tag and changes based on the URL, I don't know if the cache will work the same way for all sections and entry types.

To complicate things even further, this will end up being multilingual as well, and I'm concerned this will put a lot of strain on the server.

Thanks in advance, any clarification is much appreciated.


texts: How can I add a favicon to the admin part of Craft?

texts:
I've successfully added a favicon to the site template through the _layout.html template. So the question is, how do I add the favicon code to the admin/backend of the website?

Thank you.


texts:
I am looking for the best way of installing a fresh craft 3 project and making it a git repo.

I tried the following:

Option 1:

first creating an empty new git repo
clone the empty repo to my pc using sourcetree
try and install craft through commandline in that folder

The issue is that craft says the folder isn't empty (which is true because there is a hidden git file inside of the folder of course) and I want craft to be installed in the root of that folder and not in a subfolder.

Option 2:

I installed a local craft project using command line with success
then I created a remote repo
then used git commands (https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/) to push the project to the remote repo
If I then clone the repo to my pc I can't get craft to work, I adjusted the env file and ran composer

I have been messing around so long just to get the craft project up and running in combination with a repo that I need help. I have managed this before but with a lot of detour so I am guessing there is a much better and faster way.

Can anyone explain what the best practices are for creating a craft project in a repo?


texts: RexEg Pattern to Exclude Using the Retour Plugin

texts:
The Retour plugin has this setting: Exclude Patterns - Regular expressions to match URLs that should be excluded from Retour.

How would I exclude images (jpg and png) from being handled by Retour? My statistics are full of 404s from old Asset transforms that I used before switching to the Imager plugin.

I tried adding this (which I found here: https://regexr.com/2ukfb): (http:\/\/[0-9a-zA-Z\.\/_-]+.png|http:\/\/[0-9a-zA-Z\.\/_-]+.jpg)

But that didn't seem to work. Images with a 404 were still logged in the Statistics section of Retour. Thanks in advance for any help.


texts: Nesting blocks - is the following problematic?

texts:
I lazily added the following to my parent site template:

{% block body %}
    {% block content %}
    {% endblock %}
{% endblock %}

Is this 'allowed' in Twig ?


texts: What's the difference between {{ siteUrl }} and url()?

texts:
Both of these things:

1.  {{ siteUrl }}path/to/template
2.  url('path/to/template')

... will generate this:

http://mywebsite.com/path/to/template

So I'm wondering, which method is preferred? Are there any pros/cons of either technique?


texts:
I’m trying to merge two query sources (some entries and some categories) but have them ordered by a shared field that is a date field. Here’s what I have so far:

set classesLocations = craft.entries.section('classes')|merge(craft.categories.group('locations'))`

I can group by the field of course, but not sure that helps me with ordering.

When I try to use .order('startTime') on the merged object I of course get an error, as they have already been automatically converted to an array to perform the merge rather than remaining as objects. And of course doing the order on both set of objects first doesn’t help, because the merge just tacks the merge on to the end.


texts: Is it possible to create this type of custom field?

texts:
We need a field that holds assigned postal codes. Each Location entry will have this field and I'd like to have the following:

Buttons to assign postals by city, state, county (data grabbed from table I have)
on button click, the postal codes will be added to the actual field

I'm not sure if this is possible with a field or if I have to do this on a separate CP page

EDIT: I'll be more descriptive

We would have 4 buttons and 4 selects. The first select (State) will auto choose the state that the Location entry has on another field.

The 3 other fields (city, state, zips) will populate based on the proceeding choices.

So if the state is PA, the other 3 selects will populate only counties, cities, and zips located in that state.

There are buttons underneath each to assign either all zips in a state, county, city, or a single zip.

When they press add, I'd like to add to a table with the columns

State, County, City, Zip

I'd also like to have an option to add/remove assigned zips simply from a CSV in a textarea.

it sounds quite complicated, but I've done this exact thing on other apps...just not inside craft.


texts: SQL Error - cannot add foreign key constraints

texts:
I'm uploading a site to a new environment and getting the following error:

The assetfiles table structure:


texts:
I'm a complete noob in the Craft world but love to give it a whirl for my latest project - just wondering if it can do what I want it to, and to maybe get some starting points from you guys in the know!

I'm building an Author agency website. In addition to their simple static info pages they will need to administer their 250+ clients (Authors,Public Speakers or both) and the 600+ Books by their clients. These will obviously need to be linked (through Entries as I understand it so far). i.e they want a single Author profile page (headshot, bio etc) which also displays a list that author's books, in turn linking to each book's profile page (synopsis, jacket, purchase link etc).

Now clearly I'll need either Client or Pro, as I imagine I will need to achieve this through Channels? Am I on the right track? Is there anything you think I'm missing (plugins?) Or maybe I pissing up the wrong tree?

Thanks in advance.


texts: Plugin init check if current page is dashboard

texts:
Is there an easy way to check if the current page is the Dashboard?
I have a widget that needs several Javascript resources but if I include them in the widget library I get a google maps error that I should not do that.
You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

I could make a workaround and set a static public variable to false after the first include but that would be kinda dirty.

So all I want to know id there is something like

function init()
{
    if (craft()->isDashBoard()) {
        //include all JS ressources
    }
}

or if there is a better way to include Javascript.


texts:
I now have 5 Structures that belong together (they are all different parts of our restaurant menu) together with my other structures its all very confusing. So what I want is a way to split up my
----Structures----

in the entries area to have like:

-----Singles------
  ..
-----Channels-----
  ..
----Structures----
  ..
-----FoodMenu-----
  ..
----Navigation----
  ..

Is there any way to achieve that ?


texts: Post to Sprout Forms plugin from an app or another website

texts:
Is it possible to post a form to Sprout Forms in Craft 2 from a desktop app or another website?

The AJAX example in the docs mentions this - sproutForms/entries/saveEntry
What would the full URL be?

I did try http://domainname.com/sproutForms/entries/saveEntry but it gives an 404 error.

Thank you for reading this.


texts: How to access Plugin Variable in Plugin?

texts: I want to access a variable created in Plugin itself. In Craft 2, it could be simply done by craft()->pluginName->getVar() but I couldn't find a way in Craft 3. I have tried Craft::$app->pluginName->getVar() but that throws an error.


texts: Deleted rows from elements_sites hunting stray slugs now I can't login

texts:
Working on a migration up/down testing I went through and deleted TOO much from the element_sites table to remove unwanted slugs, not understanding really what's in there. Now I understand many elements are in there and I've deleted some vital stuff without a backup.
Is there a way to perhaps use these config/*.yaml files to rebuild the tables or something to that affect?
At the very least, when logging in my username and password no longer works, and forgot your password gives no joy. What a mess. Can the project be salvaged or am I looking at starting fresh?
I have time machine backups on my mac but as a docker newbie I didn't have the VM included in the backup. I believe the mysql data is all stored in the VM that nitro creates.


texts:
First time working with matrix fields. In this case to load images. But somehow I can't manage to fetch the url of the Images. I can get the title and id but not the url. Can someone point me to the mistake am am making? Thanks!

{% set allProjects = craft.entries.section(['sectionHandle']) %}

    {% for projects in allProjects.all() %}

        {% for block in projects.matrixFieldHandle.all() %}

           {% if block.type == "image" %}

             {% set image = block.image.one() %}
             {% if image %}
              {{ image.url }}
             {% endif %}

           {% endif %}

       {% endfor %}

    {% endfor %}


texts:
Requests for non-existent templates/pages (404s) result in an uncaught HttpException.404 being thrown, though the correct 404 template is displayed. Is there some way to suppress or handle this exception? It's flooding my error reporting tool. For reference, here's the stack trace from the log:

2016/12/07 17:29:07 [error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in /project/craft/app/controllers/TemplatesController.php:59
Stack trace:
#0 [internal function]: Craft\TemplatesController->actionRender('page-no-existy', Array)
#1 /project/craft/app/framework/web/actions/CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#2 /project/craft/app/framework/web/actions/CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Object(ReflectionMethod), Array)
#3 /project/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#4 /project/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#5 /project/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#6 /project/craft/app/framework/web/CWebApplication.php(282): CController->run('render')
#7 /project/craft/app/framework/web/CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#8 /project/craft/app/etc/web/WebApp.php(290): CWebApplication->processRequest()
#9 /project/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#10 /project/craft/app/index.php(62): CApplication->run()
#11 /project/src/static/index.php(21): require_once('/project...')
#12 {main}
REQUEST_URI=/page-no-existy


texts: Using Element API to pull child categories

texts:
On Craft, I can assign categories to my different customers: a customer might be "Cloud", "Software" or "Energy". I have set it up so that you can also choose subcategories (children) ("Cloud subcat 1", "Cloud subcat 2", "Energy subcat 1").
Cloud
--- Cloud subcat 1
--- Cloud subcat 2
Software
Energy
--- Energy subcat 1

The customer entry can have multiple categories or subcategories selected, and choosing a parent category (ex Cloud) does not mean that it's children are necessarily selected.
I'm trying to pull this data using Element API. This is what I have set up:
        'transformer' => function(Entry $entry){
          foreach ($entry->customerType->level(1)->all() as $cat) { // to only pull parent-level categories
            $data[$cat->title] = [];
            $children = $cat->getChildren();
            if ($children) {
                $data[$cat->title]['category'] = [];
                foreach ($children as $child) {
                    $data[$cat->title]['category'][] = $child->title;
                }
            }
          }
    ...
    return [
    'searchableFields' => [
      'category' => (array) $data
]
    ]

When I pull the customer data on the front end though, any customer that has "Cloud" selected as the category also has "Cloud subcat 1" and "Cloud subcat 2" assigned as subcategories, even though those weren't selected in the admin. I would want that customer to just be [Cloud], not [Cloud: Cloud subcat 1, Cloud subcat 2].
Am I missing something in the PHP? Is this even possible?


texts: Craft 3 improvements to relationship querying?

texts:
I've been using Craft for a couple of years now and I do love it, however I consistently run into massive performance issues with it. I heavily rely on caching and eager loading - however this doesn't help when building filters that query against relationships (i.e. 'categories' and 'entries' fields) as the number of combinations of returned content is too high to think about caching.

Craft 3 has been made significantly faster than Craft 2 according to the website, however that's ideal conditions presumably loading entries with no fields on them - because even with Craft 2 I've never got close to the numbers quoted in real world applications.

Have any improvements been made to the performance and overhead of searching related fields and categories?

Some people have suggested using Algolia, but I've built a solution that's worked around the issue. I'd just rather not have to go to such extremes.

Thanks! (and thanks in advance for your time - presumably Brad :P).

An example of the type of scenario I'm referencing is below:

# Get element criterea for searching projects
$projectCriterea = craft()->elements->getCriteria(ElementType::Entry);
$projectCriterea->section = 'projects';
$projectCriterea->order = $orderBy;
$projectCriterea->limit = $limit;
$projectCriterea->offset = $offset;

... etc ...

# Project categories i.e. bridges
$relatedProjectTypes = [
    'targetElement' => $projectCategories,
    'field' => 'portfolioCategories',
];

# Location (New Zealand, Australia etc).
$relatedToLocations = [
    'targetElement' => $locationCategories,
    'field' => 'portfolioLocationCategories',
];

... etc ...

$projectCriterea->relatedTo = ['and', $relatedToLocations, $relatedProjectTypes];


texts: Install Failed - Numerous Errors when running with pgsql

texts:
Getting Numerous errors when trying to test a staging environment with Craft 3.1. States Install Failed - Check Logs which I have and I'm seeing the following logs being given. I don't understand what's causing this problem at all.

When the server starts, it presents me with the following error repeated many times:

data.db (postgresql[daemon]) ::  STATEMENT:  INSERT INTO "resourcepaths" ("path", "hash") VALUES ($1, $2)
data.db (postgresql[daemon]) ::  ERROR:  relation "resourcepaths" does not exist at character 13

Then when I head through the install window it presents me with the following error outputs in the link below (was too much to paste here)

https://paste.ee/p/lrFsi

db.php

<?php

 return [
     'driver'      => 'pgsql',
     'server'      => $_ENV['DATA_DB_HOST'],
     'user'        => $_ENV['DATA_DB_USER'],
     'password'    => $_ENV['DATA_DB_PASS'],
     'database'    => 'gonano',
     'schema'      => 'public',
     'tablePrefix' => '',
     'port'        => 5432
 ];

.env

# The database driver that will be used ('mysql' or 'pgsql')
DB_DRIVER="pgsql"

# The database server name or IP address (usually this is 'localhost' or '127.0.0.1')
DB_SERVER="localhost"

# The database username to connect with
DB_USER="root"

# The database password to connect with
DB_PASSWORD=""

# The name of the database to select
DB_DATABASE=""

# The database schema that will be used (PostgreSQL only)
DB_SCHEMA="public"

# The prefix that should be added to generated table names (only necessary if multiple things are sharing the same database)
DB_TABLE_PREFIX=""

# The port to connect to the database with. Will default to 5432 for PostgreSQL and 3306 for MySQL.
DB_PORT=""

Composer.json

{
  "require": {
    "craftcms/cms": "3.1.15",
    "craftcms/redactor": "2.3.2",
    "lukeyouell/craft-fetch": "1.2.0",
    "nystudio107/craft-seomatic": "3.1.44",
    "verbb/feed-me": "3.1.10",
    "verbb/feed-me-pro": "3.0.4",
    "vlucas/phpdotenv": "^2.4.0"
  },
  "autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },
  "config": {
    "sort-packages": true,
    "optimize-autoloader": true,
    "platform": {
      "php": "7.0"
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ]
  }
}

Project.yaml

https://paste.ee/p/VkgNe#F3NWs50GBWk0M1B7AgmQDuVphbDcwRau


texts: Frontend Form Search Users based on Tags

texts:
Context:
I'm trying to build a search form that will filter users based on Name, Skills and School. Users who have any of the search criteria should appear in my results.

Name Is a fuzzy keyword search of user.fullName

Skills Is a multiple select of tags, where any should match (if multiple are selected)

Schools Is a single select of a tag.

Problem 1:
When I search just by tags, leaving the Name field blanks, only the last tag is used to return results. So if two users were tagged with multiple tags, only the one relating to the last search term tag will be returned.

Problem 2:
It seems I can't combine the query so that I am searching not only by 'who has these tags', but also 'who's name partially matches this search' as well.

Thanks for any suggestions!

Code: Form

<form action="{{ url('search') }}">
    <input type="search" name="qName" placeholder="Name" value="{{craft.app.request.getParam('qName')}}">

    Skills
    <select multiple id="qSkills" name="qSkills[]">
        {% for item in craft.tags.group('profileSkills').all() %}
        <option value="{{ item.title }}">{{item.title}}</option>
        {% endfor %}
    </select>

    School
    <select id="qSchool" name="qSchool">
        <option value="">All</option>
        {% for item in craft.tags.group('schoolPrograms').all() %}
        <option value="{{ item.id }}">{{item.title}}</option>
        {% endfor %}
    </select>

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

Code: Results (on same page)

    {% set searchName = craft.app.request.getParam('qName') %}
    {% set searchSkills = craft.app.request.getParam('qSkills') %}
    {% set searchSchool = craft.app.request.getParam('qSchool') %}
    {% set queryParams = {} %}

    {% if searchName is defined and searchName is not empty %}
        {% set queryParams = queryParams|merge({
            search: {
                query:'fullName:*' ~ searchName ~'*',
            },
        }) %}
    {% endif %}

    {% if searchSkills is defined and searchSkills is not empty %}
        {% set skillList = "" %}
        {% for skill in searchSkills %}
            {% set skillList = skillList ~ 'profileSkills:' ~  skill ~ " OR " %}
        {% endfor %}
        {% set queryParams = queryParams|merge({
            search: {
                query:  skillList,
            },
        }) %}

    {% endif %}

    {% if searchSchool is defined and searchSchool is not empty %}
        {% set queryParams = queryParams|merge({
            search: {
                query: 'profileSchoolProgram:' ~ searchSchool,
            },
        }) %}
    {% endif %}

    {% set entries = craft.users(queryParams).group('members')
        .orderBy('score')
        .all()
    %}

    {% if entries|length %}

{{ entries|length }} results:

            {% for entry in entries %}

{{ entry.fullName }}

            {% endfor %}

    {% else %}

Your search didn’t return any results.

    {% endif %}


texts:
For example have the following code:

<form action="">
       <select>
               <option>2015</option>
               <option>2014</option>
               <option>2013</option>
               <option>2012</option>
      </select>

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

how to get a entries of the selected year?


texts: Not all assets copied over when copying an entry from admin panel

texts:
I have a site with multiple locales.  I have some entries that will have some basic fields such as title, description, etc and also an asset field.  The asset field is translatable so I could have an English PDF and a French PDF for the entry.  We often copy over entries and I have noticed when we do it will copy over the English asset but not the French asset.  Often times some admins are not aware they have to go back and re-add the French asset which is causing issues.

I am wondering if this is by design, a bug or ideally is there any setting or workaround I could do to fix the issue.

I am doing this in the admin panel when editing an entry and clicking on the arrow on save and selecting save as new entry.

Thanks


texts:
I'm trying to call an action from my main class in Craft 3. This is working fine with my services like this:

AbandonedCart::$plugin->serviceExample->serviceMethod();

I've tried to do something similar for my action but it doesn't work and I can't find any solution to it.

AbandonedCart::$plugin->actionExample->actionFunction();

Any ideas on how to do this?

Thanks in advance,
Sam


texts: How do I create a list of categories and display the entries relating to each of these categories that have at least one entry?

texts:
Here's a summary of what I try to do:

I created a Single page with a specific template where I want to display a list of partners
I created a group of Categories to define all types of partners
All my partners are encoded in a 'partners' Channel
In this Channel, each partner has a field that allows to select one partner Category
On the Single page, I display all categories of partners with at least one partner
For each Category of partners, I display the partner(s) related to this Category

And here is my code which attempt to do this, but not correctly:

{% set entryIds = craft.entries.section('partners').ids() %}
  {% set categories = craft.categories.relatedTo({ sourceElement: entryIds }).groupId(2).find() %}
    {% for category in categories %}

{{ category.title }}

        {% set categoryToDisplay = category.slug %}
        {% for entry in craft.entries.section('partners') %}

          {% for category in craft.categories(categoryToDisplay) %}

{{ entry.title }}

          {% endfor %}

        {% endfor %}

    {% endfor %}

This properly displays all Partners categories with at least one partner, but this does not correctly display the partners associated with each category. Each time, all partners of all categories are repeated instead of displaying only those that are related.


texts: Redactor II issue - adding completely random linebreaks to pasted text

texts:
(This is not a duplicate of Redactor II Craft 2.5 Prevent Paragraphs)

I am trying to paste in text from LibreOffice and the text ends up in Redactor II with, as far as I can tell, completely random linebreaks. It is not limited to a single document, but happens with any .odt or .doc I attempt to use. It's adding multiple linebreaks within a single paragraph, sometimes after every word - and they are getting added as [br]s to the HTML source, so it's not just some sort of visual artifact.

My client is, as you might imagine, furious with the new behavior. Has anyone else seen anything like this? Is there a fix? In the meantime I am using the "Redactor I" plugin by P&T, but that's not sustainable.


texts: Sprout Forms - include hidden fields in notification emails

texts:
I need to include the contents of a hidden field in my form's notification emails. I know the field value is being captured, as I can see it in the CP, but it's not included in the emails.

I thought maybe I needed to create custom template, but the path to the default Sprout Email templates in the docs is no longer accurate.

I'm using Sprout Forms 3.0.0-beta.44 and Craft 3.1.14


texts:
I have a Craft 2 installation that I'm upgrading to Craft 3.

I've got v3 running locally in its own virtual host, but now I need to temporarily put the dev v3 instance in the same hosting account as the live v2, with the v3 instance resolving at a dev subdomain:

account root
    craft              <-- v2 system
    craft              <-- v3 executable
    config … templates <-- other v3 dependencies
    public_html        <-- live web root
    dev                <-- dev web root

Given the naming conflict between the v2 system folder and the v3 executable, can I exclude the v3 executable and have v3 still run?

Or can I put all the v3 stuff in its own folder still above web root and then tell the dev index.php where to find it? It's not clear to me from the doc on customising directory structure that I can do that.

I know there is a doc on moving Craft files but that focuses on moving into web root (in my case, dev web root), which I don't want to do.


texts:
I'm trying to list some entries from specific channel and get the access to matrix fields. The problem is that some of the entries are listed twice or even often. How do I remove the duplicates?

    {% for coupon in craft.entries.section('coupons').status('live').order('postDate asc') %}
        {% for content in coupon.contentBuilder %}
        {% endfor %}
    {% endfor %}


texts: Can Craft Commerce receive back the address used in paypal express checkout?

texts:
When I checkout via Paypal express if I don't already have an address added to the cart model, when the paypal checkout process returns back there will be no address attached to the order.

The reason I want the address to be sent back afterwards is that i want to send customers to paypal from the cart page so there is no address form prior to leaving to paypal. This flow is something possible on say, woocommerce.


texts: Close entry editing after set time (for certain a user group)

texts:
I have a group of users who are allowed to create entries and edit them but I want to put a window on how much time they have in which they can edit it. For example, after initial submission they would only have two weeks to edit the entry before only an admin can make changes to that entry.

I understand how to run the logic to check the user groups and calculate cut-off dates but I have no idea where I need to hook in to be able to do this.

Is there anywhere I can hook in to run this logic? If so, where is this?

Any guidance would be really appreciated!


texts:
I have a {{ siteURL }} tag inside a matrix plain text field. But it does only render as a tag and isn't beeing converted to the actual url.

Accoring to this post one way is to use reference tags.

So I write inside the matrix plain text field: { globalset:siteUrl } and in the template I write:

{% for block in siteDropdown.matrixDropdown %}

     {{ block.cellLinkTitle }}

{% endfor %}

But this does nothing but print the tag itself. What am I missing?


texts:
I'm trying to build a feed of entries in a column grid. Something like that:

 First entry
 Fourth entry

 Second entry
 Fifth entry

 Third entry
 Sixth entry

How do I achieve that? In my head .batch(3) only works horizontally for rows.

Edit: To make it more clearly, that's my goal and the reason for columns instead of rows:


texts: So I'm new to PHP and ok with Javascript. I have a page on my site with a long list of external links, would it be possible to add a counter to be displayed next to each link that shows how many times it has been clicked?


texts: Video embed displays HTML code instead of video

texts:
We're using Dukt Videos to display a video on this page of our website. However, the video no longer appears on the page and just shows the HTML for the iframe.

Any idea what has happened?


texts:
I'm trying to get a dev environment set up and have got stuck.

I use Linux in the office and Windows at home. I simply wanted a basic LAMP stack to run craft on so I could develop locally. Given the two OSs, I figured I'd use Xampp.

I've installed Xampp on my Linux Mint PC. localhost seems to take me to htdocs, which I understand is normal? I've put Craft in htdocs, and then created a folder called public and put the index.php etc. in there.

So we have:

htdocs
 - craft
 - public
   - index.php

However, when I then do localhost/public/admin, I get
Could not find your craft/ folder. Please ensure that $craftPath is set correctly in /opt/lampp/htdocs/public/index.php

My craft path is set to ../craft (i.e. the default)

I've had a google, and there do seem to be similar questions, but mostly on Windows.

Should I move everything up a level? Or am I doing something else wrong?


texts: Craft Commerce: Filter completed orders based on a product category field

texts:
I know how to filter entries or products based on a category field with .relatedTo, but how can I filter completed orders based on a product category field?
In this specific case, I have an overview of completed orders. I would like to select a category and show only those orders that contain products with the selected category.
Any hints in the right direction are greatly appreciated!


texts: I encountered a problem which is very similar to this post. I've been using the letter "p" as part of a search string so www.website.com/test?p=querystring. It worked for more 6 months and now all of a sudden it doesn't work. Thanks to the other post I looked in my .htaccess file and see this rewrite rule: RewriteRule (.+) index.php?p=$1 [QSA,L] which was there by default when I installed Craft. I changed my query string parameter to "q" and now it works again. Not sure if something changed when I updated to the latest Craft version which at the time was version 2.6.2945, or if it's something else.


texts: Not All Entries showing in feed page but do show in Page Source XML

texts:
Creating an RSS feed in craft and I have it to loop through all the entries via:

    {% set sermons = craft.entries.section('sermonEntry').limit(null).find() %}
    {% for sermon in sermons %}

On my feed url (example.com/feed) I can only see 17 of my entries. However when I view the page source. I see all of my entries in XML format (roughly 31 entries)

Anyone have an idea why this may be? Or if it will affect my podcasts that go to itunes?

I am not sure if there is a limitation on atom or rss with craft but I have seen 100's of entries on a rss feed page so maybe I am overlooking something?

Any help is appreciated. Thanks!


texts: "Craft CMS does not support backtracking to this version. Please upload Craft CMS 0 or later."

texts:
I have a problem related this and this question. I began updating a long time ago (2017?) and got the error "Craft CMS does not support backtracking to this version. Please upload Craft CMS 0 or later" when I try to access the site or admin. I'm just now trying to fix it. I have tried replacing the app folder with a clean craft 2 version and I'm getting a blank white screen on everything.

I run a local install and a live install from the same DB.

What else can I try?


texts: How to override UserController.actionLogin or the login form template in Craft 3?

texts:
Hi I'm trying to build a custom authentication plugin for an organization, and I'm having a hard time figuring out how to override the craft\controllers\UserController.actionLogin method. I tried hooking into AuthenticateUserEvent however this is fired after craft has already checked to see if a user exists. For our purposes we want to skip that entirely and solely use ldap to authenticate users. Here's ideally what I need to do.

Check if the user with the given creds exists in ldap.
If so, and they don't exist in craft, create a new user with those same creds.
Forward the creds of the new or existing user to craft\controllers\UserController.actionLogin to finish logging them in to the admin panel.

Essentially I need to override that controller action and I can't find in the docs how to go about doing that. It also doesn't seem possible to override the login form template either? I realize if I could override that template then I can just call my own controller action.

Thanks for any help you can give!


texts: How to filter entries by slug in url segment?

texts:
I want to return entries in the news section, except the one that has a slug the matches url segment 2.

I've tried:

{% for entry in craft.entries.section('news').slug(not craft.request.getSegment(2)).limit(6) %}...
{% for entry in craft.entries.section('news').slug('and, not craft.request.getSegment(2)').limit(6) %}...

But neither work - all entries are returned.

What's the right syntax please?


texts:
I've been tasked with recreating an API within our Craft 2.X installation. For whatever reason, the API specifies the resource it is requesting with the query string parameter action. For example, instead of baseurl.com/api/users, they have it set up as baseurl.com/api?action=users

I thought I'd be okay if I used the ElementAPI plugin, set up an endpoint, and parsed the query string to figure out which set of elements to return as JSON. But it turns out that action is a very special query string parameter to Craft. When it receives a request containing action, Craft goes looking for a controller that will match it. I believe that Craft uses this pattern to handle a lot of basic business logic for the CMS. This seems like a very difficult branch of code to subvert -- this check fires before just about everything else.

Things I've tried, without luck:

Changing the action trigger in the config file, in hopes of removing the magic from "action".
Setting up a route in routes.php that goes directly to a plugin. Didn't work because UrlManager only fires after processActionRequest, which is the source of the error.
Asking the people who maintain the API to change the endpoints they're looking for.

Assuming that I'm required to use "action" as a key in my query string, how can I accomplish that in Craft 2?

Thanks in advance for any advice.


texts:
I'm attempting to upgrade my Craftsite from 2 to 3, which I have done so, however I seem to be getting a few deprecation errors.

The first error is:

  The auto-generated validation key stored at
  /Users/User/My-Site/craft/storage/runtime/validation.key has been
  deprecated. Copy its value to the “securityKey” config setting in
  config/general.php.

To which I assumed I should just add 'securityKey' => 'xxxxxx', but the error hasn't gone.

The second error is:

  The environmentVariables config setting has been renamed to aliases.

Which to be honest im not sure how to fix.

Any suggestions?


texts:
Is there a plugin/solution or something else in Craft so that I can basically:

1) Create a payment request in the CP and send it to a specified email?

2) The email contains a link to a payment form which the user can fill in and pay (amount would have been passed via email)

3) When paid the status would be updated in Craft CP

I have seen the 'Charge' plugin (https://transition.topshelfcraft.com/software/craft/charge) which looks great but it doesn't look like its up to date.

Many thanks
Malcolm


texts: How do I preserve user sessions across subdomains?

texts:
I have defaultCookieDomain set to .site.com
I am logged into www.site.com
I expected to also be logged into sub.site.com (which is pointing to the same web root), but I'm not.

What am I missing?


texts: Example of Craft 3.0 plugin - querying an existing table

texts:
Learning how to create plugins. I want to do a select query in an existing table in the Craft database, build navigation HTML and then return that HTML using a variable. I can see how to set up my own variable using the *Variable.php file. In the docs I don't see how querying database tables is done with any of the sections of the plugin found here.

I am guessing that I would use a class in the Craft classes?

If so then...

Do I put my logic for querying the table in my method to return the variable value, in my primary plugin class or somewhere else?

Which classes would I use?


texts:
Could anyone help me with this one? I have a custom plugin which needs to update a user's custom field with a particular value if they've filled out something on the registration form.

I believe the code below would work but it's running 44 times which is causing a nesting level error with xdebug.

Could anyone tell me why it would be running 44 times on a simple /users/saveUser post request with the below hook?

talentJobFamily and talentStage are both custom fields.

public function init()
{
    craft()->on('users.onSaveUser', function (Event $event)
    {
        $user = $event->params['user'];

        if ($user->talentJobFamily->value != '') {
            $user->getContent()->setAttributes([
                'talentStage' => 'engage',
            ]);

            craft()->users->saveUser($user);
        }
    });
}


texts: New user registration activation timeout?

texts:
Does the "Activate your account" link, in emails sent to new users, have an timeframe for expiration?  I've had a few of my users run into a "Invalid verification code" error when clicking on the link, after waiting a couple days. If I resend the email, and they click on it within a few hours there's no issue.

I've looked through the docs and posts here and don't see any reference to one.  If there is a default expiration, is this something I can override?

Thanks!


texts: Is there a way to control the order of appearance of shipping methods in Craft Commerce?

texts:
If there are multiple shipping methods available for an order, is there way to control the order in which they appear?
The CP doesn't seem to offer a way to re-order them. I'm using something like the following code to retrieve all available methods.
{% for handle, method in cart.availableShippingMethods %}
<input type="radio" id="{{ handle }}" name="shippingMethodHandle" value="{{ handle }}" />
{{ method.name }}

{% endfor %}

Craft Pro (3.4.28.1) & Craft Commerce Pro (3.1.12)


texts: How do I get elements using getCriteria from a specific date?

texts:
I'm trying to get elements in a section created on a specific date. How do I do that?

This is what I've been trying with:

$criteria               = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section  = 'sectionHandle';
$criteria->postDate     = '2014-11-04';


texts: How to block direct access to templates (hiding templates)

texts:
How can I prevent people accessing templates directly that are only used as includes for instance?

I read that I could add an underscore ie _example.html,but then the include stops working.


texts: How do you programmatically update an asset index?

texts:
I am trying to update an asset index from a plugin but can't seem to get it to work.  Looking at the docs this seems to me like it should work but it does not. I am on the right path here?

$ses = craft()->assetIndexing->getIndexingSessionId();
craft()->assetIndexing->processIndexForSource($ses, null, 7);

7 is the id of the asset folder I want to re-index.