texts:
I'm currently building my first JAM stack app using Nuxt as my front-end framework and Craft as my headless CMS. I'm leveraging Apollo as my GraphQL interface client. I have it pulling data back just fine, but I want to shuffle the output to always be random. I know I could do this in a typical twig query with .orderBy('RAND()') but I need a way to shuffle that with my GraphQL endpoint.

I know I can do this on the frontend by shuffling my <li>s or something, but would love for this to be more performant if I can help it.

I've tried a few variations of the below but can't seem to get it to work. Is this possible?

apollo: {
  entries: {
    query: stories,
    prefetch: true,
    variables: {
       "section": ["stories"],
       "orderBy": "RAND()"
    }
  }
},


texts: Have Craft deliver single page despite having a directory of the same name in the public folder?

texts: I just switched my company's website to Craft, and I have a lot of already existing static webpages that I would rather not remake as templates and define routes for. I have a single page made in Craft at /events, but when I add the subdirectory events/event-name, going to /events presents a 403 error. I know why this is happening, because of the way Craft handles routing, but is there any way (possibly in my .htaccess file) for going to /events to deliver the single page like normal, despite having the subdirectory in my public folder? Thanks.


texts: Solspace Freeform query for submission assets returns all site assets

texts:
I'm attempting to query for all assets associated with a specific form submission like this, where 'submission' has been set based on a URL parameter:

{% for field in submission.fieldMetadata %}
    {% if field.type == "file" %}
        {% set assetId = attribute(submission, field.handle) %}
        {% set assets = craft.assets.id(assetId).all() %}
           {% for asset in assets %}
                {% if asset %}
                    {% if asset.kind == "image" %}
                        <img src='{{ asset.url }}'>
                    {% endif %}
                {% endif %}
            {% endfor %}
    {% endif %}
{% endfor %}

The above code returns all site assets rather than just the assets associated with the submission. All other fields associated with the submission are returned correctly. Is this a bug or is my template incorrect?


texts:
Learning Craft currently. Wondering if there's any plugin that simplifies the curation of the home page by allowing pinning a post, highlighting a post, reordering a post etc (non chronologically)

Here's a reference of a equivalent Wordpress plugin:
https://github.com/10up/curator

THanks


texts: Search syntax for searching matrix fields (in the CP)

texts:
Looking for a way to search (in the CP), for elements where a matrixField is empty or not.

This seems to work:
- with matrix rows: myMatrixField::*
- without matrix rows: -myMatrixField::*

However, this doesn't work in the event that you have fuzzy enabled by default: https://craftcms.com/support/enabling-fuzzy-search-by-default

Any other way to achieve this?


texts: How to update the lineItemStatus of an order on the front end with twig?

texts:
I'm building a simplified interface that is only going to be used by employees preparing the orders. They are in a usergroup that has the right permissions to update orders.
I'm building this because updating an 'order status' or 'line item status' from the controlpanel is too finicky to do from a smartphone or tablet.
I've found how to update an order status here and got that working nicely.
{% set order = craft.orders.id('123').one() %}
{% do order.setAttributes({'orderStatusId': 4}, false) %}
{% do craft.app.getElements().saveElement(order) %}

What I don't know how to do is how to update the lineItemStatus.
I'll probably have to fetch the order first then the lineItem id and then update the lineItemStatus attribute, but I have no idea how to even start.
Any help putting me in the right direction is greatly appreciated!
*I also know this would be better to do with a module or plugin, but alas, I don't write php.


texts: Best Method of Handling Repeated Content Within Existing Fields?

texts:
We are trying to find the best solution for handling repeated content within existing Fields in the CMS.

That is, there are bits of information which could be used nearly anywhere within existing fields in the CMS (e.g. inside a Plain Text field / Rich Text field etc) (things like the event booking link, booking deadline, event start date etc etc). The ideal solution would be that these bits of information are housed in one place in the CMS (probably will be a global), and can cleanly be pulled through to other areas of the CMS with a super user-friendly bit of syntax.

-

We've explored a few options, namely the following...

Reference Tags

As these are limited to Plain Text field types, these are not an option.

Globals

As per this SE question.

This would involve having to add include(template_from_string()) almost everywhere where a content is output from the CMS, which would be a pain and also the syntax might be a little confusing for the end user.

Create our own plugin

Whilst this might mean the syntax could be a bit more user friendly (e.g. something like [main-event-dates], we would still have to pass every field output to the plugin (i.e. craft.myPlugin.parseSyntax(entry.body)

Events

I'm just starting exploring Hooks and Events, and this looks like the best solution so far to me. From my understanding, the approach which would be most suitable for us would be something like this:

myPluginPlugin.php

function init() {
    craft()->on('elements.onPopulateElement', function(Event $event) {
        craft()->myPlugin_main->parseSyntax($event);
    });
}

myPlugin_MainService.php

function parseSyntax($event) {
    // Parse the content of the fields, using something like the following
    $event->params['element']->getContent();
}

Considerations with using the 'Events' method

We would need to build in a mechanism of programatically clearing all template caches when one of those bits of central information is changed (as Craft will not be aware of which templates need their cache clearing)
Is there a risk that this will be super php intensive to essentially loop though each field for each bit entry model / matrix block model etc etc?

-

Does anyone know of a better way to achieve what we are trying to achieve? Or feel strongly any way about any of the above?


texts: Is it possible to tell if a user was registered through the front end or CP?

texts:
I would like to be able to perform actions on those users that register through the front end and skip ones who are created in the CP... is there are way of checking or a parameter accessible in the onBeforeSaveUser or onSaveUser events?

I assume there must be something hidden in there as users registered on the front end can be assigned to a certain user group which isn't applied to a CP registration.


texts: Interacting with table fields via plugin

texts:
When you set up a table field column through the admin cp, you assign a name and a handle. When I var_dump the table field, all row data is referenced by column number. (e.g. col1, col5, col2, col3, col4)

    $partnerProducts = $currentPartner['0']->getContent()->productInfo;
    foreach ($partnerProducts as $pp){ echo ($pp['col2']); }

These columns may not be in order depending on how they were drag and dropped in the admin control panel, which is super confusing from the PHP plugin side. Is there any way to reference the table items by their cp handle?

You CAN do this from the twig side.

    {% for partnerProduct in partner.productInfo %}
        {{ partnerProduct.sku  }}
    {% endfor %}

I'm still not sure what the difference between $currentPartner['0']->getContent()->productInfo; and $currentPartner['0']->productInfo is but the latter works.


texts: Is there an easy way to reset user permissions back to usergroup settings?

texts:
Is it a matter of clearing the userpermissions_users table?

Background: After initial authoring, we've cleaned up permissions for our usergroups, but the existing users have accumulated manually-added permissions as sections got added.  Would be nice to be able to blanket-remove all the custom permissions.
(Also, "Deselect All" in the User Settings' Permissions tab is doing a select-all instead.)
Thanks.


texts: Migrating a whole website between Craft instances

texts:
A developer built our site locally configured as "craft.dev". At the same time, my sysadmin was busy getting Craft installed with Apache on our Linux server. He set that up with our real domain and purchased the $299 license for "ourcoolwebsite.com".

Now we've got the real website on the developer's machine, and a blank website on the linux server.

What files/folders do we need to migrate to get the real website up? Should we just dump and load his database and overwrite the one that was created for the install? I am guessing there are some database tables with data specific to my purchase and license key that differ from his. Basically I want to know how to take his work and put it into my production environment with database tables and file paths.


texts: Entry list field get duplicated entries from specific section

texts:
I have some weird behavior when I have an entry list field (in a super table, but I get the same behavior from the native entry list field type).
When I select an entry from a certain section, it will populate 2(!) entries in that list, which point to the same entry after save. It looks correct, after I selected the entry, but as soon as I save the entry which contain the list, it gets duplicated?
Before saving:

After Save:

It only affects a single, specific section, entries from any other section is fine.
Where to even start trouble-shooting?


texts:
How do comments work in Craft? I mean inline and multiline comments, like:

HTML: <!--xxx--> m
  JS:   /*xxx*/  m   //xxx i
 PHP:   /*xxx*/  m   //xxx i   #xxx i


texts: Commerce 2 Subscriptions (Using Stripe API)

texts:
I'm currently trying to implement and understand how Subscriptions work on Commerce 2. I'm using Stripe API and have created the subscriptions on their CP. I've listed them on my shop page and added the form that goes to "commerce/subscriptions/subscribe".

However, when i click on the submit button, the page is simply reloading itself without any error message. I've tried looking for any _POST response but not are found.

Can anyone tell me the correct flow please? I assume you:

List the subscriptions
Submit the subscription with the subscription id (to commerce/subscriptions/subscribe)
It checks for stored card details and if none found, presents the add card page
Submits those details and processes returning result

Is that correct?

Really appreciate any help.


texts: Do Remote Assets (ie. S3) have file paths?

texts:
New to remote assets, and can't seem to find any information on accessing remote assets via filepath in areas twig can't be used, such as CSS. I'd like to be able to use those same assets in CSS files but can't seem to find them.

For example, if I named my remote Amazon S3 Asset Source handle to 'amazon', and it has sub folders asset/images/template for an example, would there be a way to reach the files in a file path such as amazon/assets/images/template/filename.jpg for use in CSS and whatnot?

Any information would be greatly appreciated. Thanks!


texts: Plugin Development - Template Resources?

texts:
I'm in the middle of creating a plugin that needs a template to display information stored in some records when the user clicks this in the CMS sidebar.

I've managed to get the template to appear (Yay!) And I've been looking at other plugins with regards to styling / structure of these pages.

A lot of them are extending and using classes that appear within Craft.

Is there a reference to this anywhere? Such as a class / styleguide or any where I can find out a bit easier what blocks etc are used?

Thanks


texts: Crossdomain ajax request to controller with requireAjaxRequest()

texts:
I make request from my localhost(gulp server) to example domain in to VerifyPassword controller. When i make request without headers: {'X-Requested-With': 'XMLHttpRequest'}, It comes as expected 400 Bad request

$.ajax({
        url: 'http://example/index.php/actions/users/verifyPassword',
        type: 'POST',
        data: $data,
        xhrFields: {
            withCredentials: true
        },
        success(data, response) {
            console.log(data, response);
        },
        error(data, response) {
            console.log(response, data);
        }
});

When i make request with headers: {'X-Requested-With': 'XMLHttpRequest'} comes response XMLHttpRequest cannot load http://example/index.php/actions/users/verifyPassword. Response for preflight is invalid (redirect), and are not sent cookies. Done OPTIONS preflight request without cookies and server comes 302 and redirect to example/login.
How To be?

http://www.yiiframework.com/forum/index.php?/topic/4945-yiiapp-request-isajaxrequest/


texts: How to set a field of an asset from within a plugin

texts:
I am using the following code to save an asset that has been downloaded to the storage/runtime/temp directory from an external API

$response = craft()->assets->insertFileByLocalPath(
    $tempPath,
    $photo['FileName'],
    $folderId,
    AssetConflictResolution::Replace
);

// if the response is a success, get the file id
if ($response && $response->isSuccess()) {
    $fileIds[] = $response->getDataItem('fileId');
}

In this example $photo[] array is the response from the api with all photo information. What I need to do is also save $photo['PhotoId'] to a field I have setup on the photo asset source in Craft.

I can't however find an example of how to achieve this. Does anyone know how?


texts: Localhost: Why does {{ asset.url }} return {{siteUrl}}/path in the browser?

texts:
I'm very new at Craft templating, and I can't seem to get an asset to link correctly in the browser.

{% block content %}

{{ entry.title }}

        {{ siteUrl }}

Posted on {{ entry.postDate.format('F d, Y') }}

        {{ entry.blog_body }}
        {% for asset in entry.blog_featured_image %}

        {% endfor %}

{% endblock %}

Becomes this:

New Blog 1

  http://localhost/craftcms/public/

Posted on January 15, 2017

"Body Text"

when output to a browser.

{{ siteUrl }} will display the path just fine, but when I'm using {{asset.url}} and it gets changed to {{siteUrl}} it doesn't create the path, it just stays at siteUrl. This is really confusing me.

Why doesn't {{ siteUrl }} return the base path when it's used in the asset.url?


texts:
All of my products have a category field called stateCat. These state categories have a field called stateImportance. This is because some states are more important than others and I want to sort the products based on that stateImportance number. I have no idea how to do this.

This is what I've tried:

{% set products = craft.commerce.products.order('stateCat.stateImportance asc').type('coins').limit(null) %}

This doesn't seem to work, how can I accomplish this?


texts: Loop through entries with custom ordering, showing one from each category then start loop again

texts:
I have a channel with entries that may or may not have a custom date field populated.

I'd like the display a list of entries, looping through each category, showing one entry from each category. Then just start the loop again.

Then, show the rest of the entries which don't have the date field populated. I guess they would just have to be just ordered by postDate, but still only showing one per category each loop.

So (assuming there are 3 categories in total)...

Entry - 4th April - Category 1
Entry - 6th April - Category 2
Entry - 8th April - Category 3
Entry - 5th April - Category 1 - start the loop through categories again
Entry - 7th April - Category 2
Entry - 9th April - Category 3
Entry - Category 1
Entry - Category 2
Entry - Category 3

Note that the dates appear jumbled, as the categories are the thing dictating the order. Date order is a factor, but secondary to the looping of the categories.

This is the code I have so far, all it does is output the entries but with the ones without date fields populated appearing first.

{% for entry in craft.entries.section('heroes').order('date') %}

    {% if entry.date|length %}

{{ entry.title }} - {{ entry.date|date("j") }}{{ entry.date|date("S") }} {{ entry.date|date("F") }} {{ entry.date|date("Y")}} - {% for category in entry.genre %}{{ category.title }}{% endfor %}

    {% else %}

{{ entry.title }}

    {% endif %}

{% endfor %}

Hope that makes sense! Any help will be appreciated.


texts: Where should I make an HTTP REQUEST using AJAX?

texts: Where should I put my ajax call if I want to get some data from an external link or website? Should I put it in the controller, or in the service?


texts: Get entries filtered by author's category

texts:
I got a list of entries news (channel type).
They are created by users (or author).
These users have a category region assigned to them.

My point is to list the news entries that have the same author's category than the currentUser's category...

I am trying with relatedTo but I am stuck here:

{% if currentUser %}
    {% set userRegion = currentUser.region.first() %}
{% endif %}

{% set regionNews = craft.entries.section('news').relatedTo('and',
    { sourceElement: currentUser, field: 'unepRegion' },
    { targetElement: author, field: 'unepRegion' }
) %}

Really don't know where I am going with this.


texts: Can't list S3 buckets from Craft behind a firewall

texts:
We are using Craft2, and want to move the assets to Amazon AWS S3.
We have two instances of Craft2, one on AWS, and one on a onprem server.
The bucket is made (and is on eu-west-1) and the IAM user got the right permissions, and the secret and key is also right.
The instance on AWS works fine and no problem to list buckets from S3, but the onprem server, when pressing the "refresh" button on bucket the spinner just spins and then gets timed out and a 500 error.
The command is: index.php/admin/actions/assetSources/getS3Buckets
Since it worked on 1 instance and not the other, I think it might be a firewall issue. Which port and IP / URI need to be opened in the firewall for it to work ?


texts: Display a user's selected checkbox options for a category field type in a front-end Edit Profile form

texts:
I have a user field called "designOptions" that is a Categories Checkbox field type. I have this field in the Edit Profile front-end form so that the user can see the saved options that they had selected previously (if any) and then change or add to those selections in the Edit Profile form. I am having a hard time finding anything in the documentation or SE about how to display all of the user's category checkbox options while displaying the options that are already selected in their account for that field. This is what I have so far, but it is checking all category options instead of just the 4 that the user has selected - likely because the length conditional is only looking at whether this field has 'any' value and not checking the value of each option.

I would appreciate any guidance you can give on the best way to do this. :)

Thank you!

{# Grab all categories in the group and set variable. #}
{% set categories = craft.categories.group('designCategories') %}

{# Grab the categories that the user already selected #}
{% set userOptions = user.designOptions %}

{# Display all category checkboxes in the form, with the logged in user's saved selections already checked.#}
{% for category in categories %}
    <input type="checkbox" id="designOptions" name="fields[designsOptions][]" {% if userOptions | length %}checked{% endif %} value=" {{ category.id }}"> {{ category.title }}</input>
{% endfor %}


texts:
Does anything need to be done to allow for ajax submittions using the GuestEntries plugin?
https://github.com/pixelandtonic/GuestEntries

I'm following the method used here for Contact form, it submits fine and returns success but nothing shows up in the DB?

https://github.com/pixelandtonic/ContactForm#ajax-form-submissions

in chrome the request looks right?

Request URL: http://familiar.dev/
Request Method: POST
Request Payload:
{"action":"guestEntries/saveEntry","sectionId":"5","enabled":"1","redirect":"contact/thanks","title":"asdsa"}

any ideas?


texts: Invalidating Cloudfront Cache in Craft 3

texts:
We very recently migrated from Craft 2 to Craft 3 and I was wondering what was the easiest way to invalidate Cloudfront's cache?

I saw that Craft 3 has a panel for clearing cache in the Utilities menu, within the admin dashboard, but I didn't find any information about if it integrates with the AWS S3 plugin, or similar.

This is the panel I'm refering to:


texts: Interpret TWIG's {% js %} as  in PHPStorm

texts:
Does anyone know how to get PHPStorm interpret {% js %} as <script> for correct syntax highlighting in PHPStorm?
Background: I'am always doing this:
{% js at endBody %}
    {% if false %}<script>{% endif %}
    document.querySelector('body').classList.add('overlay');
    {% if false %}</script>{% endif %}
{% endjs %}

which I would like to avoid.


texts: templatecachequeries entries with of 157.000 characters in query column

texts:
after enableling querycaching in craft3 I found rows in templatecachequeries with big amount of characters in the query field. I decoded it with base64 and got this as the largest entry:

query_length: 157036

query_decoded:
O:28:"craft\elements\db\EntryQuery":71:{s:8:"editable";b:0;s:9:"sectionId";a:1:{i:0;s:1:"7";}s:6:"typeId";N;s:8:"authorId";N;s:13:"authorGroupId";N;s:8:"postDate";N;s:6:"before";N;s:5:"after";N;s:10:"expiryDate";N;s:17:"

query: TzoyODoiY3JhZnRcZWxlbWVudHNcZGJcRW...(+157.000)

my sql query:

select length(query) as query_length , FROM_BASE64(query) as query_decoded, query
from craft_templatecachequeries
order by query_length desc

why does the unencoded query with a size of 221 characters get encoded to a size of 157036 characters?


texts: Internal Server Error: SQLSTATE[42000] 1118 Row size too large

texts:
I have a very large entry type in craft with quite a few fields.  I've been updating a single record on a regular basis but upon adding a few more paragraphs of rich text in a field, I received this error when trying to save:

  Internal Server Error

  CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED may help. In current row format, BLOB prefix of 768 bytes is stored inline.

Is there some other solution beyond what the error is suggesting? Not sure what I'm missing. Any thoughts would be appreciated.

Thanks!

UPDATE 10/1

I was able to get the existing table in my Craft instance updated to the barracuda file format with row_format=DYNAMIC. Updated the global MySQL params as well:

+--------------------------+-----------+
| Variable_name            | Value     |
+--------------------------+-----------+
| innodb_file_format       | Barracuda |
| innodb_file_format_check | ON        |
| innodb_file_format_max   | Barracuda |
| innodb_file_per_table    | ON        |
+--------------------------+-----------+

The problem now is with new matrix fields: the newly created tables are not being set to the row_format=DYNAMIC. Is there somewhere in Craft where I need to update this? Or is there somewhere else I need to update this?


texts:
I am building an online store with craft commerce, but I have a problem, I need to update a remote stock on every purchase, this stock is located in a remote server, do you know if  exist a plugin that makes this task easier for me?
Maybe a plugin that sends a POST API on every purchase or something.


texts: How to render entries on a singles page in a specific pattern/order?

texts:
On my homepage I have one entry that is constantly there. Below that entry I want to display 2 different types of entries in an alternate order (gallery, update, gallery, update...).

Right now I have it so that I'm getting all the sections, setting it to a variable and looping through doing a entry.type check so it renders according to it's type. What would happen now is that it would display everything according to the posts' time.

Thoughts? Ideas?

Thanks.

my code

{# story #}
 {% for entry in craft.entries.section('stories').limit(1) %}

{{ entry.title }}

Posted on {{ entry.postDate.format('F d, Y') }}

        {{ entry.body.getPage(1) }}

Continue reading

{% endfor %}
{# end of story #}

{% set entry3 = craft.sections.getAllSections() %}

{% paginate craft.entries(entry3).limit(2) as entries %}
{% for entry in entries %}
{% if entry.type == 'carousels' %}

{{ entry.title }}

Posted on {{ entry.postDate.format('F d, Y') }}

                    {# {{ entry.body.getPage(1) }} #}

                    {% for block in entry.gallery.limit(3).find() %}
                    {% set asset = block.galleryImage.first() %}
                    {# {% set asset2 = block.galleryImage.nth(2) %} #}

                    {% endfor %}

Continue reading

{% elseif entry.type == 'updates' %}

{{ entry.title }}

Posted on {{ entry.postDate.format('F d, Y') }}

                    {{ entry.body.getPage(1) }}

Continue reading

{% endif %}

{% endfor %}
{% endpaginate %}


texts:
I can't find a way to include buttons on the correct place at the sidebar of my plugin.

So I noticed that on the sidebar markup, there's a div for buttons, there's created automatically:

I can easily add anything to the sidebar, I can include the buttons on the top, as you can see on the example, but my question is, how do I add the buttons to that div?

I couldn't find on the templates the correct place.

[EDIT]

Here's my template.

{% extends "_layouts/elementindex" %}
{% includeCssResource "crashC/css/crashC.css" %}

{% set title = "Entries" %}
{% set selectedTab = 'entries' %}
{% set elementType = "CrashC" %}
{% set docsUrl = '' %}

{% block sidebar %}
  Download CSV
  {{ parent() }}
{% endblock %}

Thanks a lot for the help!


texts: Okay so my question is simple. Is there a craft plugin that lets me add tables in my redactor fields? If not then is there a way I can add the table.js to the redactor plugin config. I add ti but it doesn't show up.


texts: Can I make the front-end entry form send an email to a user group?

texts:
I've used the front-end entry form in the docs to build a Q&A portal, and it's working great. But I'd like to extend the functionality once the new entry is saved.

I've set the entries up to not be enabled when saved so that a moderation team can later approve them. Is there a way for members of the moderator user group to receive an email every time someone publishes a new question via the front-end form?


texts: Craft Commerce Order Notifications from customer email and name

texts:
Quite a specific question from a client on another e-commerce system who would maybe like to move to Craft Commerce. I have used Craft for a few client sites now but not Commerce as of yet.

Basically, when a customer places an order he wants the FROM email address and FROM name to be that of the customer who has placed the order (in the confirmation/notification email/invoice that gets sent to him).  It's basically so that he can group all the emails easily in Outlook.

Bit of a specific question but wondered if anyone can shed any light?


texts: Columns on the Entry index page giving errors

texts:
For some reason whenever I add a custom column to a section's entry list I'm getting errors and no values.

If I add Entry Type to the column list, for example, it's saying:

Unknown class: Craft\EntryTypeModel

And links are saying:

Unknown class: Twig_Markup

I'm a little dumbfounded?  I tried removing and re-adding them and still no luck.  Any ideas?


texts:
How do I change this template code to only return results from the title field of an entry?

The search result page url would look like this: /search-results?q=joe+blogs

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.section('not thisSection').search(query).order('score') %}

Thanks for any help.


texts: How can I notify store owners when stock levels are getting low?

texts: For a Craft Commerce site, the store owners wish to be notified automatically when a stock is starting to get low. Can this be achieved with a plugin, and if so, how?


texts:
So doing some entries loading via ajax from this question which I expanded on.
https://craftcms.stackexchange.com/a/9868/3579

I'm curious about setting up a route for the actual ajax file since it seems a route is needed otherwise it doesn't work, and will 404. In my example you can see I am setting the ajax url as

$.get( "/resource-center-ajax/p"+page, function( data ) {//do stuff}

so I setup a route with the following.

URI resource-center-ajax

Template /resource-center/_resource-center-ajax

Actual Template file _resource-center-ajax.html

If I go to example.com/resource-center-ajax it will show the results from my ajax file which is just a plain page since I am not including the layout file in that template file.

Is there a way for me to prevent people from accessing this url directly and make it only used for the ajax request? Maybe check if its an ajax request if not redirect to the homepage or something?


texts:
I'm experimenting with migrating a large site from EE to Craft to take advantage of the performance improvements for an upcoming site redesign. I see there are some plugins that work well to import entries via XML or CSV, but I have been unable to find a way to import members.

Obviously, the passwords are stored in the database encrypted for the EE logins which makes it a little more tricky. Any thoughts? Thanks!


texts: Specify FolderId When Uploading a File on the Frontend

texts:
In a front-end form where I am uploading a file, I need to specify a specific subfolder. I can't do it in the cp dynamic field for reasons so I was hoping to use a hidden field to set the folderId. The folderId exists and each entry has a different folder. I have this code that works but I can't figure out the code, for example something like: folderId: 44
<form method="post">
 {{ csrfInput() }}
 {{ actionInput('entries/save-entry') }}
 {{ hiddenInput('sectionId', '3') }}
 {{ hiddenInput('enabled', '1') }}
 {{ hiddenInput('entryId', entry.id) }}
 {{ hiddenInput('redirect', craft.app.request.absoluteUrl|hash) }}

    {% for relatedAssetId in entry.patientFiles.ids() %}
      {{ input(
          'hidden',
          'fields[patientFiles][]',
          relatedAssetId,
        ) }}
    {% endfor %}
          {{ input('file', 'fields[patientFiles][]', options={
             multiple: true,
          }) }}
    <button class="btn btn-primary" type="submit">Upload</button>


texts: Using a matrix Date/Time field to sort entries

texts:
I'm trying to use Supersort to sort entries using a date/time field within a matrix, for example 1/6/2019 12:00AM. These dates will always be in the future. I want to sort it so that the entries that are closest to happening are displayed first.

To make it more complicated, entries with multiple dates in the matrix are split apart, so I need to sort each of these according to their date (from https://gocrowsnest.ca/events):

I can't figure out how exactly I'm supposed to do this. What I have:

{% set pageEntries = craft.entries.section('events') | supersort('sortAs', '{dates.type("date").first.startDate.getTimestamp}') %}
{% for event in pageEntries %}
    {% for block in event.dates.all() %}
        {# Event code #}
    {% endfor %}
{% endfor %}

This is sorting each entry by the first matrix date, not by each date.

Matrix handle: dates, block: date, field (date/time): startDate.


texts: How can I get cookies that were set in javascript from a twig template?

texts:
The docs state that {{ craft.request.getCookie(name) }} will not work for cookies that were set in JavaScript, because all cookies in Craft go through some validation to ensure that they aren't tampered with.

This is understandable, but is there any way of getting non-Craft cookies with twig?


texts: How to get user's photo url without transform?

texts:
Craft 3: I'm trying to get User Photo URL WITHOUT any transforms, but none of those options seems to work:
(some of it prints the url with some transform)

user.photo
user.getPhoto()
user.getPhoto('original')
user.getPhotoUrl()
user.getPhotoUrl('original')
user.photoUrl()
user.photoUrl('original')

There is no DOCs for this yet on the craft 3 site.
Anyone know?
Thanks


texts: Solspace Freeform plugin: Multi page form not going to next page

texts:
I have a multi-page form set up. No matter what I enter on page 1, the form doesn't submit - the page just reloads.
Looking in devtools - the POST data is there, but seems like Freeform is not recognising it to move to page 2.

Any help appreciated!


texts: Is it possible to stop Craft from logging so much?

texts:
I've got a Craft CMS installation that is set to production mode. I notice that my logs get flooded with a bunch of entries which don't seem very useful.

For example, in a matter of several days, I've already got console.log up to console.log.5 - So it's rotated the log file 5 times already. These files are filled with what seems like every single query that gets executed on the website. They're 70k lines a piece. It also logs a lot of entries in queue.log, among other files.

How can I stop logging information and only log things which require my attention, such as errors?

Thanks!


texts:
I'm fairly new to Craft. I have a question about how to manage and setup the editing of shared content in Craft which is used on multiple pages.

As an example I have a Mailing List signup element which will be used across multiple pages. In my templates I'm using an include:

{% include "includes/_mailing-signup" %}

I come from Perch where you could make a Region of content shared which would take it out of the page and into a 'Shared' area in the admin.

What's the best way to approach this in Craft where content can be edited in one central location to update on all page?


texts: Create entry with newly-uploaded asset programatically

texts:
I'm trying to do something very simple - but I've yet to find documentation to cover this basic scenario.

I'm writing a plugin. In a controller, I want to create a new entry, and assign an uploaded file to an Assets field on the entry.

I can create an entry using the example code:

$entry = new EntryModel();
$entry->getContent()->title = 'Title of thing';
// set some custom fields
craft()->entries->saveEntry($entry);

One of the fields is an Assets type; I have image data in a variable - I want to create an asset and associate it to the relevant property of the entry.


texts:
I've followed this answer for running a Craft install based on two domain names. I thought it was working but either I was wrong, or something's changed, because it's not now.

I have a.com (where the Craft install is) and b.com. In b.com's index.php I have this:

$craftPath = '../craft';

$_GET['p'] = 'subpath/' . (isset($_GET['p']) ? $_GET['p'] : '');

So that if I go to b.com/directory it loads a page as if it was a.com/subpath/directory.

Except it's not - it's as if it's trying to load a.com/directory.

If I put this in b.com's index.php (after the above):

var_dump($_GET['p']);
exit();

Then I see "subpath/directory", as expected. But if in my base layout template I put this:

{{ craft.request.getQueryString() }}

Then it shows "p=directory". So it seems like "subpath/" is going missing somewhere? I'm stumped.

UPDATE:

If I request b.com/index.php?p=directory then I get the page I expect (ie, /subpath/directory).


texts: Craft Commerce 2 - get order data for plugin

texts:
I want to write a plugin which writes all the order data into a CSV file.
Unfortunately the documentation for Commerce 2 isn't quite complete yet so I have difficulties to find out how to do the following with a plugin (so I need to use PHP and not Twig).

Get an order by ID.
Get ordered items.
Get the addresses for the order.

Every help appreciated.


texts:
Working on my first craft site and I'm setting up a thankyou template for after a form submission, but am getting an error when calling the contact entry (it's a single).

I've tried several code variations with no luck. This is my current template

{#
 # Contact Thank You template
 # ---------------
 #}

{% extends "_layout" %}

{# pass body id to layout template #}
{% set bodyId = 'contact' %}

    {% set entries = craft.entries.section('contact').id(5).find() %}
    {% for entry in entries %}

        {# Top Images/Slider Content Here #}
        {% block headImage %}
        {{ entry.title }}

        {% endblock %}

    {% endfor %}{# end contact entry for loop #}

Please advise.


texts: I want same template which is used in http://www.rideicon.com/ this website...is there any way to find which template is used in given website?


texts:
After updating from Craft CMS 2.6.2973 to Craft CMS 2.6.2981 I get the following error message:
"Unable to load the "Craft\xyz" runtime after Craft update"

"Craft\xyz" is a Twig extension
Fails in [install folder]\craft\app\vendor\twig\twig\lib\Twig\Environment.php line 900 (Twig_Environment::getRuntime())
Twig_Environment::runtimes is an empty array

Anyone else experienced this problem, and know what is causing it?

Thanks in advance!


texts: Commerce: Remove tax adjuster from line item in plugin

texts:
I need to remove adjusters from each line item if a certain condition is not met. I see that in the CP you can manually remove them by editing the line item but hunting down this code in Commerce's codebase has proven difficult.

Here's some of my code. I'm intending to keep certain adjusters from appearing for all line items before they save. How can I do this?

use yii\base\Event;
use craft\commerce\services\LineItems;
use craft\commerce\events\LineItemEvent;
use craft\commerce\models\OrderAdjustment;
use craft\commerce\models\LineItem;

Event::on(
    LineItems::class,
    LineItems::EVENT_BEFORE_SAVE_LINE_ITEM,
    function(LineItemEvent $event) {

        $lineItem = $event->lineItem;
        foreach ($lineItem->getAdjustments() as $adjustment) {
            /* @var OrderAdjustment $adjustment */

            if ($someExampleCondition) {
                // remove adjustment
            }

        }

    });

But when I inspect an OrderAdjustment model or LineItem model, I don't see any methods about removing or setting adjusters, only getting them.


texts: Business Logic Controller for Validating Address in Commerce

texts:
I am putting together my Business Logic plugin, as I want to validate the address fields throughout the checkout process of my Cart. I understand in order to do this I need to create a plugin and us the Craft Commerce commerce_addresses.onBeforeSaveAddress event.

I decided to try and use the https://github.com/lindseydiloreto/craft-businesslogic as a starting place.

My code is as follows;

public function init()
{
    craft()->on('commerce_addresses.onBeforeSaveAddress', function(Event $event){
        $address = $event->params['address'];

        if (empty($address->firstName))
        {
            $address->addError('firstName', Craft::t('Please enter your Name'));
             $event->performAction = false;
        }

        if (empty($address->address1))
        {
            $address->addError('address1', Craft::t('Please enter an Address'));
            $event->performAction = false;
        }

        if (empty($address->city))
        {
            $address->addError('city', Craft::t('Please enter your Town/City'));
            $event->performAction = false;
        }

        if (empty($address->zipCode))
        {
            $address->addError('zipCode', Craft::t('Please enter your Post Code'));
            $event->performAction = false;
        }

        if (empty($address->countryId))
        {
            $address->addError('countryId', Craft::t('Please select your Country'));
            $event->performAction = false;
        }
    });
}

If I have this code inside my to level plugin file named BusinessLogicPlugin.php it seems to work and it validates some of the fields as specified.

However, if I move this code into the controllers folder inside /controllers/BusinessLogicController.php it doesn't.

I am unsure what I need to do to move this out of the main/top level file, as I see this file getting very logon/messy if I need to add several 'business logics' to the site.

Can anyone shed light on this as to why it might not work within /controllers/

Thanks.


texts:
Does anyone know how to make the dropdown field translatable?

I'm working on a site which has both English and German languages, but whenever I set up a dropdown field it only ever appears in English and I don't have an option for the German version.

EDIT: I'm needing this to work as a dropdown on the German site also and not through templating {{ "word" | t }} as I need the client to have total control of this feature.

Any help would be appreciated — thanks.


texts: Close bootstrap row and start a new row Matrix

texts:
I need to figure out how to close out the columns if it equals 12 and then open a new row. I have a Matrix field set up with rows, but it needs to break with a new row if the columns equal 12.

Any suggestions?


texts:
I've tried to follow a ton of other articles posted on Stackoverflow for showing posts between 2 dates. I just can't seem to get it working and I keep getting an error of: Call to a member function getTimestamp() on boolean

{% set startDate = now | date_modify('first day of ' ~ qFilter) %}
{% set endDate = startDate | date_modify('+ 1 month') %}
{% set entries = craft.entries.section('events').postDate('<= startDate').expiryDate('>= endDate') %}

(qFilter is a url param: eg "May")

I'm trying to show posts that were live during a certain month.


texts:
This seems simple, but I cannot get it to render -- how do display a user's User Group? Assuming I set the user in segment 2:

{% set thePartner = craft.users.username( craft.request.getSegment(2) ) %}
This Is My User Group: {% ???? %}


texts: How do you pull out second level structure entries based on their parent?

texts:
I have a structure as follows:

Parent 1

Child 1
Child 2
Child 3

Parent 2

Child 1
Child 2
Child 3

Parent 3

Child 1
Child 2
Child 3
etc...

On my Child entry pages I want to pull out the other child entries under that parent to use as navigation. I think this should be fairly straight forward but I can not find any documentation on it. So far I have the below but this pulls out all level 2 child entries and not just the entries for the specified parent.

Any help much appreciated.

{% for subnav in craft.entries.section('mySection').level(2).find() %}

{{ subnav.title }}

{% endfor %}


texts: Updating Array Variable In Extending Template

texts:
I have a layout template:

{% set bodyClass = [] %}

    {{ block('pageBody') }}

And a template that extends it:

{% extends 'layout' %}

{% set bodyClass = bodyClass|merge(['myclass']) %}

{% block pageBody %}

Hello World

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab, consequuntur!

{% endblock %}

When I try to append to the bodyClass variable I get the error:

  Variable "bodyClass" does not exist.

However if I call the variable:

{% for class in bodyClass %}
  {{ class  }}
{% endfor %}

The template renders fine. Why can't I merge onto a variable that's been set in an extended template? Is there another way to do this?


texts: 299US$ Upgrade for Pro is for 1 site or any domain with my License

texts: I'm not sure 299US$ for Upgrading to Pro License is for 1 domain on upgrading or any domain with my account (Craft CMS Member).


texts: Showing pagination for a date range of entries

texts:
Pulling hair out here so looking for divine inspiration.

Trying to list a set of events/entries grouped by day. This is fine when all the dates are organised by an event date but when we introduce a date span (event start date and event end date) am struggling to work out how to get days that are not specifically occurring on a set day to appear, eg if starts Tuesday and ends Thursday to show on Wednesday.

I can get this working with an arbitrary range, eg to show all the events across a certain month but this gets considerably more complicated introducing pagination when no date range is specified. Ideally need to paginate by dates but pagination requires the ElementCriteriaModel.

Any thoughts on how might go about this as banging head against a brick wall …


texts: Cache issues making site super slow in production but not in dev mode

texts:
We have a site that is performing very poorly with very long load times and I'm guessing it may be related to caching but have no idea how/why.

The site's homepage was loading very slowly while in development due to a mega menu with a lot of queries to create primary and secondary navigation. I cached that globally while in dev and the page performance improved about 70%. I did some further global caching {% cache globally %} for things like the site footer and than added some regular caching {% cache %} for entry-specific template content.

Once this was all done, performance was very good. However, then we launched the site and took the site out of dev mode (which is had previously been in). The launch was on the same account - nothing changed - just pointed the DNS to this account.

Since that time, performance has been poor again. Further, when logging into the control panel, we always see this (which we never saw while in dev mode):

What's odd also is the circle and bar progress indicators are always in the exactly pictured state - they're never more or less along in terms of position (over the course of weeks).

Lastly, if I go into the CP settings area and Clear Caches, performance seems to pick up again for a little while.

I'm at a complete loss as to what may be happening that is causing these issue and any help would be greatly appreciated.

Thanks,
Mike


texts: Can I use a Global Variable for date/time?

texts:
The goal is to create a global variable that allows the user to specify how they would like to format the date/time for entries. I'd like to remove the hardcoded format shown here:

{{ entry.postDate|date('Y.d.m') }}

And replace it with something like this:

{{ entry.postDate|date('{{ global__siteMetadata.gv__articleDateFormat }}') }}

The user would add "Y.d.m" or any other PHP date format they like through the global field in the CMS. But when I use this, I get the following output:

{{ 1THURSDAY2019PMTHURSDAY__001631AMERICA/CHICAGOMARAMERICA/CHICAGO31PM21PM31PM.1CT__PMTHU, 21 MAR 2019 13:16:00 -050031162019-03-21T13:16:00-05:00THURSDAYAMERICA/CHICAGOTHUPM31AMERICA/CHICAGOMARCH2019THU, 21 MAR 2019 13:16:00 -050003PM31 }}

Obviously, the global variable is not being parsed. Any thoughts on how to make this happen?


texts: 'Unable to find component class 'FocusPoint_FocusPoint' - Craft CMS 3 Migrating from Focus Point Fields

texts:
I am migrating from Craft 2 to Craft 3 where images have Focus Point fields.

I've followed Dan Hoerr's FocalPoint Migration (migration guide)
And the php migrate script seems to have run successfully, however entries are still showing:

Opening the field under Settings > Fields > Matrix Block > Image shows:

How do I remove old FocusPoint field data and regain these image fields?
Will I need to manually re-add all the images?

I have tried:

Clearing Caches
Updating asset indexes


texts: Bumping into max row size of 65k craft_content table in MySQL 5.5

texts:
We are building out web applications for one client and have been using Craft to do so. However, I think we may have just hit a limit in the number of fields that Craft will support. More specifically this looks to be more of a MySQL limit. I had recently encountered a similar issue with a single entry that exceeded the row size with too much rich text. This was resolved with an update to the innodb file format, setting it to barracuda.

Unfortunately this is not helping me in this instance as the limitation is now the total byte count for the number of columns, not the actual content.

I've tried changing any columns in the table to 'text' and looked at any other tweaks based on the described limitations, but to no avail.

I'm at a loss for what to do at this point as I am unable to even add one more field without an error being thrown and the DB becoming corrupt.

As soon as I save that one more variable, I get this error:

Internal Server Error

CDbCommand failed to execute the SQL statement:
SQLSTATE[42000]: Syntax error or access violation:
1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB may help.
In current row format, BLOB prefix of 0 bytes is stored inline.

Then when I try to access the admin or any template on the site, I get this error:

Internal Server Error

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'content.field_heroCtaTitle' in 'field list'

The bummer with this error is I can only recover with a database restore. Didn't want to try and hack out the bad field.

In the short term, I may try to replace some standard fields with matrix fields which should reduce the number of columns in the craft_content table, but this is not really an ideal approach.

Any other thoughts, ideas, hacks would be greatly appreciated!


texts: Best practices for plugin service/controller/etc file names

texts:
When it comes to naming files within a plugin - is it preferable to follow PluginHandle_SomeController, or stuff everything inside a single PluginHandleController file?

This is probably a subjective question for the most part - but in building out a plugin at the moment, I have 4 different Service files, and I'm not sure if I'm being too pragmatic by breaking each different service type out individually, or if I should just include it within the single file. Each service isn't complex, they're basically a function or two each, but cover different aspects of the plugins feature set.

Any benefit to one way or the other?


texts: Dynamic entry template not loading on staging site but works on local.dev

texts:
I'm having a strange issue where pages aren't loading on the staging site that were all working fine on the local.dev site.

I have a Section called Available Homes and in that section it has two Entry types called Available Homes and Plot which link to two entry templates, that are dynamically called from the main entry.html.twig template, which then links to the sub folder

/entry
  /availablehomes
    availablehomes.html.twig
    plot.html.twig
  default.html.twig

The sections Entry URL Format is as follows:

developments/{counties.first.slug}/{developments.first.slug}/available-homes

and nested entries get the following:

{parent.uri}/{slug}

If I change the template from entry in the control panel to different template then it loads.

This is the entry template code:

{% include [
  "entry/" ~ entry.section.handle ~ "/" ~ entry.type,
  "entry/default"
] %}

Can someone help please?


texts:
I am following the documentation for Craft 2 here to create an entry form on the front end of my website. The form appears correctly on the front end but when I submit it, I get the following error:
"Page not found.
Caused by: Invalid Route – yii\base\InvalidRouteException
Unable to resolve the request: entries/saveEntry"

Here's my form:

<form method="post" accept-charset="UTF-8">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="news/{slug}">
    <input type="hidden" name="sectionId" value="1">

    Title
    <input id="title" type="text" name="title" value="">

    Body
    <textarea id="body" name="fields[body]" rows="20"></textarea>

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

Does anyone know where I am going wrong here? The user I am currently using to submit the form is an admin. I realize that the docs I'm following are for Craft 2 but I could not find this form in the Craft 3 docs.

Any help would be appreciated and thanks in advance!


texts: DB Queries in Craft Commerce 2 with large data

texts:
Currently working on an e-commerce site, which currently has over 4000 products with a mass of variants (averaging 3 variants per product) - and hit a few hurdles on the way...

At present, craft.products.hasVariant({hasSales: true}) takes over 4 minutes to return the data of items on sale. And again running a product count against the brand (category) is a similar issue.

Now I understand the sheer amount of queries for the above is getting a little ridiculous around 300 are showing in the Logs each time this is run - so running these queries from twig is next to impossible with the overheads.

So now turned to use a plugin with a public function in order to try and ease the pressure from the front end...

Anyone any ideas on how get the same results with a craft\db\Query...

Thanks in advance...

I hope this makes sense...


texts: Best practice for volume aliases in config files

texts:
I'm wondering about using a config/volumes.php file to specify volume aliases (instead of putting them in config/general.php). There's a comment in a previous codebase mentioning https://docs.craftcms.com/v3/config/#overriding-volume-settings but that seems to have been removed and now we can't find documentation about creating additional config files.

I see this somewhat related post and that @robin-schambach posted with a suggestion to put volume aliases alongside of other ones in config/general.php.

Craft 3: how can I set dynamic Base URL in sites setting?

So, is it best practice to create a config/volumes.php just for volume aliases or should they be kept in config/general.php?


texts: How to update different parts of the same Entry by different Users

texts:
I'm trying to work out the best way to administer this. The point of the system I'm building is as follows:

A front-end system which contains Events, Partners and Users
Each User is associated with one Partner
Each Event allows each Partner a certain number of places (guestAllocation)
Each User must be able to log in via the front end and update the names of the people who are going to the event (limited by guestAllocation) associated with their Partner.

Structure:

Currently, SuperTable lists the Partners invited to that event and their allowed guestAllocation

At the end of all this I need to export a Guest List which should be generated by the names of people who are attending the Event (if there are missing names and spare guestAllocation, there will be default value).

What's the best way to structure this in the database? Should I have one Event that gets updated by multiple users somewhow, or an Entry for each Partner related to an Event?
Is it possible to update a single Entry by multiple Users who can only add the correct number of names to the guest list for their Partner?


texts: How to fetch entries based on contents of several custom fields?

texts:
I'm currently doing something like this:

{% set vars = "foo, bar" %}

{% set entries1 = craft.entries.section('sectionName').customField1(vars).limit(NULL) %}
{% for entry in entries1 %}
    {% if entry not in allEntries %}
        {% set allEntries = allEntries | merge([entry]) %}
    {% endif %}
{% endfor %}

{% set entries2 = craft.entries.section('sectionName').customField2(vars).limit(NULL) %}
{% for entry in entries2 %}
    {% if entry not in allEntries %}
        {% set allEntries = allEntries | merge([entry]) %}
    {% endif %}
{% endfor %}

But for each custom field I want to check, it's a trip to the database, and I've currently got to check three custom fields. Is there a way to merge these into one trip? I need to know whether the contents of vars are in either custom field. They might be in one, none of both, for example.


texts: relatedTo - return only entries that have a related entry where a field in the related entry has a value

texts:
Trying to figure out if this is possible in 1 step. I want to return locations that have a related entry in the relatedMerchant field, but I'd also want to make sure that a field in the relatedMerchant entry has a value...

$locationsRelatedToCategories = Entry::find()
   ->section('locations')
   ->limit(100000)
   ->relatedTo([
     // somewhat unrelated, but this entry should be related to a specific category
     'targetElement' => $categoryElement, 'field' => 'locationOffers.category'
   ])
   ->relatedMerchant(':notempty:') // has to have a related merchant
   // somewhere here, how can I return only relatedMerchant entries where relatedMerchant.someField :notempty:
   ->all();


texts:
I have been trying to install Craft CMS on Windows.

I tried composer:

composer create-project craftcms/craft d:\temp\craft

After that when I try to craft setup there is a loop on the console which doesn't end.

When I try to run craft install the same thing happens, a loop but different text!

Thanks


texts:
I am trying to order a list of Users by the date of their last entry. order('postDate desc') works for entries of course, but I can't find a way to order the Users of those posts based on their latest post date. This is the code I am using now which orders the User by the date their account was created.

{# Grab all the Design Entries #}
{% set allDesigns = craft.entries.section('designs').limit(null).find() %}

{# Group by the authorId #}
{% set allDesignsByAuthorId = allDesigns|group('authorId') %}

{# Grab all of the users with the userIds in allDesignsByAuthorId #}
{% set designers = craft.users.group('designers').id(allDesignsByAuthorId|keys).order('dateCreated desc') %}

Thank you in advance for any help you can give!


texts: Solspace Calendar (2.0.0-b9) returning template not found error in CP

texts:
In the CraftCMS (3.0.2) control panel > Calendar > Month, when I click on one of my events I get the following error:

Template not found: therapy-wellness/_entry

I deconstructed the link and found that it's trying to pass the calendar name and the entry URL title to the _entry template. Eg.

/calendar-name/my-event-url-title

Obviously the issue is that the template to handle this request does not exist, but I'm not clear on when this stopped working or what to do about it?


texts: How can you check if "public user registration" is turned on or off on the front-end?

texts:
I'm trying to make a rather bullet proof front-end template that can toggle a sign up link based on if public registration is enabled or not.

Is there a way I can query to see if the system currently has public registration turned on from the front-end?


texts: Widget initialized in Business Logic plugin not loading

texts:
Hokay, this is a big one. Thanks in advance for anyone that has a look:

I’m trying to get this widget working on a Craft site.

The install documentation is pretty simple, I've hosted it here: http://brycekirk.com/documentation/

I've also installed Business Logic. Within that plugin, I've created a folder called vendor and and moved the psmw folder into it.

I've then initialized it in BusinessLogicPlugin.php:

public function init() {
    require_once 'vendor/psmw/init.php';
}

and added into /variables/BusinessLogicVariable.php, I've added the path to the shortcode functions, and a test one:

public function shortcode($optional = null)
{
    require_once(CRAFT_PLUGINS_PATH.'businesslogic/vendor/psmw/shortcode.php');
    shortcode(['type' => 'spark', 'symbol' => 'AAPL', 'template' => 'line', 'color' => 'blue']);
}

And then called it in my template with {{ craft.businessLogic.shortcode }}. It's generating HTML and JS, but not displaying the ticker, and I'm getting a jQuery is not defined error.

I'm sure there's something wrong with the logic behind how I'm loading in the plugin and its assets, I just can't figure out what it is. Any gesture in the right direction would be much appreciated! I can provide more info if needed.


texts:
We've currently got Subscriptions setup on a site which works a charm, but my main issue is outputting the price of the subscription, after the user has subscribed.

From the docs/templates I can even see how this is possible?!

You can get it via:

{% set subscriptions = craft.subscriptions.user(currentUser) %}

{% for subscription in subscriptions %}
    {{ subscriptionPlanData.plan.amount }}
{% endfor %}

But if for example, the plan is £300.00 then it outputs as 30000 and when formatted, it comes out like 30,000.00 using {{ subscriptionPlanData.plan.amount|number_format(2, '.', ',') }}

I can't see anyway of showing the user, how much they've paid in a human format without hacking around the number.


texts: Multisite Craft 3, different entries on different sites

texts:
Is it possible to show different entries on different subsites?

Currently I can show different versions of the same entry (e.g. translations), but I want entry 1 to show on site 1, entry 2 on site 1, entry 3 on site 2, etc.

As I have different user accounts for the admin for each site, is it also possible to only show the entries for site 1 in the cms of site 1?

In total I'd like to create around 30 subsites.

Update - site setup

I'm working with only 1 locale. I have one primary (default) site, the rest is in the same group, all on a different base URL and handle.


texts: Foreign key constraint sql error from entries/saveEntry when adding entry

texts:
I am getting a foreign key constraint sql error when trying to add an entry through a front end form.

<form method="post" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="entries/saveEntry">
  <input type="hidden" name="entryId" value="{{ entry.id }}">
  <select name="fields[vendor][]">
    {% for v in craft.entries.section('vendors') %}
      <option value="v.id">{{v.title}}</option>
    {% endfor %}
  </select>
  <input type="submit" value="Submit"/>
</form>

vendor is an Entries fieldtype, for unlimited entries from the vendors channel. Very similar code for adding a category works fine.

The error (complete with back-ticks):

  CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (metro.craft_relations, CONSTRAINT craft_relations_targetId_fk FOREIGN KEY (targetId) REFERENCES craft_elements (id) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO craft_relations (fieldId, sourceId, sourceLocale, targetId, sortOrder, dateCreated, dateUpdated, uid) VALUES (:row0_col0, :row0_col1, NULL, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7). Bound with :row0_col0='13', :row0_col1='39', :row0_col3='v.id', :row0_col4=1, :row0_col5='2016-02-13 08:28:03', :row0_col6='2016-02-13 08:28:03', :row0_col7='e455a06e-8f9d-4299-ad57-93577907f9a0'


texts:
I'm trying to activate a user via a plugin so that when the user is returned to the login page they are re-directed to their profile page.

I'm making use of the social logins beta plugin by dukt (I have written directly to them as well) which works fine if the user is already a craft user. However if the user is completely new to craft it throws an error saying the 'Account Has Not Been Activated'. When checking the CMS though the account has been set up and is active. So somewhere along the line the activation seems to be too late and is being delayed until after the user is sent back to the template.

The code creates a new user model in the plugin service with the _registerUser function. Which when looking at the object returned has 'pending =>' so not actually set to anything not even zero.

I've tried a couple of things but neither worked firstly adding

craft()->users->activateUser($user);

directly after saving the new UserModel and before returning the model.

Secondly setting the new UserModel with pending = 0 and pending = '0'

$newUser = new UserModel();
$newUser->username = $attributes['email'];
$newUser->email = $attributes['email'];
$newUser->pending = '0';

So can anyone shed any light on this or can advise me if this is possible from within the plugin or how the activation works on a new user when you want to automatically activate them without sending an activation email.

Many thanks


texts: How to apply a filter on a title with several concatenated elements?

texts:
Here's an example:

{% set title = entry.artistFirstName | capitalize ~ ' ' ~ entry.title | capitalize %}

It outputs Firstname title instead of Firstname Title whereas filters are applied on the two concatenated elements. Why and how to add this filter on each of these elements?


texts: Seeking information on the largest Craft sites built

texts:
We're writing an article on the largest Craft sites built and I'm having some challenges finding this information. Ideally, we want to compile a list of the top 20. "Largest" is determined by certain criteria like: Traffic (uniques/month; and pages/month); Number of Entries, Number of Members; Number of forum posts, etc.

I came across this article https://straightupcraft.com/articles/who-uses-craft-cms as a start to find out some basic info on sites built in Craft but it doesn't provide me with any info that would suggest these are some of the largest sites. In fact, when I entered in some of the names from that list into Alexa https://www.alexa.com/siteinfo their global ranking was quite low. I'm seeking help on how to surface this info.


texts: Craft login problem with memcache and ubuntu?

texts:
session_regenerate_id(): Session object destruction failed is the error i'm receiving after attempting to log in.

I just updated to Ubuntu 16.04LTS using PHP7 and php-memcached.

Is there a fix for this in a craft version? I'm on version 2.6.2791 and this behavior is still broken. I cannot seem to find a workaround besides overwriting Yii with a workaround myself.


texts: Order Entries Query by a Featured Light Switch

texts: I have a case studies filter that allows you to filter case studies by category. I've attached a light switch field called 'featured' to the entries that allow you to set it as featured. The idea is to have featured case studies appear first when filter results are returned. I've seen a few post discussing using an innerJoin to do this but I'm not sure if that's the right path or not. Any help would be greatly appreciated.


texts: Wanted to test 404 error page on our beta site. Set devMode to "false" in general.php. When I do this and try to view inner pages on the website, we receive an "internal server error". All inner pages fail and report "internal server error". The homepage works fine. Any ideas?


texts: Looking to get a random entry from my database which is tagged with 'featured', is this possible at all? I've seen randomised by just the entry loop but nothing else.


texts: I have switched the field of the SEOmatic plugin to translateable. All the SEO Titles are taken from the entry title. After changing to translateable I can see the translated fields in the SEO Title field but I need to save the entry again to see that on the website. Until then, the title is just in one language. Why is that? Is there any way to automate that, since I have a hundreds of entries and I dont want to do that manually.


texts: Wondering if there is anything (plugin or otherwise) I can put into my Redactor json file that will generate a mailto option in the insert link dropdown? I can’t seem to find anything on the subject.


texts:
I would like to selectively show a subset of my sections in the main navigation. Is it possible to do something like this?

{% set sections = craft.sections.getSectionById(1,2,3) %}

{% for section in sections}
...


texts:
I need to pass the logged-in user's email address as a variable to a embedded javascript form. I think the easiest way for me to do this is to dynamically embed the user's email address in the embed code URL.

Within the javascript snippet in the HTML block would be a URL "form=http://www.formsite.com/formname?email=XXXX@XXX.COM" -- how can I pass the logged in user's email into that?

I'm not a web developer nor do I have a lot of experience with craft other than as an admin level user. I'm trying to accomplish this without enlisting the services of a web developer to do any custom work.


texts: How to query/filter by the value of a lightswitch

texts:
In my news entries, I have a lightswitch field with the handle 'pinned'. I'm trying to query my news section for both pinned and unpinned news entries (true or false essentially), but I can't get consistent results with any of the following:

{% set pinnedNews = craft.entries().section('news').pinned('1').all() %}
{% set unpinnedNews = craft.entries().section('news').pinned('0').all() %}

{% set pinnedNews = craft.entries().section('news').pinned('true').all() %}
{% set unpinnedNews = craft.entries().section('news').pinned('false').all() %}

{% set pinnedNews = craft.entries().section('news').pinned('1').all() %}
{% set unpinnedNews = craft.entries().section('news').pinned('not 1').all() %}

{% set pinnedNews = craft.entries().section('news').search('pinned:1').all() %} THIS WORKS
{% set unpinnedNews = craft.entries().section('news').search('pinned:0').all() %} DOES NOT WORK
{% set unpinnedNews = craft.entries().section('news').search('pinned:not 1').all() %} DOES NOT WORK

Is there a proper to get the boolean values in Craft 3?


texts:
I have Sprout SEO working just great on Channels. However when I go to my channels that are single entries how do I handle custom SEO on a per page basis?

With my channels I can use this code in my templates and it works great:

{% do craft.sproutSeo.meta({
id: entry.id,
default: 'default'}) %}

However when on singles the entry.id throws an error.

Variable "entry" does not exist

Do i need to create my own default for each section listed out under Singles?

EDIT AFTER MORE TESTING
This seems to be effecting just one or two of my singles.
I wrote a little more about my issue but as I was typing so was Ben with the answer :)

Thanks for the help in advanced,

John


texts: Error when Attempting to Install Plugins

texts:
I keep getting this error whenever I try to install a plugin.

Not sure how to troubleshoot / resolve this.

Basically, I need the Contact Form and CKEditor plugins.

Setup: I'm running AMPPS with PHP 7.1, Apache and MySQL.


texts:
I'm having trouble using the Pixel and Tonic's Events plugin. I actually have no clue where to start on how to get it to render events in a template. I'm currently trying to pass in:

{% for event in craft.events.events_calendars('calendarName') %}

Which is obviously wrong. Could anyone explain how I understand what methods and variables those methods take for custom Element types?


texts: I realize this is a very general question but is there a way to sort a matrix field? So not alphabetically but a very certain order.


texts:
I am trying to import from Wordpress, so originally installed the Import plugin which worked but I needed xml not csv. So I uninstalled that and installed another, but now no matter what plugin I try to install, nothing shows up!

Any ideas? I tried resetting cache etc.

Update: Adding more details.

I've tried to install multiple plugins since the original one, the current plugin that I have in the plugins folder is 'craftimport-master' with all the correct files inside it.

The plugins page just says "There are no available plugins." with no errors.
I've tried running Clear Caches and Rebuild Search Indexes, just in case it worked.

I also tried updating to Pro (using craft.dev) but that didn't change it either.

Here is the current file structure:

Oh and there was an error when I uninstalled the first plugin but it redirected me almost instantly so I don't know what it said.


texts: User registration form add user to User Group?

texts: When using the User Registration Form (https://craftcms.com/docs/templating/user-registration-form), how do I make it so the user is added to a predefined User Group?


texts: Imager scrset matrix field, art directed content

texts:
What I'm trying to achieve: I would like the content editor to upload 2 images to use in a matrix block, one outputs at mobile and the other at desktop (they need to be different images due to art direction from landscape formate to portrait on mobile).

Here is the matrix field setup:

Current twig:

{% for block in entry.workVisuals.all() %}
    {% if block.type == "imageContent" %}

        {% set relatedAssets = block.workImageMobile.all() %}
          {% for pic in relatedAssets %}

            {% set img = craft.imager.transformImage(pic, {
              mode: 'crop',
              width: 1920,
            }) %}

            {% set imgMob = craft.imager.transformImage(entry.workImageMobile, {
                mode: 'crop',
                width: 768,
                height: 1272,
            }) %}

            <picture>
              <source media="(max-width: 767px)" srcset="{{ imgMob }}">
              <source media="(min-width: 768px)" srcset="{{ img }}">
              <img src="{{ img.url }}" alt="{{ pic.title }}">
            </picture>
          {% endfor %}

      {% endif %}

So obviously this is outputting the mobile image for both as asked:

{% set relatedAssets = block.workImageMobile.all() %}

What do i need to do to use both in the <picture> tag?


texts: Different order per locale for Structures

texts:
I know this is a long shot, but is there a way to order a Structure differently per locale? As in the standard drag and drop ordering that comes with a structure but with the ordering saved for each locale.

I'm trying to avoid having to create a translatable entries field to achieve the same thing on an overview page, as that means whene


texts: Sending E-Mails via SMTP with email address that contains special characters

texts: I got a problem with some smtp settings in my craft 3.5.14. The domain of my client uses special characters like (ö, ä, ü) and therefore for their email addresses. In this case my client only use the character "ö". When using those email addresses for authentication I always get an error when testing it in craft (settings/email). I can't find anything in the logs. Is it generally possible to send emails with special characters in their domain? Something to watch out for? I also tried to convert the email address into ace through an idn converter. No success. When using another provider on another domain without special characters the sending of emails works. Thx for you help!


texts: Why is Craft rendering a blank page instead of an error template?

texts:
I'm currently seeing this in the PHP error logs:

Fatal error: Uncaught exception 'Craft\\HttpException' with message '' in
/home/vagrant/htdocs/site/craft/app/controllers/TemplatesController.php:59\nStack
trace:\n#0 (): Craft\\TemplatesController->actionRender()\n#1
/home/vagrant/htdocs/site/craft/app/framework/web/actions/CAction.php(109):
ReflectionMethod->invokeArgs()\n#2
/home/vagrant/htdocs/site/craft/app/framework/web/actions/CInlineAction.php(47):
CAction->runWithParamsInternal()\n#3
/home/vagrant/htdocs/site/craft/app/framework/web/CController.php(308):
CInlineAction->runWithParams()\n#4
/home/vagrant/htdocs/site/craft/app/framework/web/CController.php(286):
CController->runAction()\n#5
/home/vagrant/htdocs/site/craft/app/framework/web/CController.php(265):
CController->runActionWithFilters()\n#6
/home/vagrant/htdocs/site/craft/app/framework/web/CWebApplication.php(284):
CController->run()\n#7
/home/vagrant/htdocs/site/craft/app/framework/web/CWebApplication.php(141):
CWebApplication->runController()\n#8
/home/vagrant/htdocs/site/craft/app/etc/web/WebApp.php(288):
CWebApplication->processRequest()\n#9
/home/vagrant/htdocs/site/craft/app/framework/base/CApplication.php(185):
Craft\\WebApp->processRequest()\n#10
/home/vagrant/htdocs/site/craft/app/index.php(62):
CApplication->run()\n#11
/home/vagrant/htdocs/site/public/index.php(19): include()\n#12 {main}

I have a _404.html template under templates/ and the errorTemplatePrefix set to _.


texts: Adding Redactor formatting that wraps selection

texts:
Anybody know how to add a redactor style/formatting option that effectively lets you select a bunch of text, click the formatting style, and have it wrap it in a div?
the desired scenario is basically... starting with

this is the original text

this is the original text

this is the original text

select the text, click the button turns it into...

this is the original text

this is the original text

this is the original text

what's currently happening is...

this is the original text

this is the original text

this is the original text

I basically added... this to  formattingAdd
"introduction": {
    "title": "Introduction",
    "api": "module.block.format",
    "args": {
        "tag": "div",
        "attr": {
            "class": "my-class"
        },
        "type": "toggle"
    }
}


texts:
As part of the new GDPR requirements in europe I've used cookiebot to show visitors what cookies we use on our site.

It's managed to show us what all but 1 cookie is used for. The cookie is called TS# and in their example stores this information:
0ei8sug22mj561h32e087mb5f2

The cookiebot report doesn’t mention CraftSessionId which has this data:
p2q9d364sf2abu1mmd5vi8rd54

May be a coincidence but they're both 26 characters long.

Does anyone know what the TS# cookie is used for, if it is a Craft CMS cookie?


texts: How can I get a full stack trace in my custom plugin log?

texts:
I'm using MyPlugin::log to separate the errors for my plugin. However, I'm only able to log a simple message using this technique.

Is it possible to have that output the full stack trace?

Here's what I'm getting (note the general format)...

2015/06/09 20:41:42 [error] [plugin] My example error message.
in /craft/app/etc/plugins/BasePlugin.php (65)
in /craft/plugins/businesslogic/services/BusinessLogicService.php (194)
in /craft/plugins/businesslogic/controllers/BusinessLogic_ActivitiesController.php (47)

But here's what I want (again, note the general format)...

2015/06/09 20:39:25 [error] [exception.CException] exception 'CException' with message 'Craft\BusinessLogic_ActivitiesController and its behaviors do not have a method or closure named "handleError".' in /craft/app/framework/base/CComponent.php:266
Stack trace:
#0 /craft/plugins/businesslogic/controllers/BusinessLogic_ActivitiesController.php(47): CComponent->__call('handleError', Array)
#1 /craft/plugins/businesslogic/controllers/BusinessLogic_ActivitiesController.php(47): Craft\BusinessLogic_ActivitiesController->handleError()
#2 /craft/app/framework/web/actions/CInlineAction.php(49): Craft\BusinessLogic_ActivitiesController->actionUpdate()

How do I get the #0, #1, #2, etc. to show up?


texts: Is there a way to retrieve the last date of an event using the Solspace calendar plugin?

texts:
I want to output a list of events some of which are repeating, on a monthly basis. Each event should show up once even if it's scheduled to repeat multiple times in the same month and the information for each event must also include the date of last occurrence if there is one.

To be a little bit more specific I would like to access the value of the field "End repeat" when it's value is set to "On date".

Is this possible?


texts: Set default status in CP admin for queried entries from "All" to "Live"

texts:
Just wondering if there's a way to set the default status for the entry listing pages in the admin, in my case from "All" to "Live". This would need to account for a page "refresh" and navigation using the sidebar links.

I've tried to amend the toolbar property available in the passed context for the cp.layouts.base hook but this is purely visual and has no effect on the criteria to query for these entries.

I've attached a screenshot to confirm location for anyone who's unsure. Many thanks in advance!


texts:
I am rendering some headings using twig and want to know if there is a better and more readable way of doing the following...

<{{ block.headingType }} class="measure-wide">{{ block.headingText }}</{{ block.headingType }}>

{{ block.headingType }} is the value of the heading selected in the editor. The values are h2, h3, h4, h5 etc.

The way the HTML headings are templated looks ugly (even though the rendering works). Is there a better way of rendering out the heading tags in twig based on the value selected?


texts: Linking to channel via structure section

texts:
I apologize for opening up a whole new question for this topic since it's been discussed a few times now, however I don't have enough rep yet to comment on the existing questions.

Regarding the answer to this question:

Channel index page linked in a structure

So what this answer is saying is that instead of having a whole separate channel for say, a blog, I should have it set up so that "Blog" is an entry type in my larger structure that also contains the various static pages for my site? if I'm understanding that correctly, doesn't the user lose out on some of the basic feature that a separate channel offers, such as not having to choose where in the structure hierarchy a new blog post should be?


texts: Having a plugin trigger on entries.onSaveEntry if a Lightswitch is turned on

texts:
Essentially I want the plugin to trigger on entries.onSaveEntry which I have working fine at the moment. I want to add a Lightswitch field that will be a condition however. i.e. The plugin will only trigger on save if the Lightswitch entry is turned on.

However I'm having trouble finding use of how to get the status of a field (specifically Lightswitch). Is that data available to be in $event->params['entry']?

Thank you.


texts: How can I display search "excerpts" from multiple sections?

texts: How do I create search result page "excerpts" when there are multiple sections/fields that need to be represented?


texts: How do I pass existing template variables on to an action controller?

texts:
In a plugin I am using registerSiteRoutes to route URL requests to a controller to handle some user validation before rendering the appropriate template. For example:

public function registerSiteRoutes()
{
    return array(
        'some-path-to/(?P<template>template-name)/(?P<entryId>\d+)' => array('action' => 'myPlugin/handleRequest'),
    );
}

The handleRequest controller looks something like this:

public function actionHandleRequest(array $variables = array())
{
    if (!craft()->request->isSiteRequest())
    {
        throw new HttpException(404);
    }

    // Do some conditional checks

    // If everything is OK, load requested template
    if (craft()->myPlugin->doChecks($userId, $entry))
    {
        $variables['entry'] = $entry;
        $this->renderTemplate('statement/_'.$variables['template'], $variables);
    }
}

The rendered template includes a form that submits to another action controller in the plugin to handle creation of a number of entries based on the submitted values.

How can I pass the error messages (if any) back to the submitted form (that is accessed via the site route set in the plugin)?

I've tried removing the site route and accessing the template directly and this works. However, it also means that I need to add in a load of conditional logic to control access to the template in the template itself. I'd rather extract the logic into a plugin controller as I did before as it makes the templates a lot cleaner and separates out the logic.


texts: What could be causing the 'Password cannot be blank' validation check not to run on user update?

texts:
I have an instance of a front-end password update form running on one of my Craft Pro 2.3.2635 sites, and it works correctly. If I submit the form with the correct current password and valid new password, it updates the user, and if there is a problem, it displays an error message.

However, when I use the same code on a new build, if I leave both the current and existing password fields blanks it fails to correctly validate redirects to the page specified in my redirect input field, and the on user save event is fired. The same form on my other build appears to fail validation with the message 'Password  cannot be blank'.

All other erroring including the password length, and incorrect current password checks seem to run fine. Why might the 'Password cannot be blank' not be working on my new site?

I've included my form template below:

{% macro errorList(errors) %}
    {% if errors %}
        {% for error in errors %}

{{ error }}

        {% endfor %}
    {% endif %}
{% endmacro %}
{% from _self import errorList %}

{% extends "_layout" %}

{% block content %}

{% if not user %}
    {% redirect "/login" %}
{% else %}

Enter your existing password, then choose a new one and click save.

            <form class="agents-login__form  [ form  form--agents ]" method="post" action="" accept-charset="UTF-8" enctype="multipart/form-data">
                {{ getCsrfInput() }}

                <input type="hidden" name="action" value="users/saveUser">
                <input type="hidden" name="redirect" value="/agents">
                <input type="hidden" name="userId" value="{{ user.id }}">

                {% if account is defined %}

                        {{ errorList(account.getErrors('currentPassword')) }}
                        {{ errorList(account.getErrors('newPassword')) }}

                {% endif %}

                        Existing Password
                        <input class="form__control" id="currentPassword" type="password" name="password">

                        New Password
                        <input class="form__control" id="newPassword" type="password" name="newPassword">

                        <input type="submit" value="Save" class="[ btn  btn--full ]" />

Back to downloads

            </form>

{% endif %}

{% endblock %}


texts:
I am trying to make dependency's work using Craft Cache (set to Redis.)

I've tried:

craft()->cache->set('cache_key', 'cache_value', 0, new CFileCacheDependency('dependent_cache_key'));

This stores the cache. However, when I then update the value for cache with the key name dependent_cache_key, cache_key does not invalidate.

Is CFileCacheDependency not the right way to attach dependency to a cache key? All the YII description says is "File Name."

Also, is it possible to declare directories for Craft Cache? I see YII also has a dependency method for directories CDirectoryCacheDependency, which would be optimal in my case, but I have no idea how to assign a directory for cache using craft()->cache->set() and craft->cache->get()

Any help would be incredibly appreciated. Been stumped crawling through yii docs to figure this out.

http://www.yiiframework.com/doc/guide/1.1/en/caching.data#cache-dependency


texts: How to process POST and entry fields when using same form for Add as Edit on front end?

texts:
I use the same form for adding an entry on the front end as I do for editing it.

So when editing it, we need to insert the field values in the fields.

When editing or adding it we also need to re-populate the values in the form from the POST submission in case of form validation error.

So this means checking if there is a post request, assigning the values from the post to some variables used in the form, but if not then assigning them from the entry.

I always think the method I use is a bit of a hack, and there should be some built in way to do it, but cant find it.

Below is the most efficient code I have yet but it's needed for each field. What it does is if there is a post entry then to assign it to the entry object, so that way in my form the value is just the entry.myCustomField which is set whether we're editing or posting (priority to post value if it exists).

But I wanted to know if there is an even more efficient way, something built in, or if I could even iterate through all post fields automatically without having to create the below code for each field.

{% if craft.request.getPost('fields.myCustomField') is not null %}
    {% set entry = entry|merge({'myCustomField': craft.request.getPost('fields.myCustomField')}) %}
{% endif %}

I did think maybe I could just assign the whole POST to the entry as follows which would be ideal, but I get the error 'The merge filter only works with arrays or "Traversable"'

{% if craft.request.getPost('fields') is not null %}
    {% set entry = entry|merge(craft.request.getPost('fields')) %}
{% endif %}

Another idea I had was to get all the fields from the section and iterate through them, but I don't know how I can create variables named after the values of the field handles.

{% set fields = craft.sections.getSectionByHandle('mySection').getEntryTypes()[0].getFieldLayout().getFields() %}
{% for field in fields %}
    {# dont know how to create each field named after the field.handle so I can enter my code above once and iterate over it per field #}
{% endfor %}


texts:
I have a field type that I need to initialize. When the page loads I can use code like the following to handle certain behaviors of the field:

$('.myfieldwrapper').each(function() {
  new Craft.MyField(this);
});

Within the Craft.MyField object, I add a couple listeners like so:

this.addListener(this.$element, 'change', 'handleElementChange');
this.addListener(this.$element2, 'click', 'handleElement2Click');

That all works fine.  However, this field doesn't just get added to the page on page load. It exists in the row of a table, and a user can add additional rows to the table which add a new row and field to the DOM.

I've tried to instantiate the newly added field in several ways, and I have been unable to get it right yet. The Craft.MyField seems to be initializing, and I appear to be able to re-initialize the default fields on the page, but my attempts do not have any affect on the dynamic fields that get added.

I don't think the following is the best way to do this, but it's currently the closest I've come and is the simplest example code I can share reflecting my attempts.

After a new field gets added dynamically, I trigger an event:

$('#tableId').trigger('rowAddOrRemove');

And I have additional code watching for that event and attempting to re-initialize all the fields on the page:

$('#tableId').on('rowAddOrRemove', function(event){
  $('.myfieldwrapper').each(function() {
    new Craft.MyField(this);
  });
});

When I do this the initial field on the page still works but none of the dynamically added fields behave as I need them too.

Any ideas on what I'm doing wrong or what concepts I need to understand better to get this right?


texts:
I am looking for a way to add new locale files or override existing ones.

Basically a Craft 3 version of this: https://craftcms.com/support/adding-additional-locales

I've tried the way described here: https://github.com/craftcms/locales

But that does not seem to be picked up by Craft 3.


texts: permissions userphotos "an unknown error occurred"

texts:
On my production server, each time I try to change or upload a user photo I get the "an unknown error occurred" message. If I check the logs, the error says it couldn't delete the folder of the userphotos because it is not writable.

Now I checked the settings and everything is set to 755, the same as the assets folder where I have no problems uploading. The only way I got the userphotos to work is to set the permission on the folder to 777, but that's not the best solution security-wise.

So why isn't the userphotos folder writeable but the assets folder is?


texts: Restrict user editing permissions within a user's group?

texts:
I'm setting up a site for a charity with a national branch and several sub-chapters. I'd like users of a particular chapter to be able to add/modify users, but only within their chapter's user group. It seems like with the current structure of admin permissions, I'm only able to say whether or not a user can add/edit users, and not restrict that to a particular group.

Is this possible and I'm just not seeing a setting somewhere? If not, does anyone know of a plugin that provides this functionality?

Thanks.


texts: How can I add and replace classes in the markdown field?

texts:
Prompt please both in the field {{ block.markdownContent|markdown|raw }} replace and add classes?

For example:

 replace by:

 replace by:

 replace by:

 replace by:
 and add within the tag
 тег

Provided that the listed list of
 is to be replaced:

 replace by:

 replace by:

add:

1

Html code:

Numbered list:

Simple text

                    1

Simple text

                    2

Simple text

Simple list:

Simple text

Simple text

Simple text


texts: Import database backup when using docker

texts:
I am trying to import a database backup into a craft instance running on Docker, but none of the fields or content from the latest backup are importing.

Here are the steps I took

I used these default.conf and docker-compose.yml files here  to create a local environment with Docker.
I made a site locally, and backed up the database several times (and so now have a series of backups - see image below)
I restarted Docker after updating to the latest version, then ran docker-compose up to relaunch.
Craft loaded with the initial DB, but none of the fields or content from the latest backup appear (localhost actually returns a Twig runtime err when it encounters the first field.)

Here is how my backup folder looks:

It seems the issue lies with my docker-compose.yml (below), but I don't see how to edit this to call the right DB backup.
Any help or advice much appreciated!

# docker-compose.yml
version: '2.1'

services:
  nginx:
    image: nginx:alpine
    ports:
      - 80:80
    depends_on:
      - craft
    volumes_from:
      - craft
    volumes:
      - ./default.conf:/etc/nginx/conf.d/default.conf # nginx configuration (see below)
      - ./assets:/var/www/html/web/assets # For static assets (media, js and css). We don't need PHP for them.

  craft:
    image: urbantrout/craftcms:mysql
    depends_on:
      - mariadb
    volumes:
      - ./backups:/var/www/html/storage/backups
      - ./templates:/var/www/html/templates # Craft CMS template files
      - ./modules:/var/www/html/modules # Craft modules directory
      - ./config/element-api.php:/var/www/html/config/element-api.php # Element API file - we require the plugin below
    environment:
      DEPENDENCIES: >- # additional composer packages (must be comma separated)
        yiisoft/yii2-redis,
        craftcms/redactor,
        craftcms/element-api,
        nystudio107/craft-seomatic

      CRAFTCMS_EMAIL: XXXXXXXXXXXXX
      CRAFTCMS_USERNAME: admin
      CRAFTCMS_PASSWORD: XXXXXXXXXXXXXX
      CRAFTCMS_SITENAME: Craft CMS Installation
      CRAFTCMS_LANGUAGE: en-US

      REDIS_HOST: redis
      SESSION_DRIVER: redis
      CACHE_DRIVER: redis

      DB_SERVER: mariadb
      DB_NAME: craft
      DB_USER: craft
      DB_PASSWORD: secret
      DB_DATABASE: craft
      DB_SCHEMA: public
      DB_DRIVER: mysql
      DB_PORT: 3306

  mariadb:
    image: mariadb:10.1
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: craft
      MYSQL_PASSWORD: secret
      MYSQL_DATABASE: craft
    volumes:
      # Persistent data
      - dbdata:/var/lib/mysql

  redis:
    image: redis:4-alpine
    volumes:
      - redisdata:/data

volumes:
  dbdata:
  redisdata:


texts: Allowing users to register with only email, without specifying username

texts:
Is it possible create user (using frontend registration form) without specifying username?
Since users can log-in using their email, for frontend users username only adds to confusion.


texts: SproutForms: "an unknown error occurred" in entries template chart

texts:
When viewing the charts in the entries template of the SproutForms plugin, I receive an "an unknown error occurred" error message.

In the console, I see this:

Failed to load resource: the server responded with a status of 500 (Internal Server Error): https://domain.com/index.php?p=admin/actions/sproutForms/charts/getEntriesData

Any clue what's going on here?


texts:
Is there any way to save a variable in the Craft session inside a controller?

I'm running a cron job and I need to store a variable as a session for every run to see if a condition matches.


texts: Eager Loading a Structure and descendants

texts:
In looking at the the BaseElementModel:getDescendants() method and saw it checks for eager loading elements named 'descendants.'

// Eager-loaded?
if ($this->hasEagerLoadedElements('descendants'))
{
    return $this->getEagerLoadedElements('descendants');
}

I added with and the descendants condition to a Structure and the page is now loading with a few less queries.

{% set entries = craft.entries({
    section: 'sectionHandle',
    limit: null,
    with: [
        'descendants'
    ]
}) %}

Can anybody explain what is happening here?


texts:
I have my users setup with a category field that links to a category of countries and each country has states/provinces.

I have my form setup to only display the states listed under United States. The plugin I created saves this data as expected.

The problem I'm having is accessing the state which was saved for the user. This is my current code. It works BUT there has to be a better way:

{% if user.addressMatrix | length %}

    {% for addressInfo in user.addressMatrix %}

        {% set cat = addressInfo.region[1] %}

        {{ cat.title }}

   {% endfor %}

{% endif %}

Please advise and thanks in advance.


texts:
On our play pages (ex. http://actors-express.com.s102768.gridserver.com/plays/liaisons), we list our each of the cast members, their headshot and role. We did this by creating a matrix field that pulls in the Entry for each person and relates it to the specifics for the show.

We would like to write code on the template for their bio page (ex. http://actors-express.com.s102768.gridserver.com/people/kristin-butler) that will scan through all those matrices on play pages and find out which plays they have been in, then display a list of plays with links to each of their URLs. It would be nice to pull in what their role was in the play, but that's not a requirement at this point.

We would also perform a lookup and see if one of the plays was currently on stage (a flag on our play entry type), or if it was upcoming to pull it into the module above on the right.


texts: What files does Craft store in "craft/storage/runtime/temp"

texts:
What files does Craft store in craft/storage/runtime/temp folder.
And what is the purpose of it.
And how to stop it form getting huge.