texts: Is it possible to pass a variable to an event in a plugin?

texts:
I need to find out if any changes have been made to the entry on successful save.

Using events entries.onBeforeSaveEntry and entries.onSaveEntry seems to be a way to do it. Maybe.

Can I pass some entry variables as arguments to the function on event listener?

public function init()
{
    parent::init();

    $oldVar = "";

    //Event: onBeforeSaveEntry
    craft()->on('entries.beforeSaveEntry', function (Event $event)
    {
        $entryModel = $event->params['entry'];
        $oldVar     = $entryModel->fieldVar;
    });

    //Event: onSaveEntry
    craft()->on('entries.saveEntry', function (Event $event)
    {
        $entryModel = $event->params['entry'];
        $newVar     = $entryModel->fieldVar;

        if ( $oldVar !== $newVar ){
            // ...
        }
    });
}


texts: validationKey on load balanced enviornments

texts:
In the Craft docs for validationKey config settings, it states that validationKey should be used in load-balanced environments.

I'm curious on how to set this up for a load-balanced site. Does each  server need a different key, or should they all share the same setting in the config?


texts:
Is it possible to exclude some fields when using search?

Getting the q parameter from the URL and searching the products section including all fields:

{% set query = craft.request.getParam('q') %}
{% set results = craft.entries.section('products').search(query) %}

This searches all fields, included those for "related articles" and "related products". I need to exclude those from the search.

Some experiments

Works to exclude hits in relatedProducts but limits the fields being searched to the productName field:

craft.entries.section('products').search('productName:'~ query ~' -relatedProducts:'~ query)

Does not work - also returns the product with a related product matching the query:

craft.entries.section('products').search(query ~' -relatedProducts:'~ query)

and the same when trying to include several fields before excluding relatedProducts:

craft.entries.section('products').search('productName:'~ query ~' OR productDescription:'~ query ~' -relatedProducts:'~ query)

Also tried searching just in the relatedProducts, confirming that it returns only the product with a related entry matching the query:

craft.entries.section('products').search('relatedProducts:'~ query)


texts:
i'm developing on a dedicated root server and all works fine.
The whole installation (database and all files except /craft/storage) is then pushed to an git repository and will be deployed to the production server from there.

The production server is a cloud server and i can not log in the CP on this server. I can load the admin page, but if i try to login, nothing happens.
The XHR-Request gives back following error:

Server Error
session_regenerate_id(): Session object destruction failed

I found this https://github.com/yiisoft/yii/issues/2376 but i think a custom fix to the yii framework is not the right solution for me.

Any suggestions?

thanks and brgrds
Stephan


texts:
This is my first multi locale Craft setup and everything is cool on my local/dev environment. However running into difficulty on the production server (Digital Ocean/ServerPilot). My default (EN) version plays nice but my German locale returns a 500 when isSystemOn => 'true'. When set to false it displays the appropriate 'Unavailable' (503) template. So it looks like everything is setup fine as far as Digital Ocean, ServerPilot, domain, etc... so I'm wondering if there's something amiss in my config?

I have 2 "apps" setup in ServerPilot for my default (EN) and German sites. My German app contains a public folder with an index.php that contains the server path:

$craftPath = '../../sitenamecom/craft';

I've also tried a full server path but the above seems to work fine anyway.

Then in my config/general.php I've got all the usual stuff, plus:

// production (DE)
'sitename.de' => array(
    'backupDbOnUpdate'                  => true,
    'devMode'                           => false,
    'environmentVariables' => array(
        'baseUrl'                       => 'https://sitename.de',
        'basePath'                      => realpath(dirname(__FILE__)) . '/../../public',
    ),
    'isSystemOn'                        => false,
    'siteUrl'                           => 'https://sitename.de/',
),

So as I say, everything working fine on my local server but with isSystemOn set to true on production I get an Internal Server Error. Anyone got any suggestions on how best to debug this?


texts: Activation link missing from activation email

texts:
A client is reporting that users are attempting sign up but receiving activation emails with no activation link present, simply a blank space where the {{link}} tag is placed.

We are unable to re-create the issue at our end. Domain name settings have been verified, we are only using one domain and prefix (www diverts to non-www address).

In the screenshot below, the link shouls appear after 'following link:'

To activate your account, please click the following link, or copy-paste it into your browser:

{{link}}

When the site opens, simply log in to view the Option Grids

Has anyone had any similar issues?


texts: Craft Commerce: Create new shipping zone by excluding other zones

texts:
I need to create 3 shipping zones in Craft Commerce 2 (currently on v2.1.7):

UK
Europe
Rest Of The World

Having to manually add the countries to the UK and Europe zones isn't too much of an issue, but do I have to manually add all the remaining countries to the Rest Of The World zone? Or is there a way to create a zone just by excluding countries from the other zones I've created (e.g. Rest Of The World should be all countries except the countries in the UK and Europe zones)?


texts: Internal Server Error - getDateFormatter() on null

texts:
When doing a manual update from 2.6.3012 to 2.7.8, I get the following error:

  Internal Server Error
  Call to a member function getDateFormatter() on null

I get the following error when enabling devMode:

Updating from the Dashboard fails too, but in a slightly more verbose fashion:

  [curl] 28: Operation timed out after 30001 milliseconds with 0 out of 0 bytes received [url] https://download.craftcdn.com/craft/2.7/2.7.8/Patch/2.6.3012/[redacted string of numbers].zip

Any help is welcome.


texts:
I have an existing database full of users with their addresses. I'd like to import this into Craft (Commerce), and have their addresses saved as their billing address.

The user import part is fine, I can use boboldehampsinks plugin to get the users in, and I can add custom fields to temporarily hold the address information until I can add it as their billing address.

Can anyone suggest a good way to go about this? The documentation for Craft Commerce doesn't seem to be as complete as for Craft, and I can't see a way to set a users billing address.

Thanks.


texts: (Apache) pages only load when adding index.php?p=

texts:
It looks like Apache (or Craft?) isn't routing all of the requests to index.php. So http://SITENAME/index.php?p=admin/install works, but http://SITENAME/admin/install doesn't. The issue is this is happening with every URL, so the HTML for the install page loads, but none of the assets (CSS, JS) do.

Here's my issue in picture form:


texts:
I'm getting alarmed by the size of the database backups and the database in general. The site has Craft Commerce installed, which contributes I think, but if you look at the following list of backups there seems to have been a sharp increase in database size that has nothing to do with Craft Commerce (which has been installed since July).
Does anyone have an tips or articles to share about getting control of this? I feel it's getting ridiculous but that it has probably happened since we went live on October 17.
EDIT:
Looking at the database tables, there are definitely several tables that seem to larger than they should be:

craft_searchindex 31MiB
craft_commerce_orders 30MiB
craft_elements_i18n 20MiB
craft_content 15MiB craft_elements 13MiB
craft_commerce_customers 8MiB
craft_entryversions 3MiB
craft_deprecationerrors 1.5MiB

I'm wondering if there is a spam issue here. Could that be it?


texts:
I'm loading a set of entries related to 'category' and ordering them by the value of a Dropdown field in the entries. This work well using this code:

{% set entries = craft.entries.relatedTo(category).order('myDropdownField') %}

Now I need to change the Dropdown field to a Category field, but I am not able to sort my entries by this new category field by swapping the dropdown with the category field like this:

{% set entries = craft.entries.relatedTo(category).order('myNewCatField') %}

It gives me this error:

  CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'departmentCat' in 'order clause'.

I also tried to use the Craft group filter, but I could not make it work in my setting.

Any suggestions are appreciated!


texts: How can I extend admincp to show all related category not only the first one on the AdminCP list view?

texts: I would like to extend the adminCP via plugin to not only show the first related item, but every related item in the list (like categories, or tags etc...) Right now the adminCP is showing only 1 item in the table view


texts: Accessing relation data in an on save entry event

texts:
I have a front end form that saves an entry with a relation field based on an ID.

<input type="hidden" name="items[{{ index }}][finish]" value="{{ finish.id }}">

When the entry is saved this ID saves the field with the correct category relation.

I then have a plugin which triggers on entry save that sends an email and attaches the $entry.

craft()->on( 'entries.saveEntry', function( Event $event ){
    $entry = $event->params['entry'];
    if( !$event->params['isNewEntry'] || $entry->section->handle != 'sampleOrders' )
    {
        return;
    }
    //die(Craft::dump($entry->samplesOrder[0]->finish->find()));
    $email = new EmailModel();
    $email->toEmail = 'luke@ten4design.co.uk';
    $email->subject = 'Order Received';
    $email->body = '';
    $email->htmlBody = craft()->templates->render( 'pentagonemailservice/_emails/order', array(
        'entry' => $entry
    ) );
    try{
        craft()->email->sendEmail( $email );
    }
    catch( Exception $e ){
        Craft::log( 'Could not send email.', LogLevel::Error );
    }
} );

For some reason in my email template I cannot access the finish field with the following code. The other fields print correctly. The finish field is a category relation.

{% for item in entry.samplesOrder %}
    {% set appr = craft.entries.section( 'appearances' ).apprId( item.appearance ).first() %}

{{ appr.apprId }} - {{ appr.displayName }} - {{ appr.pentagonRange[0].title }}

Material

{{ appr.material }}

Finish

    {#
{{ finish.title }}
#}

Quantity

{{ item.quantity }}

{% endfor %}

How do I access the finish field in my email template?


texts: I'd like to manage my users (both active site users, and other employees at my client's company) via the Craft user management. I've added more profile fields, etc. But i'm wondering, is there a built in public profile page/route for users?  I'm listing various users on a page, and i'd like their profile image to link to a profile page for each of them, with more info, contact info etc. What's the best way to do this?


texts: Install Craft in a subfolder of an ee site?

texts:
I have an ee site which I can't move over to Craft yet (need a commenting plugin) but I need to extend the site quite a bit. I'm thinking of either installing Craft in a subdomain or a subfolder.

In a Friday chat Brandon advised to go with a subdomain, as having Craft in a subfolder of an ee site that I would/might run into session problems.

Is installing Craft into a subfolder of an ee site a complete no no, or are the potential session problems avoidable? Anything else to lookout for?

Thanks for any help.


texts: The fieldtype class “insert fieldtype class here” could not be found

texts:
I'm specifically having this issue with Sprout SEO, but I would imagine the problem would persist across any plugin, given whatever solution is used.

Anywho, so I've got three environments - dev, stage, and production (live site). I've reinstalled the plugin multiple times, and checked permissions several times as well. All environments are running Ubuntu, so I know that a case-sensitivity issue (as seen here) isn't the case.

Is there anything database related that could be causing the problem?

Or if not that, our .gitignore file just looks like this:

craft/storage/backups/
craft/storage
*.swp
public/uploads

Wasn't sure if anything in storage needed to be not ignored for any plugins.

Any help would be greatly appreciated. Thanks!


texts:
I found this useful search, sort and filter script http://jplist.com, which I have added to my website. It works perfectly until I realize that when my database grow to the point it slow the page down. I am on the fence whether use Craft's {% set entries = craft.entries.relatedTo(category) %} or jplist's data source to fetch the entries from the database?

Any suggestion what the best safest approach?


texts: Select Freeform email recipients from dropdown (not dynamic recipients field)

texts:
I have a Freeform form where the user selects their area of interest from a dropdown. I need the email to be sent to different email addresses, based on the area of interest (some will have multiple addresses).

I thought I could do it with the dynamic recipients field, but that doesn't let me customize the label (it needs to be the area of interest, not the email address).

I tried setting the values of a regular dropdown field as the email address, with the areas of interest as the label, and then setting setting the admin recipients of the email to [[ interestedIn }} (the dropdown field name), and I can submit the form, but the email is not sent.

Is there another way to accomplish this?


texts: How to allow non-admin user group to copy password reset URL and activation URL?

texts: So, as an Admin, I can copy either the password reset URL or the activation URL. But giving another user group all of the Users permissions (e.g. using select all in the permissions tab when editing the group) does not give them the same functionality. Is this a config setting or just not possible?


texts: addFieldVariables not functioning with string data

texts:
I have the following code:

    {% set query = {} %}

     {% if not craft.request.getParam('q')|length %}
          {#.. key, value pairing .. #}
          {% set query = query | merge({(key):(value)}) %}
     {% else %}
          {% set query = craft.request.getParam('q') %}
     {% endif %}

     {% set queryStr = query|join(' OR ') %}

     {% do craft.sproutForms.addFieldVariables({ queryStr: queryStr }) %}

     {{ craft.sproutForms.displayForm('requestcsv') }}

When I add {{queryStr}} to my hidden field in requestcsv, it doesn't populate. I can output {{queryStr}} on the page, and even so, it doesn't get passed.

Is there something I'm missing in order to be able to pass this string to a hidden field? {{queryStr}} is just a plain string.


texts: How to save extra data when I save an entry

texts:
I am trying to understand if it is possible to do a hook on an entry save without creating a plugin.

This is what I would like to happen:
- In my entry, I have some address fields (street, city, province...).
- I would like to take those info and go grab a lat and long from Google maps and save it with the entry.  The lat and long fields are also available in the entry if people want to fill them or modify them.

I was doing all this in Wordpress with custom post types, but I'm trying to convert it to Craft.

Is it possible or do I have to create a plugin to do it?


texts: Ajax Function on a search form not working in Safari & IE

texts:
I made an ajax function so my page wont refresh and my search window wont disappear on form submit. It works fine in all browsers but it keeps refreshing on Safari.

Here is my code:

{% if not craft.request.isAjax %}
    {% set pagingJs %}
        $(function () {
            $('#searchBtn').click(function (e) {
                $( ".searchResult" ).remove();
                $( ".noResult" ).remove();
                e.preventDefault();
                var search = $('#searchField').val();

                $('#loading').show();
                $.get( "/?q="+search, function( data ) {
                    data = $('#searchQuery', data).html();
                    $( "#searchQuery" ).append(data);
                });
            });
        });
        $( document ).ajaxStop(function() {
           $('#loading').hide();
        });
    {% endset %}
{% includeJs pagingJs %}
{% endif %}


texts: .htaccess for Craft CMS - removing segment from URL

texts:
I'm rebuilding a website which needs to run Craft CMS as the main frontend and a bespoke CRM system at the same domain.

The file setup is basically

public_html

cms
crm

To make things a bit more complicated, certain parts of the CRM have to be publically accessible, so there are a few different URL structures that need to run from the CRM, and the rest from Craft. Also, the images/scripts are in the cms folder, so I need to get those to work without cms in the URL.

For the most part this is working lovely, but I can't get force /cms/ to be removed from the URL, so whilst the site works fine without it, it's live on 2 different URLs.

I have the  with the following code:

<IfModule mod_rewrite.c>

    # Force the root to match slug of home page
    # This is the only way I can get the home page to
    # show on the root, as it's within a structure
    RewriteRule ^$ /__home__

    # Get rid of /cms (this doesn't work)
    RewriteRule ^cms/?(.+)$ /$1 [R=301]

    # Sort out frontend files
    RewriteCond %{REQUEST_URI} /assets/.*
    RewriteCond %{REQUEST_URI} !/assets/admin/.*
    RewriteCond %{REQUEST_URI} !/cms/.*
    RewriteCond %{REQUEST_URI} !/crm/web/.*
    RewriteRule ^(.*\.(gif|jpg|jpeg|bmp|svg|png|css|js|json|pdf|eot|woff|woff2|ttf|otf))$ /cms/$1 [QSA,L]

    # Sort out admin files
    RewriteCond %{REQUEST_URI} /assets/admin/.*
    RewriteCond %{REQUEST_URI} !/cms/.*
    RewriteCond %{REQUEST_URI} !/crm/web/.*
    RewriteRule ^(.*\.(gif|jpg|jpeg|bmp|svg|png|css|js|json|pdf|eot|woff|woff2|ttf|otf))$ /crm/web/$1 [QSA,L]

    # Send would-be 404 requests to Craft
    # Need to exclude any that should route to the CRM
    # Any that we exclude, we then need to route below
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteCond %{REQUEST_URI} !^/manager/?(.*)$ [NC]
    RewriteCond %{REQUEST_URI} !^/forms/(.+)$ [NC]
    RewriteCond %{REQUEST_URI} !^/partners/?(.*)$ [NC]
    RewriteCond %{REQUEST_URI} !^$ [NC]
    RewriteRule (.+) /cms/index.php/$1 [QSA,L]

    # CRM Admin
    RewriteCond %{REQUEST_URI} ^/manager/?(.*)$ [NC]
    RewriteRule ^manager/?(.*) /crm/web/app.php [QSA,L]

    # Quote Forms
    RewriteCond %{REQUEST_URI} ^/forms/(.+)$ [NC]
    RewriteRule ^forms/(.+) /crm/web/app.php [QSA,L]

    # Signup Forms
    RewriteCond %{REQUEST_URI} ^/partners/?(.*)$ [NC]
    RewriteRule ^partners/?(.*) /crm/web/app.php [QSA,L]

</IfModule>

So I'm fairly sure that the line RewriteRule ^cms/?(.+)$ /$1 [R=301] would work, but the default Craft logic is somehow preventing it - if I comment out the default craft section, then it removes cms from the URLs, but obviously nothing is routed through Craft, so 404s all round.

I'm completely stumped at this point, so any help would be appreciated!


texts:
I have a number field used for episode numbers and I would like to automatically add a leading zero when the number is less than 10. I have this working with a conditional but it seems inefficient. Is there a twig filter that I don't know about that does this?

{% if entry.episodeNumber < "10" %}
    {% set episodeNumber = '0' ~ entry.episodeNumber %}
{% else %}
    {% set episodeNumber = entry.episodeNumber %}
{% endif %}

The above works but seems overly long to accomplish what should be a simple task.


texts: Testing database credentials Craft 3 Setup

texts:
When i try setup db in craft 3 at windows with composer using php craft setup/db command it give me
Which database driver are you using? [mysql,pgsql,?]: pgsql
Database server name or IP address: [127.0.0.1]
Database port: [5432]
Database username: [root]
Database password:
Database name: cmsdb
Database schema: [public]
Database table prefix:
Testing database credentials ... failed: could not find driver
Database server name or IP address: [127.0.0.1]```


texts:
I'm developing a plugin which requires certain sections and fields to exist so I'm currently creating them in the onAfterInstall() method of the plugin.

I can create individual fields, sections, entry types and even a Matrix field + block type fine. I'm having trouble with creating the Matrix sub-field and attaching that field to the Matrix block type.

I have created the matrix field:

$field = new FieldModel();
$field->groupId      = $group->id;
$field->name         = Craft::t('Field Name');
$field->handle       = 'handleName';
$field->translatable = false;
$field->type         = 'Matrix';
craft()->fields->saveField($fieldContentRSS);

And this is the block type:

$blockType = new MatrixBlockTypeModel();
$blockType->fieldId = $field->id;
$blockType->name = Craft::t('Block Name');
$blockType->handle = 'handleName';
craft()->matrix->saveBlockType($blockType);

I know that I will need to create a field/set of fields for this block type. Is this exactly the same as the new field above? How do I then attach these fields to the block type?


texts: How can I display entry edit history on the front end?

texts: When editing an entry from the control panel you can switch versions of the entry. I would like to do the same thing but on the front end. Is there any way to do this using native craft functionality or do I need to use a plugin.


texts: Pass field handle from to render tag using Freeform field

texts:
I'm new to Craft and I'm trying to figure out how to place a form within an entry using a Solspace Freeform field.  Specifically I need to pass the form handle into the render tag to place that form on a particular page.

{{ craft.freeform.form("formHandlefromfreeformfield").render() }}

Thanks!


texts: Errors occuring with Assets and Amazon S3

texts:
I've just set up a new S3 account and want to move my assets folders there. But when I try to upload a file, I get the following error:

S3::getObjectInfo(mikkelbang, shallowtree.png): [400] Unexpected HTTP status

And the same goes for when I try to update the Assets index:

S3::getBucket(): [InvalidRequest] The authorization mechanism you have provided is not supported.
Please use AWS4-HMAC-SHA256.

I've never used S3 before, so it might be something I need to set up there. But I couldn't find any documentation on setting up S3 with Craft...


texts:
We've created a site which now has 40 entries in a Structure.  We need to retrospectively remove the URI's because there isn't an individual page for each entry, they're all on one page but search engines are tracking individual pages.

We've removed {slug} from the Section and replaced with 'projects' (no quotes) but of course CraftCMS sees this as duplicate when it tries to resave all the entries.

Any suggestions?

Many thanks


texts: Recommended approach for integrating a CDN with a Craft site

texts:
I realize there are lots of options out there, but I’d be interested to know what service folks would recommend for integrating a CDN with Craft?

It'd also be helpful to know what the general pain points, strengths and/or weaknesses of a given approach are (especially as it relates to Craft integration).


texts: Creating Drafts from Frontend Entry Form

texts:
A two part question here.

When saving an entry from front-end entry form, can I designate it to save as a draft? If so, how?
If the answer to #1 is true, can I query against that to list only entries that are not in 'draft' mode.


texts: How can I upload separate 1X and 2X images?

texts: I want my site to serve 1X and 2X images depending on the browser using something like Picturefill, and I don’t want the 1X version to just be automatically generated using a transform - I want to be able to upload separate 1X and 2X versions, and have them be linked together. How can I go about that?


texts: Creating a POST request endpoint using Element API

texts:
I am currently using Element API to serve Craft contents.

What I'm wondering is, is it possible to create an endpoint that handle POST requests? Like form submission and such?

All the examples that I've seen so far is to serve Craft entries as JSON.


texts: Plugins page inside CP Settings not working

texts:
I get an error when trying to access CP/Settings/Plugins:

Fatal error: Class 'Craft\PluginVariable' not found in folderpath/craft/app/variables/PluginsVariable.php on line 47

Any Ideas?


texts: Frontend form database error with empty Users field

texts:
Within a frontend Add Product form (using Craft Commerce) I'm having problems with a database error whenever a Users field is left empty.

Here's the field:

{% set teachers = craft.users.group('teachers') %}
<select name="fields[teacher][]">
<option value="">n/a</option>
{% for teacher in teachers %}
  <option value="{{ teacher.id }}">{{ teacher.name }}</option>
{% endfor %}
</select>

I've tried setting the empty value to zero, but no luck. The forms works fine apart from this, so I don't think it's anything specific to Craft Commerce.


texts:
Following situation:

I have a inline-block title with a background gradient applied. So in order that the background always starts from the left, each line will have to be spanned by a span tag.

Welcome to

our site

should become this:

Welcome to

our site

I've started with this:

{{ block.heroTitle|nl2br }}

But I'm stuck.
Any help appreciated.


texts: How can I create a loop to cycle thru each category and the the entries within each category?

texts:
So, I have a loop that populates all the entries related to a given category. See below.  I have multiple categories.  Right now, I use the same code for each category -  swapping only the name of the category out (e.g, category1, category2 ...).  How can I build a loop that avoids this?

My current template is as follows. I did not include the repetition for each category.

        {% set category = craft.entries.seciont('posts') %}

Aircraft

            {% for entry in category.relatedTo(craft.categories.slug('category1')) %}

                         {{ entry.title }} k

            {% endfor %}


texts: How to load entries with a certain category only?

texts:
I am trying to load entries from a section which have a category field with multiple values. Based on that, I want to show specific entries filtered by category.

Example: I have a news section and I want to load sports and entertainment news only.

Help me on this, please.


texts: How do you sort elements queried from multiple channels?

texts:
This is how I query elements from multiple channels:

{% set allEntries = craft.entries.section(['publication','text', 'exhibition']).limit(null) %}

I now want to sort all these entries by a custom date field. If all channels had the same date field, I would just append order('releaseDate desc') to the query.

But as I have chosen to set up individual date fields (i.e. publicationReleaseDate, exhibitionOpeningDate) I cannot figure out how to join and sort them.

Of course I could just use the same field in all channels, but then I can't have individual field names and instructions per channel.


texts: Add elements to ElementSelect via Javascript

texts:
I'm developing a plugin that works with Spotify's API. I'm wondering if can I add elements to a ElementSelect field. I do have the IDs of the elements I want to add.

Thanks!


texts: Live Preview Not Updating - No errors found

texts:
Okay, first I know this question has been asked - specifically here: Live preview not automatically updating

But that suggestion did not help. I have no console errors, no network errors. In fact, when I view the network tab in Chrome I can see it successfully POSTing the changes as I type in live preview mode. I have this set up on MAMP using craft.dev as the hostname.

I tried this in both Chrome and FireFox with no luck, as well as trying a fresh install of Craft with no success.

Any thoughts are greatly appreciated on what the issue might be.

Thanks.


texts: How to query in MySQL all entries with related categories

texts: I have a custom product grid not associated with Craft Commerce. I am wondering, how can I query, in the SQL database, all entries and their related categories?


texts: How to handle search results that point to a page of aggregated entries?

texts:
I have a few pages in my site that aggregate information, for example, a single awards page that gets all the entries in an awards channel. Single awards entries don't have their own URLs.

How do I handle cases like this in search results?


texts: File upload - maximum upload size of 0 B

texts:
I just upgraded Craft to the latest version, and this error now shows up.

The file “myfile.jpg” could not be uploaded, because it exceeds the maximum upload size of 0 B

Any fix ? Everything worked fine before the update.
Thanks !


texts: Cast Entry to appropriate type to access fields and functions in module

texts:
Newbie to Craft CMS. I am trying to send a push notification to an app when an entry of specific type (NewsItem) is saved, and I'm doing so via a Craft Module. I got this code snippet from another StackExchange question, and I have changed it a bit to implement it according to my needs:

        Craft::$app->elements->on(Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $event) {

            // Make sure it's an entry.
            if ($event->element instanceof craft\elements\Entry) {
                $entry = $event->element;

                // Check if it's in the section you care about
                if ($entry->sectionId == 1) {
                    // Do your custom logic

                        if(isset($entry->photo))
                            $image_name = $entry->photo->getUrl();
                        else
                            $image_name = 'http://img.youtube.com/vi/' . $entry->youtubeVideoCode . '/0.jpg';

I'm getting this error:

Calling unknown method: craft\elements\db\AssetQuery::getUrl()

I may be wrong, but I'm assuming I have to cast $entry to (NewsItem) somewhere in the code to access the getUrl() function? How and where do I do that?

Thanks in advance for your help.


texts: Using the required field validation in custom element types/plugins?

texts:
I am finishing up the last few details on my custom element type. I have custom statuses and public submissions working. The last detail is providing validation on custom fields set through the field layout outside of the control panel.

Here is a brief overview of the plugin:

PluginNameElementType - that allows custom fields via the field layout.
PluginNameController - which has an action 'actionSubmit' which is allowed public access to submit entries outside of the control panel.

The code for public submission is on this post:

Allow anonymous submission on a custom element type?

I have seen some Yii examples that include CActiveForm::validate() and pass a  model to validate the input, but I don't see that anywhere in Craft.

The way I see it, there are two parts to validation on custom element types from outside of the control panel.

The first part being providing authentication for the attributes defined as 'required' in the element types model.

For example, if you have the following code:

protected function defineAttributes()
{
    return array_merge(
        parent::defineAttributes(), array(
            'formId' => array(
                AttributeType::Number,
                'required' => true
            ),
            'fieldName1' => array(
                AttributeType::String,
                'required' => true
            ),
            'fieldName2' => array(
                AttributeType::String,
                'required' => true
            ),
        )
    );
}

How would I access and return this in the controller action method that allows public submission? Does Craft provide an additional layer on top of Yii to assist with validation?

The second part of the question is similar, but unique all the same. The other part I need to provide validation for is the custom fields set in the field layout of the element type. If a user sets the fields to required in the same method they would with a regular entry field. How would I access validation on the custom fields level?


texts: Getting the URI of an Entries field in a Structure with no URLs

texts:
I am building a navigation section which is a structure. The idea is that it is a flexible place to build links to other entries/ custom urls etc. It has one entry.type called page which has an entries Field called 'entryLink' to link to other entries.

It has no urls of its own set in 'Entries in this section have their own URLs'.

When i try to get the entriesField called 'entryLink' all i can get is the title:

 {% set navEntries = craft.entries.section('navigation').hidePage('< 1')  %}
   {% for nav in navEntries %}

 {{ nav.entryLink.first() }}

 {% endfor %}

If i try and get the slug or uri I always get an error. Eg when using :

 {% set navEntries = craft.entries.section('navigation').hidePage('< 1')  %}
   {% for nav in navEntries %}

 {{ nav.entryLink.first().uri }}

 {% endfor %}

I get

Impossible to access an attribute ("uri") on a null variable

What am I missing?
I notice the documentation here: https://craftcms.com/docs/entries-fields
specifies 'target locale' which i do not have in my entrie field setup.


texts: Craft Commerce: Adding Number fields to product and cart pages

texts:
I'm adding the following to my _product.html template to try and add a number to a line item in the same way that notes are added. I'm using the following input:

<input type="number" name="numberDistance" step="any" placeholder="Add your minimum distance in mm..." id="distanceNum">

I then add the following to my cart template to output the field:

Min distance: {{ item.numberDistance }}

When I add an item to my cart I get the following error:

Craft\Commerce_LineItemModel and its behaviors do not have a method or closure named "numberDistance".

What is going wrong and how do I fix this?


texts: How do I output only country part of location field using the SimpleMap plugin?

texts:
The docs of the SimpleMap plugin mention it's possible to output only part of the full location, e.g. just the country by using

{{ myMapField.country_short }}

but in my project I get this error when I try doing so:

Internal Server Error

Craft\SimpleMap_MapModel and its behaviors do not have a method or closure named "country".

Same result without the _short suffix.
The plugin is set up properly as I can correctly output full address, lat, lng, zoom values like so:

{{ myMapField.address }}
{{ myMapField.lat }}
{{ myMapField.lng }}

Just splitting up the full address results in the above error. What's going wrong?


texts: Bypass server memory_limits for Cloud Asset resources

texts: I’m building a site that needs to upload large video files to Amazon S3. We have run into limitations with our host where they will only increase the memory_limit to 512mb and it’s likely that there will be video files in excess of this. It seems that Craft stages the video file on the server before sending it to S3. Is there a way around this so we can bypass the hosting limits on file uploads and memory and not make the user use an FTP client to upload bigger files?


texts: Can anyone tell me what's wrong with the 'andWhere' part of this query?

texts:
What am I doing wrong in the 'andWhere' part of this query? I've tried a variety of different ways of doing it but nothing seems to work... It just seems to be ignored. Does anyone know the proper way I should be doing it?

foreach($entryIds as $entryId) {
    $data[] = craft()->db->createCommand()
    ->select('*')
    ->from('amforms_content')
    ->where(array(
            'elementId' => $entryId
    ))
    ->andWhere('dateCreated > 2017-02-11')
    ->queryAll();
}

return array($data);


texts: Updating a Lightswitch value not working via front-end

texts:
Everything looks OK but when I submit my form, field doesn't get updated.

When the page reloads, the checkbox is still showing old state.

<label>Some Option</label>
<label><input type="checkbox" name="fields[membersAvailableForCollaborativeProjects]" value="1" {% if user.membersAvailableForCollaborativeProjects %}checked="checked"{% endif %} /> Yes

membersAvailableForCollaborativeProjects is a Lightswitch field type. Treating it the same as a Checkbox.

Any ideas?

My form action is users/saveUser as I'm trying to update a users profile via the front-end.


texts: Can I move a local Asset to S3 and keep relations?

texts:
I have a Assets folder (local) with 100 assets in it.

Now I have a new Assets folder connected to Amazon s3.

Can I just drag-n-drop my assets from my local folder over to my s3 folder and keep all relationships for those assets to my elements (entries)?


texts: Migration from “Focal Point Field" for Craft to Native Craft 3 image focal point

texts: Is there a migration from the “Focal Point Field for Craft“ plugin to the Craft3 native focal point? Or has anyone tried this themselves?


texts: Twig: Parent template does not inherent what's ever inside the child template even using extends in the child

texts:
I'm using twigfiddle.com for now because i want to simulate Twig templates before moving on using Craft.

Base.twig (main template)

{% block head %}
    {% block content %}{% endblock %}
{% endblock %}

Child.twig

{% extends "Base.twig" %}

{% block content %}
    Content from child.twig
{% endblock %}

I expect an output of "Content from child.twig" but instead get nothing.


texts:
I've set up a dropdown field for the client to choose from a list of pre-defined addresses.  In my template, I want to determine whether the field has a value or not.  When I look in the database, Entry A has a value of 'NULL', while Entry B has a value of 'address1'.  So the field is working properly in those regards.

However, in my template it's all or nothing.  Here is my code:

{% if event.includeMap|length %}

        Defined? {{ event.includeMap is defined }}

        Not Null? {{ event.includeMap is not null }}

        Null: {{ event.includeMap is null }}

        Value: {{ event.includeMap }}

        {% include 'partials/_inc-map' %}

{% endif %}

I've added the options in the left column to see what the database returns.  In both cases, they return the same values.  However, with Entry A, nothing is returned as a value, and in Entry B, the correct value appears.

I have also tried

{% if event.includeMap is defined %}
{% if event.includeMap is not null %}

Any other thoughts?


texts:
1.{% set totalDeliveryTime = 0 %}
2.{% set countDeliveries = 0 %}
3.{% set averageDeliveryTime = 0 %}
4.{% for order in pastOrders %}
5. to--{{order.orderDeliveryTime}}--
6.{% set totalDeliveryTime = totalDeliveryTime + order.orderDeliveryTime %}
7.  td--{{totalDeliveryTime}}
8.{% set countDeliveries = countDeliveries + 1 %}
9.  tc--{{countDeliveries}}
10.{% endfor %}
11.  result--{{ totalDeliveryTime / countDeliveries }}

Result:
to--15--
td--1
tc--1

to--30--
td--2
tc--2

to--60--
td--3
tc--3

to--60--
td--4
tc--4

result--1

Its a simple average calculating formula. I want to add my all 'orderDeliveryTime' in 'totalDeliveryTime' through line 6. As in line 5, it returns correct values of orderDeliveryTime which is in 'to' you can see in Result but when we add in totalDeliveryTime through line 6 it return 'td' values (please look 'td' in Result). I think it should 15+30+60+60 (addition of all orderDeliveryTime).

Beside this I also used

{% set ratingsSum = 0 %}
{% if pastOrders | length %}
{% for order in pastOrders %}
{% set ratingsSum = ratingsSum + order.orderDeliveryTime %}
{% endfor %}
{% set ratingAverage = ratingsSum / pastOrders | length %}
AverageTime:{{ratingAverage}}
{% endif %}

https://cliveportman.co.uk/code/calculate-average-of-numbers-in-craft-cms-using-twig
But it also returns the same result which is 1.


texts: Hide or obfuscate Digital Product file path?

texts:
What's the best way to hide the URL from the user/browser task bar? The only way I can get the link to work for a customer is to select the "Assets have public URL", which I really would prefer not to.

Even though the link to the files are on a protected My Downloads page surrounded by If License, it wouldn't be hard for a knowledgeable internet user to start guessing other file paths. I already have the filenames closely related, but not exact to the product title and the products are in a subfolder by entry id.

A preferred way would be to have the product file directory be above the web root, but I can't seem to find any way to do that with the plugin as it is. Am I missing something?

I suppose I could just make my download folder a string of 30 random characters so at least you can't see the full URL in the bottom of a browser as it would get cut off. But a smart user could still copy the link to the clipboard.

I see there is the Internal Assets plugin that looks to do what I want, but it's based on User Permissions. So I assume I would have to write a plugin that assigns a user permission to a file once they get a license generated, but it would be nice to have that feature be a part of the Digital Products itself.

Any other options?


texts: Split posts by days similar to Product hunt

texts:
I've been looking around at numerous posts but can't seem to find a solution that works without constant work arounds. I'm looking to show posts split by days they were posted similar to www.producthunt.com

Today, Yesterday -> Sunday. Then displaying the date posted e.g. 31st March from then on.

Different to most questions as this is showing live posts set out by different worded days instead of numerical. I can't seem to find a way of doing this without repeating the same code block for 7 days then a generic by date loop?

Is this possible in Craft?


texts:
When I edit the homepage in the cp I get a error 403.

But only on the homepage. Very weird. The Error is:

  You don't have permission to access
  /public/admin/entries/homepage/2-homepage on this server.

That is totaly the wrong path so I guess it must be a .htaccess problem.
It's on a server where I have not much rights.

I couldn't point the url above the webroot to /public/ so I wrote (or better yet pasted) a htaccess in the webroot to redirect into /public/ and I guess thats the problem:

- .htaccess {# points to public #}
- craft
- public
-- .htaccess

In the root htaccess I wrote:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^domain.com$ [NC,OR]
    RewriteCond %{HTTP_HOST} ^www.domain.com$
    RewriteCond %{REQUEST_URI} !public/
    RewriteRule (.*) /public/$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.html [NC,L]

And then in /public/.htaccess I wrote:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Remove file extensions on hostfactory
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)\.html$ /$1 [L,R=301]

    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.+) index.php?p=$1 [QSA,L]

  RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]

</IfModule>

And in /public/index.php there is $craftPath = '../craft';

Is there something strange in there? I have no idea about htacces.


texts:
Having a bear of a time doing something which seems like it should be quite simple. I'm trying to display the category group name in my templates, using the handle and can't quite get it. I've explored the docs but haven't found much help there.

I've tried:

{{ caseStudiesCategories }}

Error: Variable "caseStudiesCategories" does not exist

As well as:

{%  set catName = craft.categories.group('caseStudiesCategories') %}
{{ catName }}

Error: Object of class Craft\ElementCriteriaModel could not be converted to string

Any thoughts or ideas?

Thanks.


texts: Category Sources plugin not showing headings

texts:
Like the title tells you the headings, titles of the category groups, are not showing in the sidebar.

This is a screenshot from the github page of the plugin.
The "FOOD" and "DRINKS" titles are not being displayed when I use the plugin. In the source I can see:

So the plugin knows that there should be a heading but It does not fill the  element.

Any Ideas?


texts:
EmailService now has Twig render email messages in safe mode.

  -- https://craftcms.com/changelog#build2903

I don't think this is really a bug as it's intended behaviour, but this is causing me a pretty big issue because my email layout has code in it like:

{% set contactDetails = craft.globals.getSetByHandle('contactDetails') -%}

But I think safe mode now means that the craft variable isn't actually available. I can pass it in manually when I'm sending non-standard emails with craft()->emails->sendEmail(), but has anyone found a way around this for the built-in ones like the activation/verification emails?


texts: Craft 3 redirect of existing and non-existing URLs

texts:
I'm upgrading a relatively large, but low budget, local government website from Craft 2 to Craft 3. The major remaining pain point is a replacement for the Craft 2 Reroute plugin, which is not available in the Craft 3 Plugin Store.

The main use of Reroute was redirecting existing URLs to other URLs within the site (and against my preferences to external URLs as well). The site is built around a strong hierarchy and quite often the parent page of "section" is redirected to the first child page (because the parent page serves as a conceptual folder and has no content on its own). And because Reroute worked well old entries/pages were not always deleted, just redirected to their new location or replacement pages by the content editors.

In Craft 3 we have Redirect plugin, Retour and Sprout Redirect, but as far as I can tell they only redirect non-existing URLs.

Now I could add a redirect Entry field to the various sections, and manually manage it that way, but it is quite a lot of work in the midst of an upgrade done by one little person (me).

So have I misunderstood that there are no existing plugins that will redirect existing URLs? Or am I missing an obviously easy way of doing this?


texts:
Is it possible to query elements of type MatrixBlock in Twig like other elements? You can get entries with

{% set entries = craft.entries.all() %}

Is there something similar available for Matrix blocks?


texts: Custom-created or personalized products with Craft Commerce?

texts:
I’m building a webshop with Craft Commerce where customers will be able to customize/personalize parts of clothes based on a predefined set of options.

With a pullover for example, customers should be able to change material, color and prints of the body, sleeves and cuffs individually. The different options are individual products themselves and have their own stock information. So the product bought by the customer will be composed of several product variants for different parts of the pullover.

With Woo Commerce for example there is a Composite Products Plugin, that seems like a solution to this: https://woocommerce.com/products/composite-products/

Is there a similar plugin for Craft Commerce, that would help me with building this feature? Or is there another way of solving this?

Thanks!


texts:
I have completed a website for a school who can't upload files when in school.
When they upload a file the status bar loads the full way across the screen but at the top right it just keeps spinning. Nothing more happens - the files doesn't become available.
I can upload fine from home and the staff can upload fine at home as well.
What is the likely cause of this issue - I have log files to check if need be - I deleted the log files then asked them to try and upload a file - then I took a copy of the log files with Dev Mode on.

Is this likely to be a Firewall Issue in the school? I did a website for another local school who would have the same IT provider but have no issues there.


texts: Plugin to create an image transformation for an external image (non-Assets field)

texts:
In reference to this post Can I apply an image transformation to an arbitrary image (non-Assets field)? does anyone have an example of the markup used to create the plugin to do this?

I need to create a transformed thumbnail from a Vimeo/YouTube URL, but I am having difficulty creating the plugin.

I have created the following function:

public function videothumb($imageSource)
{

  $image = craft()->images->loadImage($imageSource);
  $image->setQuality($quality);
  $image->resize($transform->width, $transform->height);
  $image->saveAs($targetFile);

}

And I am calling it with:

{% set thumb = {
    mode: 'crop',
    width: 100,
    height: 100,
    quality: 75,
    position: 'top-center'
} %}
{{ craft.thoughtful.videothumb('http://thoughtfulweb.com/images/_halfPageStandard/Thoughtful-Indiana-Jones.jpg', thumb) }}

I keep getting an error saying:

No file exists at the path “http://thoughtfulweb.com/images/_halfPageStandard/Thoughtful-Indiana-Jones.jpg”

Clearly I am missing something. Any pointers would be greatly received.

PS. I know the file path does not point to a video thumbnail. It’s just for reference.


texts:
Is it possible to assign priveleges to a user group (not admin but with CP access) to manually 'Activate User's?

We have a few users who struggle with the email process but it would seem only top level admins can Activate - is that the case or is there an override?

Thanks
Dan


texts:
I have 2 sections, events and activities, that share many fields. But activities doesn't have an eventLevel field as there isn't a level. eventLevel is a radio fieldtype. So I want to insert the eventLevel when it exists and if it doesn't just insert the text "Activity". I've tried various tests on if eventLevel is defined, is null, and length. If there is an eventLevel it displays, but if it's an activity I end up with an empty cell.

{% set events = craft.entries.find({section:'events,activities', eventDate : ">= " ~ now.w3cDate() , order:'eventDate'}) %}
{% if events %}
    {% for entry in events %}

        {{ entry.eventDate.format('D j M') }}
        {{ entry.eventName }}
        {{ entry.nearestTown }}
        {% if entry.eventLevel is defined %}{{ entry.eventLevel }}{% else %}Activity{% endif %}

    {% endfor %}
{% endif %}

I've also tried the twig default filter with the same result:

{{ entry.eventLevel|default('Activity') }}


texts: Is it possible to group entries by checkbox?

texts:
We're looking to output a list of entries and group them by their check box values. Here's what we've got so far:

{% for checkbox, entries in craft.entries.section('my_entries').find() | group('checkbox') %}
   {{ checkbox }}
{% endfor %}

This currently returns "Object of class Craft\MultiOptionsFieldData could not be converted to string".

Any ideas? Is this even possible?


texts: Markdown filter, how to add HTML attributes?

texts: What's a good way to add attributes (classes etc.) to the HTML elements returned from the markdown filter?


texts:
In my experience is the build-in process of image transform not too kind to the image quality, even with the highest quality. In my case the brighter tones in the images are lost which means that images have no properly defined edges.
Is there a good possibility to modify images troughout so they don't drop to total white?


texts: Amazon S3 Images not showing up in Assets

texts:
I'm developing locally and adding images to my Amazon S3 bucket. I have the same connection to the bucket on my remote environment. On my local environment, I can see the images I've uploaded, but on my remote environment none of the images that I uploaded locally are showing when I browse assets.

On my remote environment, if I attempt to re-upload the image, I get a message: A file with the name “mylogo.svg” already exists. So I know that the assets field is correctly connected to the bucket in the remote environment.


texts: How to check for new entries periodically from the front-end?

texts:
I would like to check periodically (every 5 seconds for example) whether there are new entries in a channel. If yes, I would like to present a refresh button on the website (with the number of the new entries).

So, I probably need a javascript which executes every 5 seconds a database query for the id of the latest entry and compares that to the last entry shown on the current page.

But I guess that javascript is not able to execute a database query, so I probably need a plugin for this.

Are my assumptions more or less correct? Where could I find a paid developper for such a plugin?

Thank you very much for your support.


texts:
I want let the editor to choose an optional color via the color picker, but this didn't have the option 'no color' (or transparent).

Is there a solution to this? I use it a lot and have always to add a boolean switch so the editor can switch it on and off, but that's not the best way to do this.


texts: I have external GraphQL API's to get data which will be used in Twig Templates. This has nothing to do with Craft data or Craft's content. Is there a way to call GraphQL from Twig template instead of using javascript or something else.


texts:
I need to add a separator if there are a multiple of types. How can this be done in a for loop?

{% for type in entry.buildType %}{{ type }}{% endfor %}

The outcome is similar to a breadcrumb nav, with an added "/", however the separator should only be placed in between - not for the last.


texts: Is it possible to change a loop if mobile browser is detected?

texts:
I have a loop to go through my products which go in batches because they need to show detail info every third entry. When the Website is viewed from a mobile device, Tablet or Mobile I want it to loop in Batches of 2 instead of 3.

All I get when I make an "if" statement is errors about the for loop not closing.

    {% if craft.request.isMobileBrowser %}
        {% for batch in craft.entries.section('afval')|batch(2) %}
    {% else %}
        {% for batch in craft.entries.section('afval')|batch(3) %}
    {% endif %}
    lots of content here...
    {% endfor %}

So how can I get the loop to go in 2 entries per batch instead of 3 when reached "col-sm"(bootstrap) or atleast when a mobile device is detected.


texts: Find category through ajax using ElementCriteriaModel

texts:
I'm trying to run a controller action with ajax in a new plugin I'm making.
The action needs to return all categories from a group, so nothing impossible here.

When I run the actionUrl in the browser I get the wanted result: an array with the titles of all categories in a group.

But when I call this action while using ajax it results in an empty array.

Ajax call

 $.ajax({
        url: Craft.getActionUrl('AddEntriesFilter/Index/GetCategories'),
        context: document.body,
        success: function(response) {
            console.log(response);
        }
});

Action in controller

public function actionGetCategories()
{
    $criteria = craft()->elements->getCriteria(ElementType::Category);
    $criteria->group = 'myCategoryHandle';

    $cats = $criteria->find();

    $regions = array();
    foreach ($cats as $cat)
    {
        $regions[] = $cat->title;
    }

     $this->returnJson($regions);
}

To test this, I tried to Craft::dd($cats); and this is already empty.

I also tried to Craft::dd($criteria->count()); and this also gives different results in the ajax call and in the browser. The ajax call returns 0 and the browser returns the wanted result.

After logging the attributes of $criteria I discovered $criteria->find()is adding a relatedTo attribute. It only does this when running it through Ajax.

Thanks!


texts: How to add pagination to a filtered category output?

texts:
I've been able to successfully filter a set of entries by category, and also include pagination for the complete set of entries (in this case so 6 are displayed per page).  But once a category filter is applied the pagination does not affect the filtered output, so for example, if a filter is applied that results in only 1 entry being displayed the pagination controls still show 2 pages (for 12 entries in total).  Then clicking on previous/next page (which of course users are bound to do!) re-sets the filter to show all results.

I can't work out a solution....  :(

If someone could please have a look and suggest a solution I would be very grateful!

Many thanks.

{% if craft.request.getParam('category') is not null %}

  {% set category = craft.categories.slug(craft.request.getParam('category')) %}
  {% paginate craft.entries.section('caseStudies').relatedTo(category).limit(6) as pageInfo, casestudies %}

{% else %}

  {% set casestudies = craft.entries.section('caseStudies').find() %}
  {% paginate craft.entries.section('caseStudies').limit(6) as pageInfo, casestudies %}

{% endif %}

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

{{ category.title}}

  {% endfor %}

All Types

{% for casestudy in casestudies %}

    {% set photo = casestudy.caseStudyImage.first() %}
    {% if photo %}

    {% endif %}

{{ casestudy.title}}

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

{% endfor %}

  {% if pageInfo.prevUrl %}

{% endif %}

  {% for page, url in pageInfo.getPrevUrls() %}
{{ page }}
{% endfor %}

{{ pageInfo.currentPage }}

  {% for page, url in pageInfo.getNextUrls() %}
{{ page }}
{% endfor %}

  {% if pageInfo.nextUrl %}

{% endif %}


texts: How to get name of template that was chosen for request?

texts:
For convenience it would be rather useful if there was a way for me to achieve the following inside my main layout template:

<body class="template--{{ getNameOfPageTemplateHere|replace({ '/':'-', '_':'' }) }}">

Such that a page rendered using the template "blog/_entry" would have the following body tag:

<body class="template--blog-entry">

Is this possible?


texts: What would cause an Internal Server Error on saving entry

texts:
When I try to save a new entry as a child under a Structure entry, I get the following error:

  Internal Server Error

  Object of class Craft\ElementCriteriaModel could not be converted to
  string

I also get the same error when I tried to move it out to it's own Channel instead, so I am not sure what could be causing it.

I have several fields in this entry, most notably the cause would be an Entries field and Tags field. Both seem to select the correct values fine.


texts: Asset thumbs missing in control panel after Assets Source update

texts:
I've updated several Assets Sources on my production site. I've exported / imported the database from production into local - the new Assets Sources are in place but the asset thumbs are now missing.

How can I get Craft to re-generate these please?


texts:
My client has an online store that we are building with 10 or so products. They will also have a high street store which sells the exact same products.

Is it possible to integrate Craft Commerce with POS (Squareup or iZettle ) software so the stock levels are kept up to date?


texts: Is using nested extends a wise idea or will it be a performance/maintenance nightmare?

texts:
Here's a basic example of using nested extends in Twig. I figured this is a probably common use-case. You have a very general _layout.html that contains your common CSS, JS, meta tags, etc.

{# _layout.html #}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>{{title}}</title>

  {% block content %}{% endblock %}

Then you have a _subpage.html template that shapes the way all your subpages should look (main content area, sidebar, etc).

{# _subpage.html #}
{% extends "_layout" %}

{% block content %}

    {% block subpageContent %}{% endblock %}

    {% block subpageSidebar %}{% endblock %}

{% endblock %}

Now I extend that _subpage.html in about.html and grab the blocks that belong to the _subpage.html template.

{# about.html #}
{% extends "_subpage" %}
{% set title = "About" %}

{% block subpageContent %}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate suscipit, debitis accusantium tenetur impedit, veritatis id placeat, dolor hic temporibus architecto quas atque sunt officiis corrupti voluptatibus expedita. Assumenda!

{% endblock %}

{% block subpageSidebar %}

Subpage Link 1

Subpage Link 2

Subpage Link 3

{% endblock %}

Now I realize you can use nested extends in Twig, but I'm entirely sure if I should. Is this a maintenance nightmare? Does it take a performance hit to do this? What's the best practice for template relationships?


texts: Route to Controller action (not in a plugin)

texts:
Let's say i have a FooController extending Craft\BaseController located somewhere else (not in a plugin). The FooController is autoloaded via composer and the autoload.php is included in public/index.php

Would there be a way to route to this FooController? Is it not possible with Craft (or Yii) to just say something laravel like: Route::get('foo/bar', 'FooController@bar')?

Edit (follow up question):
If I have something like this in my registerSiteRoutes function:

 return [
     'foo/bar' => ['action' => 'plugin/foo/bar', 'additional' => 'acme'],
 ];

Would I be able to access the 'additional' information in the controller?


texts:
I have a form created with AM forms that on submission does nothing. It doesn't go to the redirect url and nothing is saved to the database. Not sure what I am missing.

Here is my simplified code:

{% set form = craft.amForms.getForm('clubMembershipApplication') %}

<form method="post" accept-charset="UTF-8" class="form-horizontal col-sm-8 col-sm-offset-2 bv-form">
  {{ getCsrfInput() }}

  {# This should always be here! #}
  <input type="hidden" name="action" value="amForms/submissions/saveSubmission">

  {# Insert your forms handle. #}
  <input type="hidden" name="handle" value="{{ form.handle }}">

  {# Optional: Redirect URL. Will redirect to current page by default. #}
  <input type="hidden" name="redirect" value="membership/thankyou">

  various fields here

  <div class="submit-btn-container col-sm-8 col-sm-offset-4">
      <input type="submit" value="Submit" class="solo-btn btn">
  </div>
</form>


texts: Search/Filter Freeform submissions by field value

texts:
I need to be able to get a count (in the frontend) of the number of submissions that have a field with a specific value. I don't need the submitted data of the submissions, just the count of submissions whose data matches a specified value.

This code returns the total number of submissions:

{% set submissionCount = craft.freeform.submissions({
    form: 'myAmazingForm'
}).count %}

I tried using the native Craft search parameter, but it returns zero:

{% set submissionCount = craft.freeform.submissions({
    form: 'myAmazingForm'
}).search('fieldWithValue:123').count %}

And yes, there are submissions that would match that.

How can I do this?


texts:
Coming from a Yii2 background, I am accustomed to doing things in an MVC way.

I have set up a demo Craft CMS application to have a play around with. I've created a "singles" page (homepage) and got it displaying data. What I want to know is, how do I pass custom variables to the view?

For example I have a function that fetches tweets from my Twitter account, I would like this data to be displayed on the homepage. In Yii2 I would normally do the following:

<?php

namespace app\controllers;

use yii\web\Controller;
use app\services\TwitterFeedService;

class SiteController extends Controller
{
    public function index()
    {
        $twitterFeed = TwitterFeedService::getTweets();

        return $this->render('index', [
            'twitterFeed' => $twitterFeed,
        ]);
    }
}

But since there is no controller or action for my homepage at the moment, I am not sure how I would go about doing this in Craft CMS.


texts: Problem getting relationship between entries to work

texts:
I'm having trouble getting what should be a simple relationship between 2 channels to work as expected.

This is how things are set up.

Channel: Apprenticeships - essentially categories, types of apprenticeship (health, construction, catering etc)

Channel: Vacancies - individual apprenticeship courses  - each one related to an Apprenticehips entry.

In my template I can show a list of all Vacancy entries with

{% set vacancies = craft.entries.section("vacancies").find() %}

Then loop through them and output field data. This works fine and shows all the vacancy entries.

But I want to be able to filter the entries returned to those that are related to a specific Apprenticeships entry. This filtering is to be based on the third url segment, which is the slug of the Apprenticeship entry.

{% for cat in craft.entries.title(craft.entries.slug(craft.request.segment(3)).limit(1).find()) %}

This works fine and I can output field data from that Apprenticeship entry. Proving, in my mind, that Craft knows which entry I want.

To get only the Vacancy entries that are related to the Apprenticeship entry represented by cat I thought I could simply use 'cat' in another craft.entries tag.

{% set vacancies = craft.entries.section("vacancies").relatedTo(cat) %}

Then loop through vacancies outputting the vacancy field data. But it doesn't return any Vacancy entries even though there definitely some to return.

Where am I going wrong here?


texts:
I want to install Craft in home directory in mac. I don't like to use MAMP as local server.

Is to possible to install without using MAMP? I use gulp and webpack in home directory.


texts: How to set field values for the table field type in Craft 3

texts:
I'm trying to insert an entry along with values for a table field. According to the docs, the setFieldValues method takes an array of values in the format handle => value, but it doesn't specify how the value should be formatted for each field type.

Here's my best guess at how it might work for the table field:

$entry = new Entry();
$entry->sectionId = 1;
$entry->typeId = 1;
$entry->title = $title;
$entry->setFieldValues([
  "field_handle" => [
    ["column_1_handle" => "hello", "column_2_handle" => "world"], // Row 1
    ["column_1_handle" => "more", "column_2_handle" => "stuff"] // Row 2
  ]
]);

This inserts the correct number of rows into the table field, but the values are empty, so I'm guessing I'm structuring the array incorrectly.

Any ideas?


texts: Showing entries based on parameters that may or may not be populated

texts:
I'm using a Matrix Field to display lists of entries. One extracts entries based on certain categories. They may or may not be set, but I need to use an "and" relatedTo parameter. At the moment it uses the default "or" option. Any suggestions on how I can be smarter about this?

The Code is currently as such:

{% set country = block.countryCategory %}
{% set location = block.locationCategory %}
{% set person = block.personCategory %}
{% set role = block.roleCategory %}

{% set categories = craft.categories.group(block.category).relatedTo(country, location, person, role).find() %}


texts: How do I render specific child entries of a structure based on url segment

texts:
For simplicity, I'm building a site for a restaurant. The "Menu" page has the following url(s):

mysite.com/food/appetizers
mysite.com/food/sandwiches

food is a structure. It contains every entree the restaurant has. I've nested the actual entree to under the corresponding category. For example:

mysite.com/food/appetizers
                         /cheese-curds
                         /french-fries

mysite.com/food/sandwiches
                        /whole-sandwich
                        /half-sandwich

..and so on.

On mysite.com/food/ I can render all entrees under thier corresponding category like this:

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

 {% for entry in entries %}
       {% if entry.type == 'category' %}

{{ entry.title }}

       {% endif %}

       {% set children = entry.getChildren() %}
       {% for child in children %}

{{ child.title }}

       {% endfor %}
 {% endfor %}

Everything is working great. All entrees are listed below their corresponding "category" on my /food/ page. I can click on each individual entree "cheese-curds" for example, and can get the entry details.

For templates I have _entry and index.

index is used on mysite.com/food _entry is used on each entree.

Where I'm stuck is how to render the entries for the current category. For example:

mysite.com/food/appetizers

I'm not sure How to get past my initial command of getting ALL entires:

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

 {% for entry in entries %}
       {% if entry.type == 'category' %}
       ....
       ....

To only this:

{% if entry.type == 'category' %}
  ....
  ....

So that I am only listing out the entries for the current category. It's OK if I need to create a new template, I'm not sure how to tell Craft how to do that. Or is there a better approach to getting all entries for the structure? It seems simple enough in theory, I keep talking myself in circles.

EDIT

Thank you @j00lz
Your solution makes perfect sense. I think I either don't quite understand, or I'm still at the same spot I was before.

{% switch entry.level %}
    {% case 1 %}
        {# this is mysite.com/food #}
        {# outputs #}
        Appetizers
            Cheese Curds
            French Fries
        Sandwiches
            Sandwich One
            Sandwich Two
    {% case 2 %}
        {# this is mysite.com/food/appetizers
        {# outputs #}
        Appetizers
            Cheese Curds
            French Fries
    {% case 3 %}
        {# this is mysite.com/food/appetizers/french-fries
        {# outputs #}
            French Fries
            French fries are awesome!
{% endswitch %}

So, it's like I need another template to only show the 2nd case on the page.
I can list all foods, and the actual entrée (3rd case) using 2 templates. I'm hung up on that middle page where it would only list the title of the entrée, and then the children entrée.

I thought about putting an if statement at the top of the page that checks the URL level. If it's only /food/ do "x", if its /food/appetizers do "y", but that seems to assume an awful lot.

Maybe there is a better route to go all together. I only had a structure in mind because of the nested elements that I wanted to be able to control where they were.


texts: How to set url of delete button of editableTableField?

texts:
As title says, I have a URL which I need to call when someone clicks on delete button. I already have a primary key which I need to set and append in delete URL. How'd I do that?

Update

Rows are being generated as:

{% if posts is defined %}
    {% for post in posts %}
        {% set rows = rows|merge([
        [
            post['scheduledTime'],
            post['URL']
        ]
        ])
    %}
        {% set index = index+1 %}
    {% endfor %}
{% endif %}


texts: Some (but not all) controller action routes return 404 on staging server

texts:
I've created a module for a project that has several actions, all of which are called through AJAX. Each is a post request that sends over any required params plus the CSRF token using the method described here: https://craftcms.com/guides/enabling-csrf-protection#updating-your-javascript

On localhost, everything works correctly. On the staging server, some work correctly but others return a 404 error. Specifically, the response gives "Template not found: actions/module-name/location/geocode-inputs".

web.log doesn't look to be throwing any errors, and I'm not sure where else to look. Any ideas on what might be going wrong?


texts: Plugin that lets user select focal point/cropped area

texts:
I would like to let the editor of a specific entry select the focal point and cropped area each time she selects an asset for an asset field.

How can I achieve that?

I know about the built in focal point function in Craft CMS 3 that lets me edit one asset and set a focal point - but what I want is:

Let the user select focal point each time an asset is selected
If the asset field has a fixed aspect ratio, let the user select specifically which portion of the image should become the cropped version.

Like this:

I found a plugin called Ansel, which seems to let me do what I want. My question is if there is another way - or built in way to achieve what I want?


texts: Display Items in customer order in a particular order

texts: Is there a way to sort the customer items by item number under commerce customer orders in the control panel?


texts: How to return asset from custom user field

texts:
In Craft 3, one of my 'User' fields is an assets type field with one selectable asset ('profilePicture').

I have routing setup to load my template when a url looks like:

domain.com/person/firstname-lastname

In my template I am getting the appropriate user with:

{% set secondSegment = craft.request.getSegment(2) %}

{% set people = craft.users.group('family') %}

{% for person in people %}
    {% set personName = person.firstName|lower ~ "-" ~ person.lastName|lower %}
    {% if secondSegment == personName %}
        {% set currentUser = person %}
    {% endif %}
{% endfor %}

All that works - I can query most fields, but I can't work out how to get my asset.

Works:

{{ currentUser.myTextField }}

None of these work (returns nothing and no error):

1.

{{ currentUser.profilePicture[0].url }}

2.

{% set asset = currentUser.profilePicture.first() %}

{% if asset %}
    {{ asset.getUrl }}
{% endif %}

3.

{% for asset in currentUser.profilePicture %}
    {{ asset.getUrl }}
{% endfor %}


texts: Impossible to invoke a method ("limit") on an array... but it's not an array?

texts:
I am receiving the error message "Impossible to invoke a method ("limit") on an array," but I don't think I am working with an array! Here is why I think that...

First I set an albums variable:

{% set albums = craft.entries.section('townAlbums').with(['townPhotoAlbum']).relatedTo(entry) %}

Then I loop through that object. I'm not calling .all(), so this is still an object, right?

{% for album in albums %}

Finally within this loop I am grabbing one image from the assets field townPhotoAlbum to use as a thumbnail or cover image for this album:

{% set albumCover = album.townPhotoAlbum.limit(1) %}

Why is it complaining about using .limit() on an array when it appears as though I'm still working with an object? Or am I overlooking something woefully obvious?

Thanks!


texts: The difference between username and loginName

texts:
In the examples they're used mixed:

Registration

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

Login

 <input id="loginName" type="text" name="loginName"
    value="{{ craft.session.rememberedUsername }}">

For the login form, a field named "username" can not be used, it should be "loginName". What is the difference between the two?


texts: How do I pass custom field contents from cart to order

texts:
cart.billingAddress and cart.shippingAddress are both are set to the same address and include custom1 and custom2 fields.

After submitting the order, order.shippingAddress and order.billingAddress have all the correct address information from cart except custom1 and custom2 which are blank.

This is a slightly simplified version of my payment submission form. It's using the manual gateway, no money is taken and the order is set with a status "Payment Pending" and paid status "Unpaid". Invoices are paid elsewhere for now.

<form method="POST">

  {{ csrfInput() }}

  {{ redirectInput('/account/invoice?number='~cart.number) }}
  <input type="hidden" name="action" value="commerce/payments/pay"/>
  <input type="hidden" name="gatewayId" value="2"/>
  <input type="hidden" name="savePaymentSource" value="0" />

  <button type="submit" class="button">Confirm order and generate invoice</button>

</form>

Why isn't the information in the fields custom1 and custom2 being set on the order addresses?


texts: Can anyone confirm if I want to pull back a list of all entries regardless of locale I could do something like craft.entries.locale(null) to get 100% of entries?


texts:
How do I replace ";" with "," in string "Red; Green; Blue"?

{% set rgb = "Red; Green; Blue" %}


texts: How to handle Craft 3 events in a plugin? Element API is returning null data

texts:
The below refers to Craft 3 and the Element API plugin for Craft 3.

I would like to do something when the Element API plugin fires its onBeforeSendData event, I can see in the controller for element there is this:

$this->trigger(self::EVENT_BEFORE_SEND_DATA, new DataEvent([
    'data' => $data,
]));

And based on Craft 3 docs and Yii 2 docs I think I would use the following in my plugins init function:

Event::on(ElementController::class, ElementController::EVENT_BEFORE_SEND_DATA, function(DataEvent $event) {
    var_dump($event->data);
}

I would have expected that to return a League\Fractal\Scope object but instead I am just getting null. Have I implemented this correctly?

Interestingly while trying to work out where I went wrong, if I modify the Element API DefaultController class and change the data property in the trigger to eventData and add the new public property to the DataEvent class then it all works and I am able to see the data in my plugin.


texts:
Our client is a builder and they need a way for their contractors to login and upload/download documents about each build (plans, building consents, information etc). They (the builder) also need a way to share build information with their clients whose homes they're building (plans, progress, photos etc.).

Ideally:

contractors would be able to log in and we'd present them with a front-end page listing their projects, view the projects' files and maybe allow them to upload files? We want to be able to restrict the contractors only to builds that they're working on. If absolutely necessary it might be ok if the contractors needed to upload files through the CP rather than the front-end.
clients would be able to log in to a front-end page and see their build(s) and any files that the contractors/builder had uploaded and made visible to them. they shouldn't be able to view other clients' builds' information.

Is it possible to do this with vanilla Craft, or would we have to write a plugin to enable us to do this?

How easy is it to associate a user/users/groups with entries/asset sources?


texts: Very slow `INSERT` transactions on the resourcepaths table

texts:
After a recent update (Craft 3.4.x to 3.5.x) I'm seeing some suspiciously slow response times in relation to INSERT actions on the resourcepaths table. Some in the upwards of a half second for a single transaction.
Has anyone ever encountered this before? One note, this is hosted on a load-balanced environment so I'm not sure if this plays into this (if at all).


texts: How can I override the language and locale before rendering a template?

texts: I render a template by a controller and it supposed to be rendered by a specific language and locale formatting regardless of current user's language or locale. Is it possible to override the language and formatting before rendering the template?


texts: Allow CP sorting on an added EntryTableAttribute

texts:
I am adding a column to the entry table with links to reverse related entries:

    public function defineAdditionalEntryTableAttributes()
    {
        return array(
            'blockParent' => Craft::t('Parent'),
        );
    }

public function getEntryTableAttributeHtml(EntryModel $entry, $attribute)
{
    switch ($attribute)
    {
        case 'blockParent':
        {
            $criteria = craft()->elements->getCriteria(ElementType::Entry, [
                'relatedTo' => [
                    'targetElement' => $entry,
                    'field' => 'contentSections.blocks',
                ]
            ]);

            $html = '';

            foreach ($criteria as $entry) {
                $html .= craft()->templates->render('_elements/element', array(
                    'element' => $entry,
                ));
            }

            return $html;
        }

    }
}

Works great. Only I want to make the column sortable (based on the title of the first entry of each).

Is there a way to sort on these types of added columns? modifyEntrySortableAttributes seems to only work on real attributes, not added ones.


texts: Controlling where user is sent if clicking old or expired email activation link

texts: When a user visits on an old or expired email activation link, how do we control which page is loaded? In my case it's rendering a template named error.twig, but I'm not sure how that's set or where to change it.


texts: Craft 3 replacement for the Craft 2 fileCache component?

texts:
I'm upgrading a plugin from Craft 2 to Craft 3 and it looks like the fileCache component is no more.

What has replaced it in Craft 3?


texts: Using modifyElementsQuery() to build a Radius Search?

texts:
I am looking to build a radius search from my field type’s modifyElementsQuery() method.

I am storing lat/lng values in a separate table, and am trying to integrate the location search based on the following:

https://developers.google.com/maps/articles/phpsqlsearch_v3?csw=1#findnearsql

Here’s my current code. It throws an error saying "unknown column 'distance' in having clause".

public function modifyElementsQuery(DbCommand $query, $value)
{

    if($value !== null)
    {
        $settings = $this->getSettings();
        $this->plugin->pluginLog($value);

        $unitAdjustment = $settings->unit == 'mi' ? 3959 : 6371;
        $lat = 37;
        $lng = -122;
        $radius = $value;

        $query->addSelect('( '.$unitAdjustment.' * acos( cos( radians( '.$lat.' ) ) * cos( radians( fruit_geo.lat ) ) * cos( radians( fruit_geo.lng ) - radians( '.$lng.' ) ) + sin( radians( '.$lat.' ) ) * sin( radians( fruit_geo.lat ) ) ) ) as distance');
        $query->join('fruit_geo fruit_geo', 'fruit_geo.elementId = content.elementId');
        $query->having('distance < '.$radius);

        // Here's the SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate.
        // It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude,
        // and then asks for only rows where the distance value is less than 25, orders the whole query by distance,
        // and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371

        //SELECT id, ( $unitAdjustment * acos( cos( radians( $lat ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( $lng ) ) + sin( radians( $lat ) ) * sin( radians( lat ) ) ) ) AS distance FROM table HAVING distance < $radius
    }

}

Template errors:

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'distance' in 'having clause'. The SQL statement executed was: SELECT `elements`.`id`
FROM `craft_elements` `elements`
JOIN `craft_elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id
JOIN `craft_content` `content` ON content.elementId = elements.id
JOIN `craft_fruit_geo` `fruit_geo` ON fruit_geo.elementId = content.elementId
JOIN `craft_entries` `entries` ON entries.id = elements.id
JOIN `craft_sections` `sections` ON sections.id = entries.sectionId
LEFT JOIN `craft_structures` `structures` ON structures.id = sections.structureId
LEFT JOIN `craft_structureelements` `structureelements` ON (structureelements.structureId = structures.id) AND (structureelements.elementId = entries.id)
WHERE (((((((elements_i18n.locale = :locale) AND (content.locale = :locale)) AND (elements.archived = 0)) AND ((elements.enabled = 1) AND (elements_i18n.enabled = 1) AND (entries.postDate <= '2015-02-06 11:57:46') AND ((entries.expiryDate is null) OR (entries.expiryDate > '2015-02-06 11:57:46')))) AND (elements_i18n.enabled = 1)) AND (content.field_date>=:contentfield_date1)) AND (sections.handle=:sectionshandle1)) AND (`elements`.`id` IN ('5747', '5823', '8529', '8865', '8913', '8972', '8973', '8978', '8979', '10228', '10370', '10912', '11780', '13366', '14673', '14675', '14759', '14764', '14770', '20516', '20682', '20683', '21042', '21043', '21143', '22247', '22570', '22814', '22817', '22827', '22830', '22834', '22835', '22836', '22844', '22855', '22859', '22860', '22867', '22899', '22909', '22916', '22945', '22970'))
GROUP BY `elements`.`id`
HAVING distance < 50
ORDER BY `field_date` ASC. Bound with :locale='en_gb', :contentfield_date1='2015-02-06 00:00:00', :sectionshandle1='events' (/var/www/vhosts/findarace.com/beta.findarace.com/craft/app/framework/db/CDbCommand.php:543)

#0 /var/www/vhosts/findarace.com/beta.findarace.com/craft/app/framework/db/CDbCommand.php(396): CDbCommand->queryInternal('fetchAll', Array, Array)


texts: Get entries related to selected category only and not it's ancestors

texts:
The following is using commerce product entries, but I'm reasonably sure it could be any entry.

With the following category taxonomy:

- Category 1
    - Category 1A
- Category 2
- Category 3
...

If I have a product entry "Product 1" with a category field selected to "Category 1A", when looping though
all categories to return products for that category, how can I list the entry ONLY for "Category 1A" and not it's any of its ancestors e.g. "Category 1"?

Currently, I'm using the following:

{% nav category in productCategories %}

        {{ category.title }}
        {% set products = craft.products().relatedTo(category).all() %}
        {% for product in products %}
            {{ product.title }}
        {% endfor %}
        {% ifchildren %}

                {% children %}

        {% endifchildren %}

{% endnav %}

Which returns

- Category 1
    Product 1
    - Category 1A
        Product 1
- Category 2
- Category 3
...

But what I want is for it to only be visible on the selected category.

- Category 1
    - Category 1A
        Product 1
- Category 2
- Category 3
...

Is there a way to do this using categories? or am I best using a structure?


texts: 413 “Request Entity Too Large” error with uploading a file

texts:
In assets when uploading a medium size file I get this error:

  Failed to load resource: the server responded with a status of 413 (Request Entity Too Large)

What does it mean? And how to fix?


texts: Email template issue Craft Contact Form Extensions

texts:
I am using Contact Form Extensions plugin https://github.com/Rias500/craft-contact-form-extensions for setting up custom notification email template but not sure what tag would be used for additional fields like Phone.
Here is my code sample:

Name: {{ submission.fromName }}

Company: {{ submission.Company }}

Name: {{ submission.fromEmail }}

Phone: {{ submission.Phone }}

Type of Enquiry: {{ submission.typeOfEnquiry }}

Message: {{ submission.message }}

Could anyone please help.


texts: Exporting site configurations for import to new websites - separate databases

texts: Is it possible to export the site configurations of one website in terms of the site structures, not the content, for importing into another site with a separate database, essentially creating a site installation profile, similar to that possible in Drupal?


texts: Modelling flexible content sections and recommendations

texts:
A little background first; I'm coming from WordPress, along with the Advanced custom fields (ACF) plugin, so my thinking behind this may not be the best way in Craft.

In ACF I usually set up a field set that consists of an outer repeater field, with a nested flexible content field inside (much like the Matrix field in Craft). Within the repeat field, there are a couple of options that controls the appearance of a section, such as a background colour/image. This is also used in my template to differentiate where a <section> starts and ends, and often has styles associated to style the overall section. Anything within the flexible content fields is contained within this.

Then, within the flexible content field, I define my layout types (title block, two column text, text with image, etc.). An image to describe the layout structure if my description is a little confusing:

I'm looking to create a similar sort of set up with Craft. Without an outer repeater field, I'm struggling to think how to achieve the "section" container. What would be a way to achieve this sort of thing?

Thanks!


texts:
We are running Craft on a site that gets a decent level of traffic, thousands of hits per day. We are running craft caching to try and keep things quick. The caching tables have been growing significantly over the past few days and don't appear to be clearing out. These are the three tables and the row counts. 1+ million rows in two of them.

| craft_templatecaches                |      34685 |
| craft_templatecachecriteria         |    1197874 |
| craft_templatecacheelements         |    1364424 |

Any ideas on why these tables would be growing so large and why they don't appear to be removing any old rows?


texts: Event or hook when user account email validated

texts:
Is there an event or hook we can leverage after a user verifies their email address? It looks like this is handled in UsersController::actionVerifyEmail() which calls $this->_onAfterActivateUser which calls $this->_redirectUserAfterAccountActivation. The specific users being created will not have CP access, so they will be redirected to craft()->config->getLocalized('activateAccountSuccessPath') in that method.

I would like to be able to set a flash message to confirm the email verification and informing them they need to log in to access all of the site, but I don't see any events or hooks to tie into. Any suggestions?


texts: What is the best way to handle Events that get triggered during a migration?

texts:
We have a Form plugin and an Email plugin.  Users can setup the Email Plugin to send off notification emails when a particular Event happens.   Some users setup a notification email to be sent when a Form is submitted from the Form plugin.

In a recent upgrade, we needed to migrate all content to the Form plugins entries table.  We did so using the saveFormEntry method in the Form plugin service layer.  This means, that each time that we call saveFormEntry in the migration, if somebody has the Email plugin to send out a notification when a Form Entry is saved, the Event fires and the Email plugin tries to do it's thing.

In our case, this just killed the migration script. Setting the Email plugin to disabled before running the Form migration get's around the issue.

So, what is the best way to handle Events that get triggered during a migration?

One method we've thought of is to just programmatically set the Email plugin to disabled before running our migration.  That might work for us, but what if other plugins need to do the same?  Do we then need to somehow try to communicate this to everyone who might trigger an email event in a migration?

Another idea we've discussed is what if Craft had something like devMode for while migrations were running.  So we could just plan into our Email plugin to only run events when migrationMode = false.

As a general question, are there any benefits to having Events enabled during migrations?  Are there any benefits to having plugins enabled during migrations?  I'm sure this isn't simply a black and white question, but I'm new to thinking about the complexity of having multiple plugins triggering behaviors in other plugins and don't really like the idea that somebody could accidentally trigger several emails to be sent out while trying to run a migration.

Any thoughts on where this is best handled and if we can take any steps to make our code more robust in handling scenarios like these would be appreciated.


texts: If merging two sections from different locales how do I then sort them by a shared criteria?

texts:
I've got a site with multiple locales and I want to merge together content from across these locales, eg News.

The two sections share the same fields so should theoretically be able to be sorted by a shared criteria.

Looking at the post at How do I sort a collection of entries from multiple sections by date? I can merge these both into a single array but when I try to post the ids from these into a new query (to sort the results) only one set of results are returned.

Sample code:

{% set ids = craft.entries.section('news' ~ Section).relatedTo(active).ids() %}
{% set mergeIds = craft.entries.section('newsAlumni').status(null).locale('prior_alum').search('shareNewsAlumni:1').localeEnabled(false).ids() %}
{% set ids = ids|merge(mergeIds) %}

{% set news = craft.entries.id(ids).localeEnabled(false).status(null).order(['stickyNews desc','postDate desc']).ids() %}

If I dump the results of ids I get:

295484 | 3747 | 1787 | 1783 | 1781 | 1778 | 638 | 636 | 640 | 295486

295486 being the entry from mergeIds being returned.
However, if I dump the results of news I get:

295484 | 3747 | 1787 | 1783 | 1781 | 1778 | 638 | 636 | 640

Leaving out the result from mergeIds.
Any thoughts on why the entries from mergeIds are not being included in the resulting news object?

Ta

Cole


texts: Loading dynamically-named classes in a plugin's service

texts:
I'm in the process of building a plugin that'll have extensible 'Providers' to allow developers to build connections to other services. These 'Providers' will just be classes that are built to an interface I've included in the plugin. (It's currently in an 'interfaces' directory of my plugin; I'm not sure about the best-practice for where interfaces should be stored.)

My question: What I'm having trouble with is how to include the developer's Provider class when I don't know what the name will be. Here's what I'm doing now:

require_once(CRAFT_PLUGINS_PATH . 'location/providers/' . $this->settings->provider . 'Provider.php');

$provider = '\Craft\\' . $this->settings->provider . 'Provider';

return new $provider();

$this->settings->provider just returns the 'handle' of their Provider, like sampleService. The file they place in the providers directory would be sampleServiceProvider.php, in that case.

If something doesn't make sense, I'll gladly clarify. Any help is greatly appreciated!


texts: Filter entry query by a custom field value

texts:
I have a channel, 'pages'. Within that channel is a dropdown 'navigation'. The values in the dropdown are 'mainNavigation' and 'hidden'.
I'm trying to set an entry query that only pulls entries where the navigation value is 'mainNavigation'.
This is the code I'm using, and I'm getting no results:
{% set nav = craft.entries.section('pages').search('navigation:"mainNavigation"').all() %}
{% for link in nav %}
    {{link.title}}
{% endfor %}

I know this should work. I've done it before. I copied the working code from another site, and copied the field name and value directly from the CP. I've stripped everything else out of the template. But no matter what I do, I get no results.
Has this functionality changed recently?


texts: How can I tell Smart Map to look at Commerce for entries?

texts:
I have Smart Map working perfectly within Commerce. Meaning, I am able to show a map, etc. when I'm looking at products.

However, I am trying to build a "product locator" to find products in my area.

I am able to successfully pass the arguments to my results page - I can print out the zip code and distance that was chosen, but I am always getting into my "no results found" case.

{% set target = craft.request.getParam('near') %}
{% set radius = (craft.request.getParam('radius')) craft.request.getParam('radius') : 200 %}
    {% set params = {
    'target': target,
    'range': radius
} %}

{% set entries = craft.entries.address(params).order('distance').find() %}

radius is a drop-down of (miles) to choose from.
near is the name of the text input the user enters the zip.


texts: ElementAPI: How to trigger the Custom service php file when a endpoint is loaded

texts:
I am Using Craft 3.3.11 version

I have a php file in

  plugin/elementapi/src/services/EapiServices.php

and the same file within

  vendor/craftcms/element-api/src/services/EapiServices.php

When I hit the http://localhost:9001/index.php/api/news.json
EapiServices.php from vendor folder is triggered instead of EapiServices.php file from plugin folder.

Can someone help to to make the services files to work within the plugin directory?


texts: User confirmation email not being received by hotmail?

texts: Has anyone experienced any issues with hotmail not receiving user confirmation emails? Our site is set up on a staging server and confirmation emails seem to work for all other email addresses we have tested apart from hotmail. Can't see anything in the logs that would suggest any problem.


texts: Commerce Product - show shipping category in template

texts: I have setup some Shipping Categories (8 weeks, 4 weeks etc) and these appear down the side bar of a product when editing in admin next to 'Shipping' . How do i bring this value out via a tag on a product page/template?


texts: Does anyone have an idea how to contact Solspace support? The email seems to be dead for about a week now.