texts: Just upgraded to Craft 3.5+ the pages are cached (instant load on a 2nd run) but the templatecaches and similar tables are empty. How exactly does it work now? How do I flush cache for 1 specific page since it's not possible to see the rows in db?


texts: What's left to troubleshoot this quirky "Unable to verify your data submission" behavior?

texts:
I have a frontend login form that sends a request to Craft's own actions/users/login action. I've used this same process in another project and it works there, but not here, and I can't figure out what might be different.

After entering username and password to my form and submitting it, I get the 400 Bad Request error page with "Unable to verify your data submission." When I look at the login request in the browser's network tab I can see it has a CSRF value.

One of the weirdest things about this is that sometimes I can click the "back" button and voila, I will be logged in! I haven't been able to tell what's different when I sometimes get a 200 status and other times where I get a "cancelled" status. No matter what the status is, I always get that "Unable to verify your data submission" error page.

Here is my frontend login method:

login() {
  if (!this.loginName || !this.password) {
    this.error = "Enter a username and/or password";

    return;
  }

  const config = {
    headers: {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    }
  };

  const data = qs.stringify({
    loginName:  this.loginName,
    password:   this.password,
    rememberMe: this.rememberMe
  });

  axios
    .post("/actions/users/login", data, config)
    .then(response => {
      console.log(response)
      if (response.data.errorCode === "invalid_credentials") {
        this.loggingIn = false;
        this.error = response.data.error;

        return;
      }

      if (response.data.success) {
        console.log(response);
      }
    })
    .catch(console.error);
}

My axios utility:

import axios from 'axios';

export default axios.create({
  headers: {
    'X-CSRF-TOKEN': window.csrfTokenValue
  }
});

And how I am attaching CSRF stuff to the window in my main template:

<script>
    window.timezone = "{{ craft.app.timezone }}";
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
</script>

I'm at my wit's end with this and am unable to figure out how to troubleshoot this further...


texts: Possible to view field handles on entry type field definition page?

texts: When I am configuring the fields for a given entry type, is there a way to see those fields' handles on the same page? I often reference the entry type page to know which fields are associated with a given entry type, but then I have to cross reference the fields page to make sure I'm using the correct handle. Is there a better way to do this?


texts: admin pages loading but not site itself, strange error

texts:
I installed Craft CMS and all seemed great! But the pages are not loading.. So bascially /admin loads but /index.php genrates an error.

In dutch: "Interne Serverfout Craft\EntryModel en zijn behaviors hebben geen method of closure met naam "heading"."

Which translated is something like: "Craft\EntryModel and its behaviours have no method or closure with the name heading"

Any idea what's wrong? Can be server-level..
I run it on a mac mini server, but mysql, php and apache (plus php-modules) are installed, and again, admin works nicely..
best,
Bart


texts: How to route 404 errors for multi-site Craft?

texts: Craft looks for /templates/404 by default. What do you do if you have multiple sites?


texts:
We're doing a rebrand and web overhaul for a Christian camp, retreat, and conference center. A big part of the site is a registration system where people can register for an event, fill out a detailed form with 30+ fields, then pay for registration. The forms will be pretty complex... people can do partial payments (via stripe), and each of the forms (10 or more) will be unique with conditional fields.  We're also hoping to hand off the form creation process to the client afterwards.

The only plugin I know that can handle something like this easily is GravityForms for WordPress, but I don't want to go the WP route. Is there anything like it out there for Craft? Or is Craft still too much in its infancy? Maybe a 3rd party form builder that will integrate nicely w/Craft?

Any help or guidance is appreciated!


texts: Delete / change Status from CP via Ajax (trigger event)

texts:
In a plugin init function I'm listening to entries.saveEntry and entries.deleteEntry. This works perfectly if I'm editing entries from their detail view. If I 'bulk' change or delete entries, these events are not fired. I saw in the SetStatusElementAction class an event called onSetStatus is triggered but how can I listen to it? The same goes with the delete action.

Somehow the following doesn't get triggered for me:

craft()->on('entries.setStatus', function($event){ dd($event); });

What am I missing here?


texts: Access data when posting to controller from front-end

texts:
I'm writing a plugin to notify authors when a Disqus comment is posted. There is a Disqus JS callback you can use to hook into this, so I'm doing the following on the front-end:

this.callbacks.onNewComment = [function(comment) {
  var commentNotification = new window.VIGET.CommentNotification();

  commentNotification.notify('{{ actionUrl("vigetDisqus/notify/notify") }}', comment, {{ entry.id }}, {{ entry.author.id }});
}];

So I am passing the actionUrl of my controller, the comment itself, the entry id, and the author id. This all works perfectly fine, and I am passing it as data along as an AJAX request to the controller.

CommentNotification.prototype = {
  notify: function(actionUrl, comment, entryId, authorId) {
    var data = JSON.stringify({
      comment: comment,
      entryId: entryId,
      authorId: authorId
    });

    xhr({
      uri: actionUrl,
      method: 'POST',
      body: data,
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      }
    }, function(err, resp) {
      console.log(resp.body)
    });
  }
};

How do I access the posted data inside my controller? I thought I could use the getPost method, but I am always getting null.

<?php
namespace Craft;

class VigetDisqus_NotifyController extends BaseController
{
    protected $allowAnonymous = true;

    public function actionNotify()
    {
        $this->requirePostRequest();
        $this->requireAjaxRequest();

        $authorId = craft()->request->getPost('authorId');

        $this->returnJson(array('authorId' => $authorId));
    }
}


texts: Entry field not outputting after {% set... %} code in template

texts:
I have an {entry.footer} field outputting just fine everywhere before {% set entry... %}
Added {% endset %} tags after closing anchor tag and caused an error. Any idea what the issue is?

{% extends "_layout" %}

{% block home_slider %}
{% include 'global/home-slider.html' %}
{% endblock %}

{% block content %}

                                     {{ entry.body }}

                                    {% for block in entry.threeHomepageImages.type('images') %}

                                                    {% if block.image|length %}

                                                    {% endif %}

{{ block.imageTitle }}

                                    {% endfor %}

                                    {% set entry = craft.entries.slug('get-a-quote').first %}
                                    request a quote
                                    {% endset %}

                            {{ entry.footer }}

{% endblock %}


texts: Craft Table/Tabular static entry input field

texts:
Is there a way to set up a Craft CMS entry field to have a table with predefined rows and columns?

I have tried with the native Craft Table field, but it allows users to add rows or edit default values. I thought a combination of Super Table and Craft's own Matrix field might work but it doesn't allow for default values.

Essentially I would like a table of rows with a static number of rows I can loop through with 4 distinct columns. One of which would be labels, the other 3 columns would be user input. Is this possible or is there another way to make this happen in a way that I can loop through? Emphasis on ease of user input for a set number of rows/elements, rich text, and using as few field names/handles as possible.


texts: Pull DateTime field using alternate timezone?

texts:
I have a question regarding populating models, in that I have a DateTime field in my model that I'm pulling / populating from the database. The DateTime value does not include the timezone it was set to when it was stored, its stored in UTC.

I have the original timezone value (Not the same as the CRAFT timezone but the users timezone that actually created the entry) stored in the model attributes as well.

Is there a way I can extend the model so that when the data is populated I can force the correct timezone on the DateTime fields?

I'm pretty sure that Craft is going to convert them to the timezone craft is set to when it pulls it into the model, but I dont want that in this case. I want it set to the TZ stored in the "timeZone" column/attribute...

Example:

Craft Timezone is America/Chicago

The user's timezone is America/New_York

The user selects a date and time and the controller creates the DateTime object with the user's selection, specifying the timezone America/New_Yrok, then tells the model to save, so it stores it in the database.

The Database DateTime value is now stored in UTC.

When I fetch this data and populate a model with it and reference the DateTime object, its going to be in Amercia/Chicago right? since that's what the craft system is set to, right?

So what is the best way to set up the model so it automatically knows to use $this->getAttribute('timeZone') as the timezone for that field rather than the Craft system setting?

EDIT:

This is what I ended up doing that appears to work. I added this to my model:

public static function populateModel($values) {
    $model = PARENT::populateModel($values);

    /** @var $startTime DateTime */
    $startTime = $model->getAttribute('startTime');
    if($startTime) {
        $startTime->setTimezone($model->timeZone);
        $model->setAttribute('startTime', $startTime);
    }
    /** @var $endTime DateTime|null */
    $endTime = $model->getAttribute('endTime');
    if($endTime) {
        $endTime->setTimezone($model->timeZone);
        $model->setAttribute('endTime', $endTime);
    }

    return $model;
}


texts: Search Plus: Target different indices from different environments

texts:
When testing the indexing configuration, it would be nice to specifically target a testing index. I obviously don't want to disrupt the live data while I make some configuration adjustments. In Algolia, I can clone an index, and rename it something like mydata_test.

Is there a way to target different indices from different environments?


texts: Redactor adds  to both image and video embeds, how to style differently

texts:
When video or images are embedded redactor wraps both the iframe and img tags in a .
I've been using the following css to style the iframe to maintain the ratio responsively:
figure {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 25px;
    height: 0;
    margin: .5em 0 1em 0;
}
figure iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100% !important;
    height: 100% !important;
}

But this screws up the embedded images as I don't want the ratio stuff to apply to images.
Is there a simple way to be able differentiate the two?
I used to add a DIV class to a specific embed in CKEditor with a custom config file containing:
CKEDITOR.on( 'instanceReady', function( ev ) {
ev.editor.dataProcessor.htmlFilter.addRules({
    elements: {
        $: function (element) {
            // Add embed_media class name to embedded media
            if (element.name === 'div' && element.children[0].name === 'iframe') {
                element.attributes.class = 'embed_media';
                return element;
            }
        }
    }
});

});


texts: No input file specified - [proxy_fcgi:error] Got error 'Unable to open primary script: [PATH]/html/index.php (No such file or directory)\n'

texts:
I have a peculiar situation that is only happening on the root domain and NOT subdomains.

For example, CraftCMS (2.6.3019) running on Apache with php-fpm works fine on dev.some-domain.tld and test.some-domain.tld, but for www.some-domain.tld it fails with:

In browser:

  No input file specified

In cPanel Apache log (/usr/local/apache/error_log):

  [Fri Aug 03 13:59:12.42352 2018] [proxy_fcgi:error] [pid 31552:tid 132443556343644] [client xxx.xxx.xxx.xxx:55292] AH01071: Got error 'Unable to open primary script: /home/USERNAME/public_html/production/current/html/index.php (No such file or directory)\n'

For identical installations for other subdomains, everything loads up and works great.  There is no difference in .htaccess or otherwise.

The only differential that we can figure must be something with how Apache's handling the root document location or permissions for the root domain... but we're not seeing anything.

For good measure, here's the .htaccess contents (that are identical on the working subdomains and this failing root domain):

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
</IfModule>

<IfModule mod_php5.c>
    php_flag zlib.output_compression on
</IfModule>

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
    Header append Vary User-Agent env=!dont-vary
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
    RewriteCond %{HTTPS} !=on
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
</IfModule>

I thought that perhaps it was the cgi.fix_pathinfo=1 setting for the php.ini, but that also didn't resolve this.

cPanel support is saying it is absolutely a code issue, but we're pretty much convinced it's an Apache / cPanel issue.  It would be nice to have some input on this since this particular incident of No input file specified does not seem to match the others already found here and elsewhere on the web.


texts:
I've got categories setup like this (Parent & Children):

Type
    Tops
    Dresses
    Pants

Colour
    Black
    Red
    Yellow

When I use this in a category filter and choose Dresses and Black, it works fine in terms that it will return entries that are in Dresses and entries that are in Black.

But how can I edit my code so that it returns entries that are ONLY in Dresses and Black (Black Dresses only!)

Below is what I have so far...

{% set productSegmentCategory = craft.categories.slug(craft.request.lastSegment()).first() %}
{% set productCategoriesArray = ['and'] %}

{% set productValues = {
    keywords: craft.request.getParam('keywords'),
    category: craft.request.getParam('category') ? craft.categories.slug(craft.request.getParam('category')) : null,
    order: craft.request.getParam('order') ? craft.request.getParam('order') : 'title asc',
    limit: craft.request.getParam('limit') ? craft.request.getParam('limit') : entryLimit,
} %}

{% set productParameters = {
    search: productValues.keywords,
    order: productValues.order,
    limit: null,
}%}

{% if productSegmentCategory|length %}
    {% set productCategoriesArray = productCategoriesArray|merge([{ targetElement: productSegmentCategory, field: 'productCategories' }]) %}
{% endif %}

{% if productValues.category|length %}
    {% set productCategoriesArray = productCategoriesArray|merge([{ targetElement: productValues.category, field: 'productCategories' }]) %}
{% endif %}

{% if productCategoriesArray|length > 1 %}
  {% set productParameters = productParameters|merge({ relatedTo: productCategoriesArray }) %}
{% endif %}

{% set productEntries = craft.commerce.products(productParameters) %}

{% if productSegmentCategory|length %}
    {% set entry = productSegmentCategory %}
{% endif %}


texts:
I'm currently trying to implement a Google maps via Maps  plugin: https://github.com/ethercreative/simplemap
I'm following documentation entirely, using PRO version of the plugin. In the plugin settings, I've chosen Google maps style map and Geo service is Google Maps with their own API key. Everything is displaying correctly in the settings menu.
Next, I have created a field, using map field type provided from Maps plugin - and there, everything seems alright; map is showing with default location displayed.
I have section Hompage (where the client wants a Google map to be) and assigned that field to that section.
The last step should be displaying that map on the site. In the plugin documentation, it says that I need to simply call that field via twig.
I was using {{ craft.entries().section("home").one().mapGoogle }} (mapGoogle is a field handle)but it is showing me an error Object of class ether\simplemap\models\Map could not be converted to string
I'm keep getting different errors, but it all came to that last one which I cannot solve, and I don't know what am I doing wrong. Did I miss something in the installation or documentation? Or, simply I don't know how to use twig tags :)
EDIT: When I'm using embed part from the plugin documentation nothing happens.
Dumping this variable I'm getting this info:
object(ether\simplemap\models\Map)[724]
  public 'id' => null
  public 'ownerId' => int 239
  public 'ownerSiteId' => int 1
  public 'fieldId' => string '37' (length=2)
  public 'zoom' => int 13
  public 'distance' => null
  public 'lat' => null
  public 'lng' => null
  public 'address' => string '' (length=0)
  public 'parts' =>
    object(ether\simplemap\models\Parts)[871]
      public 'number' => string '' (length=0)
      public 'address' => string '' (length=0)
      public 'city' => string '' (length=0)
      public 'postcode' => string '' (length=0)
      public 'county' => string '' (length=0)
      public 'state' => string '' (length=0)
      public 'country' => string '' (length=0)
      public 'planet' => string 'Earth' (length=5)
      public 'system' => string 'the Solar System' (length=16)
      public 'arm' => string 'Orion Arm' (length=9)
      public 'galaxy' => string 'Milky Way' (length=9)
      public 'group' => string 'the Local Group' (length=15)
      public 'cluster' => string 'Virgo Cluster' (length=13)
      public 'supercluster' => string 'Laniakea Supercluster' (length=21)
  public 'what3words' => null
  private '_errors' (yii\base\Model) => null
  private '_validators' (yii\base\Model) => null
  private '_scenario' (yii\base\Model) => string 'default' (length=7)
  private '_events' (yii\base\Component) =>
    array (size=0)
      empty
  private '_eventWildcards' (yii\base\Component) =>
    array (size=0)
      empty
  private '_behaviors' (yii\base\Component) => null


texts:
I have a single page selected as home page by ticking "This is for homepage" but now I find link comes up as  http://example.com/index.php/__home__

I want the home link to only be  http://example.com/index.php/ What do I need to do to get rid of __home__?


texts: Looping through an assets field type within a matrix field that's eager loaded

texts:
I'm trying to loop through images that are eager-loaded inside matrix block, but I can't get the images inside a matrix field handle to loop and show each individual image.

The loop I have loops the correct amount of times (based on how many images there are in each matrix block), but it just shows the first image of the loop.

Here's the set up:

Section handle: products
Matrix field handle: imageTextSections
Block type handle: sectionBlock
Field handle: sectionBlockImages
Field type: Assets

I'm trying to loop through images that are eager-loaded inside matrix block, but I can't get the images inside a matrix field to loop and show each individual image.

The loop I have loops the correct amount of times (based on how many images there are in each matrix block), but it just shows the first image of the loop.

Here's the set up:

Section handle: products

Matrix field handle: imageTextSections

Block type handle: sectionBlock

Field handle: sectionBlockImages

Field type: Assets

{% set blocks = entry.imageTextSections.find({
    with: [
        'sectionBlock:sectionBlockImages'
    ]
}) %}

{% for block in blocks %}
...

{% for images in block.sectionBlockImages %}
    {% set image = block.sectionBlockImages[0] ?? null %}

{% endfor %}

{% endfor %}

I figured that the following would work, but I get an error stating that the AssetFileModel.0 is not defined.

{% for images in block.sectionBlockImages %}
    {% set image = images[0] ?? null %}

{% endfor %}

Any guidance would be greatly appreciated!


texts: Umlauts in asset file-paths - Broken filenames on server

texts:
I have some issues with the asset handling of files containing Umlauts. Specifically it seems that the uploaded files on the server get renamed to a "broken" filename.

Zweigänger-1960.jpg becomes ZweigaÌnger-1960.jpg

No issues in the DB fields.

What could be the reason for that? What I'm overlooking? Also a solution similar to "limitAutoSlugsToAscii" would work for me or even renaming the files according to a pattern.


texts: How to get all (prepped) field values from an entry, indexed by field handle

texts: Getting field values, properly prepped, is covered here: What is getContent() / the ContentModel, and how do I use it to get and set custom field values?


texts: Configure path craft uses for composer and php

texts:
Is it possible to configure the PATH to composer that craft is using?
In a shared hosting (our server, lots of sites) php isn't available by default.
It's provided via redhat software collections. Each site can choose which version to run via environment variables. Since craft also uses composer; it means updates via it's web ui fail because when craft shells out to run composer; its not selecting which php it wants.


texts: How to validate email address entered during checkout on Craft Commerce?

texts:
The craft commerce templates have too many checkout steps for us in practice. So I have combined them.
I have moved the email field into the Address page.
But I can submit this form without ever entering an email. There is no validation on it (at this stage anyway).
How can I validate the email at this point please?
To validate the address I use this, but when adding email to it there is an error because email is not part of the Address.
Event::on(
    Address::class,
    Model::EVENT_DEFINE_RULES,
    function(DefineRulesEvent $event) {
        $rules = $event->rules;
        $rules[] = [['firstName', 'lastName'], 'required'];
        $event->rules = $rules;
    }
);

For info, we are not allowing user registration, its guest accounts only. No need to check if a user email exists, or have a login form or a link to checkout as guest. We just need to check the email field has been filled in.


texts:
I have looked at documentation and I still can't figure out how to output the matrix to my template.

The Field handle name is: threeHomepageImages

The Block type handle name is: images

The Fields names are: image, alt, and imageTitle

I have the following and tried a few combinations, but no luck. Any help is much appreciated.

{% for block in entry.threeHomepageImages.type('images') %}
    {{ image }} {{ alt }} {{ imageTitle }}
{% endfor %}


texts: Using relatedTo with a string of category ids

texts:
I have got a list of product variants being filtered by a string of category ids if there is some data in the category parameter with the following code:

(Note that I'm using the + character between category IDs, which getParam converts into spaces, so I'm splitting on spaces)

{% set categoryParams = craft.app.request.getParam('cat') %}
{% set categoryParamsArray = categoryParams|split(' ') %}

{% if categoryParams|length %}
    {% set results = craft.variants({product: product}).relatedTo(categoryParamsArray) %}
{% else %}
    {% set results = craft.variants({product: product}) %}
{% endif %}

This works perfectly if there is one category selected but no longer works when I select two or more. The responses are as follows:

✅No category selected: 22 results

✅One category selected: 5 results

❌Two categories selected: 22 results

Any advice on this method would be appreciated. Thanks.


texts:
I am currently working on a project in EE that involves food delivery services and have run into a block. The project is about users subscribing to a plan and receiving a different dish every day of the week. During signup, users select their meat preferences and any items they're allergic to.

On the food side, when dishes are added, the type of meat in them is one field and ingredients (ones that users could be allergic to) is another. There will be about a couple of hundred dishes added in total.

What I would like to do is select 2-3 types of dishes daily and have them distributed to users based on their meat preference. With EE, I can't figure out of I can create a relationship based on multiple queries (such as select users that have chosen Vegetarian AND chicken or Select Users that have chosen Chicken but NOT vegetarian.) Would this be something Craft is capable of? And What would be the best way of picking a dish and then figuring out which users it can be assigned to and then picking the second dish and assigning to the remaining users and if need be, pick a third dish to assign any users that are left over?


texts: Is it possible to hook into image transforms?

texts:
I have a somewhat unique thumbnail need for a certain site. I need to watermark images with custom text (per image, not globally across the site). Is there a way to hook into the Craft image transform generation logic and insert/run my own logic?

I've experimented with craft()->on('content.onSaveContent', function(Event $event) { and it seems to work okay. It will run when you save/upload the asset. The downside is that it generates the thumbnail on save, instead of on demand (using Javascript) as the native Craft transform feature does.

So, is there a different event I can hook into? Or, is there a better way to adjust the transform generation logic.


texts:
I have a large dataset of active records (not Craft entries) that I'd like to display in the admin frontend. Yii comes with a widget called CGridView, found here: framework/zii/widgets/grid/CGridView.php, which would fit the bill perfectly.

I've discovered that zii is not available in Craft, even though it's built on Yii. Is there an alternative to use in Craft that can provide a paginated grid view of active records or is there a way to include zii without affecting Craft core code?

This is for version 2.6 PRO of Craft CMS.


texts: Requesting SVGs from a plugins resources directory doesn't work

texts:
I have an SVG file in my plugins resources, I'd like to use the asset in the front end.

{{ resourceUrl('cocktailrecipes/images/gin.svg') }

It seems using the resourceURL() only allows a select few image types.

Is there a way to extend the permitted image types to include '.svg'?


texts: Is there a way to delete all entries in a section?

texts:
I've ended up with loads of duplicate entries after a botched import job.

Is there an easy and safe way to delete all entries in a section, so that I can start over again?


texts: Missing Position Field Type in Matrix (Craft 3)

texts:
Anyone know how to get the Position field type to show up in Craft 3 (RC)?

I have a Matrix field, and an Asset/Image field within that, and I'm trying to add a Position field to it.


texts: How do I enable editing of entries with a front-end form?

texts: Users can currently submit entries using a form on the front-end. How would I go about showing the current logged in user's existing entries and allow them to edit them through another front-end form?


texts: How can I utilize existing UI for my plugin's control panel views?

texts: I'm new to building plugins and I need to make templates for the control panel. How can I use existing Craft UI components to keep things consistent and save myself from having to rebuild everything?


texts:
I need to display entries that contain an image, and a piece of text, on the home page of my website.

When someone clicks 'next', I would like it to go to the next entry (by post date) and display that entries image and text. I also need the user to be able to click on 'previous' (by post date again) and 'random'.

How do I go about this?

Thanks!


texts: Top level entry url not rendering category in url

texts:
I have a structure section called products. The entry url format is

products{category.productCategory.first().slug}/{slug}

However the category never shows in the preview or real world url (real world url gives a 404)

Each product entry only has one category so am puzzled as to why the category doesn't appear in the url.


texts: Richtext Redactor Field - Standard Layout does not show image button

texts:
When i use a "Default" Richtext field - the image button displays and works.
When i change Default to "Standard" (the out of the box one) the image button does not display.

All instructions suggest Craft should be handling this to map asset fields to the richtext field. But it is failing for these - Any ideas?


texts: Getting type of element inside of a matrix field using plugin hook

texts:
I've been trying to deal with saving matrix fields to an external API by hooking onto the craft()->on('entries.saveEntry) function in a custom plugin I made. Matrices are nice for content authoring, but aren't quite nice for efficient retrieval in their current craft implementation.

Lets say I made a matrix field like this:

And I wanted to handle parsing this using the craft()->on('entries.saveEntry', function(Event $event) {} hook inside of a plugin

foreach ($event->params['entry']->getFieldLayout()->getFields() as $fieldLayoutField)
{
    $imageArray = array();
    $field = $fieldLayoutField->getField();
    // Now get the prepped field value
    $value = $event->params['entry']->getFieldValue($field->handle);
    //Check what type of field that is being saved
    if(is_object($value)) {
          switch (get_class($value)) {
            case 'Craft\ElementCriteriaModel':
                $matrixBlocks = $value;
                $value = array();
                $elementType = $matrixBlocks->getElementType();
                if(is_object($elementType)) {
                    switch(get_class($elementType)) {
                        case 'Craft\MatrixBlockElementType':
                            //Get each element block
                            foreach($matrixBlocks as $blocks) {
                                $valueNested = array();
                                $valueNested['type'] = $blocks->type->handle;
                                $valueNested['status'] = $blocks->status;
                                //Loop over each field in the matrix field
                                foreach ($blocks->getContent()->getAttributes() as $key => $blockVal)
                                {
                                    //How do I get the type of this element???
                                    //This could be an asset, or text field, etc.
                                    $valueNested[$key] = $blockVal;
                                }//End Foreach blocks->getContent()
                                //Add the results to the value array, since we can have multiple matrix types
                                array_push($value, $valueNested);
                            } // End For-each matrix blocks
                         break;
                    } //End switch
    } //End if object($value)
} // End For Each

This code works to save the matrix items into an array along with the value. I'm trying to figure out if it is possible to figure out what type the element inside of the matrix is programmatically?

Ex. Figure out if the item is a text field or a asset, etc?

I've spent hours in xdebug trying functions, looking through the matrix block type reference and seem quite lost. Anyone have any ideas?


texts: How can I get a related Asset of a specific field?

texts:
I'm trying to grab an Asset which is a child of my Entry...

$criteria = craft()->elements->getCriteria(ElementType::Asset);
$criteria->childOf = $entryId;
$photo = craft()->assets->findFile($criteria);

For the most part, this works pretty well. But my entry has multiple Asset fields, and sometimes it grabs the wrong image.

I suspect that I just need to add another parameter to my $criteria, but I can't figure out what... theoretically something to denote which specific field I'm referring to. Any suggestions?


texts: Custom plugin: Creating new fields will delete the field group they're being created in

texts:
I have a simple plugin which reads in a CSV file, and based on the first row of data will create a new field group, and then create fields within that group. The first time I run it everything goes well. The group is created, and the fields are also all created. However, if I re-run it with a new field it will delete the field group. Does anyone have any thoughts on why this is? This is the code, below:

This block checks if the desired group exists, and if not creates it:

protected function getFieldGroup($groupName) {
    $groups = Craft::$app->fields->getAllGroups();
    foreach ($groups as $group) {
        if ($group->name == $groupName) {
            return $group->id;
        }
    }

    $group = new FieldGroup();
    $group->name = $groupName;
    Craft::$app->getFields()->saveGroup($group);

    return $group->id;
}

The following is the code to then create the fields:

$fieldsService = Craft::$app->getFields();
$groupId = $this->getFieldGroup('My Group');
foreach ($fieldNames as $fieldName) {
    $fieldHandle = lcfirst(str_replace(' ', '', $fieldName));
    $fieldHandle = str_replace('#of', 'numOf', $fieldHandle);

    $field = $fieldsService->createField([
        'type'    => 'craft\fields\PlainText',
        'name'    => $fieldName,
        'handle'  => $fieldHandle,
        'groupId' => $groupId,
    ]);

    $fieldsService->saveField($field);
}

The point at which the field group is deleted is on running the $fieldsService->saveField($field); command.

So, just to reiterate:
The first time this runs there are no issues. Group and fields are created.
Running it a second time, if a new field is being added, the group gets deleted. This results in all the fields created for that group being assigned "NULL" in their groupId in the database, which causes errors.

Any help would be appreciated, thank you!


texts: If a Model can be used to save entries, what is a Record for? Is it literally just to define the schema? I've seen a few examples where the defineAttributes methods have duplication of code too, so I'm a little confused...


texts: How can I find out what type of entry is getting used?

texts:
I have an include that is being used for plain entries, and is also being used for categories. (Categories have their own urls)

{% if entry is defined %}
    {% set entry = entry %}
{% elseif category is defined %}
    {% set entry = category %}
{% elseif event is defined %}
    {% set entry = event %}
{% endif %}

...

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

I am using the Solspace Calendar and would like to use the same hero template. However, I'm getting the "entry is not defined". I am not sure what the calendar entry type is. Is there a way to output what Craft is expecting?

I have also tried:

{% if entry is defined %}
    {% set entry = entry %}
{% elseif category is defined %}
    {% set entry = category %}
{% elseif calendar is defined %}
    ...
{% endif %}

Thank you for any suggestions!


texts: Using $model->validate() with AttributeType::Url

texts:
I have a basic model defined:

protected function defineAttributes()
{
    return array(
        'id'        => array(AttributeType::String, 'required' => true),
        'url'       => AttributeType::Url,
        'info'      => array(AttributeType::String, 'required' => true, 'maxLength' => 4000),
        'title'     => array(AttributeType::String, 'required' => true, 'maxLength' => 65, 'minLength' => 15),
        'message'   => AttributeType::String,
    );
}

And when checking if the model is valid:

if (!$my_model->validate())
{
    return false;
}

Almost any string for 'url' is passing the validation, even without a '.com'

So if someone inputs sdfsdfsfsdfsdf in the input field, it'll pass as a valid URL and return as http://sdfsdfsfsdfsdf

I've also tried using AttributeType::UrlFormat but I run into the same problem. Am I not understanding what this attributetype does, or should it be validating that it's an actual URL string?


texts: Table fields, default single empty row, and never returning as empty?

texts:
I'm having a small problem with table fields. My issue is that by default a table fields starts with one row. Even if you leave this row empty (no values at all in any column) the field will never return as empty because that row exists even though it has no value. In order to get an empty field check like this to work:

{% if entry.whiskeyTableHandle | length %}

You have to actually delete that first empty row rather than simply leave it blank.

I cannot count on my client to remember to delete the row to indicate an empty field.

Would there be any way to have the table field show in the CP publish page with no rows visible by default? That means if nothing is added to the field it will properly return as empty.


texts: Plugin removed, can't get rid of its data | Control Panel JS

texts:
I was using the Control Panel JS plugin, and I entered some erroneous JavaScript that caused it to break the control panel. I then deleted its row in the plug-ins table in the database, and all associated files.

However, when I reinstall it, it finds the old JavaScript and things break again. I cannot figure out where this information is stored.


texts: Commerce new order error : mail::getRenderLanguage() must be of the type string

texts:
I just pushed an update to the latest version of craft cms and craft commerce and ran into an error that is blocking new orders from finalizing.
Everything works on the local site. On the live site, attempting to place a new order throws a 500 error and doesn't complete the order or send a confirmation email. The payment, however, does go through.
In the web.log I can only find this error:
2021-01-17 18:00:08 [-][5709][d3ac37ae1b5d01a8535b021ef5e5a0b0][error][TypeError] TypeError: Return value of craft\commerce\models\Email::getRenderLanguage() must be of the type string, null returned in /home/okaytype/craft/vendor/craftcms/commerce/src/models/Email.php:117
Stack trace:
#0 /home/okaytype/craft/vendor/craftcms/commerce/src/services/OrderStatuses.php(440): craft\commerce\models\Email->getRenderLanguage(Object(craft\commerce\elements\Order))
#1 /home/okaytype/craft/vendor/craftcms/commerce/src/services/OrderHistories.php(127): craft\commerce\services\OrderStatuses->statusChangeHandler(Object(craft\commerce\elements\Order), Object(craft\commerce\models\OrderHistory))
#2 /home/okaytype/craft/vendor/craftcms/commerce/src/elements/Order.php(1971): craft\commerce\services\OrderHistories->createOrderHistoryFromOrder(Object(craft\commerce\elements\Order), NULL)
#3 /home/okaytype/craft/vendor/craftcms/cms/src/services/Elements.php(2454): craft\commerce\elements\Order->afterSave(false)
#4 /home/okaytype/craft/vendor/craftcms/cms/src/services/Elements.php(755): craft\services\Elements->_saveElementInternal(Object(craft\commerce\elements\Order), false, false, true)
#5 /home/okaytype/craft/vendor/craftcms/commerce/src/elements/Order.php(1576): craft\services\Elements->saveElement(Object(craft\commerce\elements\Order), false)
#6 /home/okaytype/craft/vendor/craftcms/commerce/src/controllers/OrdersController.php(221): craft\commerce\elements\Order->markAsComplete()
#7 [internal function]: craft\commerce\controllers\OrdersController->actionSave()
#8 /home/okaytype/craft/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#9 /home/okaytype/craft/vendor/yiisoft/yii2/base/Controller.php(180): yii\base\InlineAction->runWithParams(Array)
#10 /home/okaytype/craft/vendor/craftcms/cms/src/web/Controller.php(190): yii\base\Controller->runAction('save', Array)
#11 /home/okaytype/craft/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('save', Array)
#12 /home/okaytype/craft/vendor/craftcms/cms/src/web/Application.php(274): yii\base\Module->runAction('commerce/orders...', Array)
#13 /home/okaytype/craft/vendor/craftcms/cms/src/web/Application.php(577): craft\web\Application->runAction('commerce/orders...', Array)
#14 /home/okaytype/craft/vendor/craftcms/cms/src/web/Application.php(253): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#15 /home/okaytype/craft/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#16 /home/okaytype/craft/web/index.php(42): yii\base\Application->run()
#17 {main}
2021-01-17 18:00:07 [-][5709][d3ac37ae1b5d01a8535b021ef5e5a0b0][info][application] $_GET = [
    'p' => 'adminbuttstuff/commerce/orders/39536'
]

It seems like Craft is looking for a language value of some kind but I can't figure out where or how to provide it.
I've tried editing the settings in Commerce > System Settings > Email > Language to English, but it always reverts to "The language the order was made.", which is also English.
Update: I can get an order to finalize if I turn off the email confirmation. This makes me think there is a problem with the email template, but I'm not getting a system error not a twig error. My email template doesn't use a $language variable anywhere.
Any help would be hugely appreciated. Thanks.


texts: Why Does Manual Cache Clear Work But CP Task Fails?

texts:
I've been having a problem with my site not properly clearing out its template caches. The task list gets stuck on "Pending" when trying to execute the "Deleting stale template caches" task.

If I manually clear the caches by going to Utilities -> Clear Caches, that works fine and it unblocks the pending task list.

I thought maybe the problem was that my PHP memory_limit was too low, but if that were the case wouldn't the manual cache clear command also cause a timeout error?

My memory_limit is already pretty high at 512M so I'm hoping there's an alternative solution to this that won't require me to remove my cache tags.


texts: Changing the asset url for the Control Panel

texts:
I'm attempting to get the Control Panel assets to load from a CDN instead of locally from Craft.

Going through the config options here and here I can't seem to find a way to change the asset URL.

Is there any way to change the asset url (in this case for control panel)?


texts: Order of draggable entries and assets won't save

texts:
Hello Craft Community,

I have a site which has just over 300 entries but most entries have several asset fields, entry fields, or complex matrices.

My problem is that when on an existing entry, I cannot drag-to-reorder any items in an asset or entry field-type. The CP will let me reorder, but saving the entry does not retain my new ordering.

There are no console errors related to this problem, so I'm looking for advise on where to start troubleshooting.

Thanks!

Edit: additional note that my PHP runtime config variables seem to be in order, 256M memory, 3000 max_input_vars, etc.


texts: Use Matrix field to output specific html

texts:
I am quite new to this so, please be patient. I am wanting to output the following html:

Helping you to establish your outdoor brand in the world of retail and e-commerce

One of our top brands

We also have a design service

Visit us at our new site

I have a Matrix field set up as follows:

Field handle: homepageSlider
Block type handle: homeSlider
Field name handles: mainImage, whiteLogo, imageText and mainImage.

mainImage has a field type of 'Assets'
whiteLogo has a field type of 'Lightswitch'
imageText has a field type of 'Plain Text'
mainImageLink has a field type of 'Linkit' (from a plugin).

So far, I have written:

{% block content %}

{% includeJsFile "/js/jquery.jcarousel.min.js" %}
{% includeJsFile "/js/jcarousel.responsive.js" %}

{% for block in entry.homepageSlider %}

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

{% endif %}

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

{% set imagetwo = block.mainImage %}

{% endif %}

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

{{ block.imageText }}

{% endif %}

{% if block.type == "mainImageLink" %}
{% set yourLink = entry.mainImageLink %}
{{ yourLink.link|raw }}
{% endif %}

{% endfor %}

This outputs html as I want, BUT, is empty between
 and
. I have tried following this post, but am so far getting nowhere.

Any help that anyone can offer would be most appreciated.

With kind regards,

Mark


texts: Setting a date range on entry parameters

texts:
I'm working on a site that uses a date slider to select members of the site by birthdate. I want to show the users by gender and between two "ages". For example: Male, between 40 and 50 years old. The selection on gender works perfect, but I can't seem to get the lowest age set.
This is does work; with only the lower date set.

{% set dateRange = '<= ' ~ lower_date %}

{% set queryParams = {
        geboortedatum : dateRange,
        order :'lastName'
    }
%}

But once I set the upper age I've got an error.

{% set dateRange = '<= ' ~ lower_date ~ ' AND => ' ~ upper_date %}

{% set queryParams = {
        geboortedatum : dateRange,
        order :'lastName'
    }
%}

{% set leden = craft.users(queryParams) %}
{% set leden = craft.users(queryParams) %}

This gets this error:

Fatal error: Call to a member function getTimestamp() on a non-object in /chroot/home/deacteur/deacteursgilde.be/craft/app/helpers/DbHelper.php on line 597

Can anyone help me out here? I'm totally lost... Thanks a lot!!


texts:
After setting an asset resource I am receiving the "your source ' ' appears to be invalid." on the update indexes, and

Error uploading the file: The file system path '{basePath}/assets/images/' set for this source does not exist.` on the assets upload page.

My file structure is:

/var/www/
        craft/
        html/
            index.php
            assets/
                images/

I've tried all variations I can think of, ie:

{basePath}assets/images/
/assets/images/
/var/www/html/assets/images

I've ensured that the basepath is set correctly in general.php and i've ensured that ownership of the folders is set correctly.

Craft is installed on a digital ocean lamp droplet running 14.04. general.php looks like:

return array(

  // Use IP address of your droplet below
  'ip.address.of.droplet' => array(
    'siteUrl' => 'http://ip.address.of.droplet/',
    'environmentVariables' => array(
      'basePath' => '/var/www/html/',
      'baseUrl'  => 'http://ip.address.of.droplet/',
    )
  )
);


texts: How do I maintain the on value with a lightswitch-field as a plugin setting?

texts:
I'm trying to use a lightswitch-field in a plugin-config. But for some reason it won't get saved. The lightswitch-field is always off.

protected function defineSettings()
{
    return array(
        ...
        'mailerShowInfo' => array(AttributeType::Bool, 'default' => false),
        ...
    );
}

_settings.html:

{{  forms.lightswitchField({
        label: "Show info in sidebar?"|t,
        id: 'mailerShowInfo',
        name: 'mailerShowInfo',
        value: settings.mailerShowInfo,
        required: true
    })
}}

I tried to use AttributeType::Number instead, and even used settype() in prepSettings() to force a boolean conversion, but still nothing.

Any idea what I'm missing?


texts: Looking for a good explanation on Craft login and if it is using persistent cookies or session cookies, etc...?

texts:
I am coming from a .NET/C# authentication and session environment.  I have used {% requireLogin %} to create a secure area on the front-end of my website, but it seems that the login credential (or cookie) stays persistent after the browser is closed.  There does seem to be time factor as the next day a login is required, but the same day after a somewhat short period with the browser being closed I can relaunch the browser and I have full access to the secure areas and the system knows my user account, etc...

Looking for some direction to explain the Craft security and cookie lifespan in more detail.


texts: Auto trigger craft project-config/sync on deployment

texts:
So I have the following in my Composer file:

  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
      "@php craft setup/welcome"
    ],
    "post-update-cmd": [
      "@php craft migrate/all",
      "@php craft project-config/sync",
      "@php craft clear-caches/compiled-templates",
      "@php craft clear-caches/cp-resources",
      "@php craft clear-caches/data",
      "@php craft clear-caches/seomatic-frontendtemplate-caches",
      "@php craft clear-caches/seomatic-metabundle-caches",
      "@php craft clear-caches/seomatic-sitemap-caches",
      "@php craft clear-caches/temp-files",
      "@php craft clear-caches/template-caches"
    ],
    "post-install-cmd": [
      "@php craft migrate/all",
      "@php craft project-config/sync",
      "@php craft clear-caches/compiled-templates",
      "@php craft clear-caches/cp-resources",
      "@php craft clear-caches/data",
      "@php craft clear-caches/seomatic-frontendtemplate-caches",
      "@php craft clear-caches/seomatic-metabundle-caches",
      "@php craft clear-caches/seomatic-sitemap-caches",
      "@php craft clear-caches/temp-files",
      "@php craft clear-caches/template-caches"
    ]
  }

and on my deployment (deployHQ) I have the following SSH command:

cd %path%
composer install

However, sync changes (project-config/sync) doesn't take effect and each time I have to manually click the button.
Any ideas what I am missing in the process?


texts: How to identify the logged in user inside a plugin?

texts:
I have a public registration form and a plugin which needs to create an entry for a user when that user is activated. That part works. Because I want to force an Admin to activate the user, I am using this code block to stop Craft automatically activating a user on registration:

public function init() {
    craft()->on('users.beforeActivateUser', function(Event $event){
        // stop the user from being able to activate their account. Forces admins to do so.
        $event->performAction = false;
    });
}

But this also stops an Admin from activating the user account via the control panel.

I can't work out how to test that the user performing the event is the admin and therefore skip that blocking code. I'd tried this:

public function init() {
    craft()->on('users.beforeActivateUser', function(Event $event){
        // stop the user from being able to activate their account. Forces admins to do so.
        if($event->params['user']->isInGroup('artists')){
            $event->performAction = false;
        }
    });
}

But that doesn't work, presumably because a new registering user doesn't belong to any group at the point that code is run.


texts: Getting full native language name in Craft3 language switcher

texts:
I'm porting across a multilingual project from Craft2 to Craft3 and have to rebuild the language switcher. I was previously using the .nativeName method but apparently this is deprecated. I've got a really basic one working for flipping between the English and French versions of my site :

{% set langSwitcher = craft.app.sites.getAllSites() %}

{% for lang in langSwitcher %}
   {# Get base URL #}
   {% set url = alias(lang.baseUrl) %}
   {{ lang.language }}
{% endfor %}

The {{ lang.language }} is outputting en & fr but how do I get it to display the full native language names i.e English & Francais?

I found the getDisplayName() function in the docs but can't seem to get it working properly: https://docs.craftcms.com/api/v3/craft-i18n-locale.html#public-methods


texts: Commerce - Advanced shipping cost calculations

texts:
What is the best way to implement advanced shipping cost calculations? Custom adjusters were deprecated right? I need to add shipping costs based on the total price of all products from a specific type.
My client sells products that don't require shipping costs and products that do. The shipping costs are based on the total price of the order. However, products that don't require shipping costs are (obviously) included in the order total which means the shipping costs are higher than they should be.
Is there any way to make this work? Thanks in advance!


texts: execute Yii2 console command from Yii2 extension with Craft

texts:
Does anyone know if and how a console command from a Yii2 extension can be used with Craft?
To be more specific, I would like to use
https://www.yiiframework.com/extension/yii2-migration-creator
which is a yii2 extension providing a command to create migrations from existing tables.
However when I composer-require the extension, its command do not appear in Craft console command's list of commands.


texts: Non-admins not authorized to create entry via frontend

texts:
I'm currently working on a page that should allow registered users to upload an image and save it as an entry in a section called "bildupload", together with some additional fields.

Creating/saving the entry works just fine as long as I am logged in as an administrator, however, when logging in as a regular user, Craft throws an error telling me that I am not authorized and lack rights to access the page.

Above image shows what permissions the default-user currently has.

I tried adding some permissions, however I does not make a difference, the error still appears on submitting the form to upload/create an entry.

Any help?


texts: How to add attachments to emails with sprout forms

texts:
I am trying to add file attachments on the notification emails sent out by sprout forms plugin. Looking in the docs it looks like I need to add hidden config setting within the plugin.

I have created a config.php file in the plugin directory and put the following code in it:

<?php

return array(

'sproutForms' => 'enableFileAttachments',

);

However, when I receive a notification email it still doesn't have the attachment. Can anyone suggest what I'm doing wrong?


texts: Using Solspace Freeform to create an entry including a file upload

texts:
I have recently been having some issues using the Solspace plugin FreeForm. I have created a front end entry form which, when submitted, creates an entry in a specified section in the CP. I have used the Element Connections feature to accomplish this. The issue I'm having is that one of the fields in the form is a file upload and it seems the form is having difficulty uploading the file and assigning it to the entry once the form submits.

What seems to be happening is that if the file field is left blank, the form submits without error and creates the entry successfully. But obviously then the entry is missing it's file in the entry data as none were uploaded.

However, if a file IS added during the form submission, once again the form submits without issue, the file gets uploaded to it's specified assets directory, but the entry itself is not created at all.

The form is being combined with FreeForm Payments too, so the form also contains some native FreeForm Stripe payment fields.

I'd really appreciate any advice on this. If anyone has experienced this before, can you share any advice on where this maybe going wrong as I'm completely stumped. There is no form error whatsoever so to my eyes, everything appears correct.


texts:
I'm trying to match the 2nd part of the slug with the category title to then place a 'current' class on the link.

Something like:

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

    {{ category.title }}

{% endnav %}


texts: Best way to deal with Impossible to access an attribute ("isEditable") on a NULL variable ("")

texts:
I've had this issue a few times & wanted to know if there is maybe a better way to deal with the following issue:

Say I have this if on a page:

{% if entry.isEditable %}
    Edit this entry
{% endif %}

On an editable entry, the button appears if logged in. If logged out the button does not appear.

If I visit a page that is not an entry (just a template group) when logged in or not, I get this error:

Impossible to access an attribute ("isEditable") on a NULL variable ("")

The only successful way I've seen to so far to make this behave is as follows:

{% if entry is defined %}
    {% if entry.isEditable is defined %}
        {% if entry.isEditable %}
            Edit this entry
        {% endif %}
    {% endif %}
{% endif %}


texts: Craft 3 Field Plugin not firing $view->registerJs in entry versions

texts:
I am creating a Craft 3 plugin. It seems to work fine when editing regular entries but when I open a revision the JS I'm injecting using the below doesn't appear on the page.

$view->registerJs($js, View::POS_HEAD);

This does work on regular entries. Any ideas?


texts:
I'm stuck with the .first() element and why the for-loop code won't work.

    {% set image = entry.bannerSlider.first() %}
    {% set transformedImage = craft.imager.transformImage(image,
      { width: 1420, height: 550, position: image.focalPoint,  effects: { grayscale: true, gamma: 1.5}, }) %}
    {% for image in entry.bannerSlider %}

    {% endfor %}

If I remove the .first() element the code breaks ("An unknown image object was used"), but, as this code populates a slider, I need all the images loaded, hence my attempt with the for-loop.

I think I am mixing up different Models, but need someone to point it out, please...


texts: How to duplicate an element type model with content?

texts:
Duplicating models is easy if you do it from the edit view, where you can just omit the ID and pass it along to save().

But how would I go about doing that programmatically without having a POST array to work with?

I tried removing the ID from the model, before I pass it to save(), in the end I had two identical entries in the database, but I could only access the new one when finding records by ID.
The original or any subsequent "original" items I clone from become unavailable even though they're in the database.
My guess is that the Content model just changes its ownership to the newly created entry and that causes this to happen.

I also tried $model->copy() and removing the ID, and that held the same results.

I tried copying the $model->getContent() and removing its ID, then using $model->setContent($clonedContent). This, at least, didn't prevent me from being able to access the original entry, but the content was never copied (all of my custom field data).

So how should go about this?
Any help greatly appreciated!


texts: How to Make a Change to an Existing Page Go Live at a Particular Point in Time

texts:
In Craft, is it possible to make an edit to an already existing (live) page but be able to set a particular point in time that you want to change to go live?

I know that you can set the post date and time for when you're implementing a new page but curious if there's a similar capability for implementing a change to that page after it's already live.

Thanks!


texts: Getting started deploying Craft sites with Capistrano

texts:
I'd like to deploy a Craft site with Capistrano but am looking for the best way to get started.

Is the Craft Deploy utility by Bluegg up to date, or would it be better to use a vanilla version of Capistrano? I'm curious because there doesn't seem to be a lot of activity on the github account for the utility.

For anyone with experience using the Craft Deploy utility, are there any caveats for bringing the Craft Deploy utility into an existing project? The instructions tell how to use it when setting up a new project but not an existing one.


texts: Is it at all possible to get forms to display per site and not all forms displaying to a site admin user? Also an admin user doesn't seem to be able to run reports on there own site, without being an admin of the entire Craft CMS instance.


texts:
I'm using a matrix inside a Super Table to organize events, and I'd like to order the events using the date field for each event.

I'm currently showing the first five events using limit then using offset to show the rest of the blocks after the first five. Then I'm separating future and past events using the date field. Like this:

First five upcoming events:

{% for block in block.eventList.limit(5) %}
     {% if block.eventDate >= now %}
          {{ block.eventTitle }}
     {% endif %}
{% endfor %}

The rest of the upcoming events:

{% for block in block.eventList.offset(5) %}
     {% if block.eventDate >= now %}
          {{ block.eventTitle }}
     {% endif %}
{% endfor %}

All past events:

{% for block in block.eventList %}
     {% if block.eventDate <= now %}
          {{ block.eventTitle }}
     {% endif %}
{% endfor %}

This works fine as is, but it doesn't sort the events within the sections by the date field. How can I add that?


texts: Check if a table field’s row has a value

texts:
We have a table field that has the default value of 1 row when a new entry is published.

Unfortunately, we have

{% if entry.tableField | length %} display markup and field content... {% endif %}

and this will always be true of each entry because of the Craft default.

Obviously, we can remove the default row in the future but wondered if there was a way to extend that condition to say, for example

{% if (entry.tableField | length) and (entry.tableField.row | length) %}


texts:
I am trying to build a leaderboard page, and I'm having difficulties finding a way to group the entries by Author.

I was able to create a plugin to get the sql sum function in there, but I now need to add a group by Author and order by Score DESC to that.

First steps were taken from here: Ability to SUM() or GROUP BY from the template or ElementCriteriaModel

What I ultimately want is a query that would look like this (very simplified of course):

SELECT author, SUM(content.score) as score FROM content Group By Author Order By score DESC

Is there a way to do this "natively" or do I need to write my own query?


texts: Get the location and id of asset volumne

texts: Is it possible to get the location (/media) and id (1) of an asset volume from within a Craft template?


texts: Craft Commerce: Agree to Terms Checkbox?

texts: What would be the best way of adding an Agree to Terms checkbox during the the checkout process of craft commerce? I'm thinking this would be best in the address section.


texts: Image transform that only crops if image is larger than set dimensions

texts:
At the moment I have an image 300px wide, my transform is set to a width of 600px so it upscales it.

I would like it to only transform if the image is over 600px.

Is this possible or should I use some other image manipulation thing like phpthumb?


texts:
I want to make a Restful API with JWT in order to be able to make calls to it.

I have this in /config/app.php:

return [
    'modules' => [
        'my-module' => \modules\Module::class,
        'demarketsjwt' => \demarkets\Module::class,
    ],
    // 'bootstrap' => ['demarketsjwt'],
    'components' => [
        'listingsDb' => [
            'class' => craft\db\Connection::class,
            'driverName' => 'mysql',
            'dsn' => 'mysql:host=localhost;dbname=' . getenv('DB_LISTINGS_DBNAME') . ';port=' . getenv('DB_LISTINGS_DBPORT') . ';',
            'username' => getenv('DB_LISTINGS_USER'),
            'password' => getenv('DB_LISTINGS_PASSWORD'),
            'charset' => 'utf8',
            'tablePrefix' => '',
            'enableSchemaCache' => !YII_DEBUG,
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'craft\web\UrlRule', 'controller' => 'user'],
            ],
        ],
    ],
];

and I have this in /controllers/UserController.php:

<?php

namespace app\controllers;

use Craft;
use craft\web\ActiveController;

class UserController extends ActiveController
{
    // public $modelClass = 'app\models\User';ç
    public function init()
    {
        parent::init();
        $now = time();
        $rows = Craft::$app->listingsDb->createCommand("SELECT * FROM table;")->execute();
        echo $rows;
    }
}

I am doing tests with Postman app but I cannot make it work. What am I doing wrong?

Thank you in advance for your kind help.


texts: Line item not found when trying to remove item from cart

texts:
I'm trying to remove a product from a cart but i'm getting an {error: "Line item not found"} error and I can't figure out why. Here is my code:

$('.js-item').on('click', function(e) {
    e.preventDefault();
    var id = $(this).data('item-id');
    var csrfToken = $(this).data('csrftoken');

    $.ajax({
        type: "POST",
        dataType: 'json',
        headers: {
            "X-CSRF-Token": csrfToken,
        },
        data: {
            'action': 'commerce/cart/update-cart',
            'lineItems': {
                [id]: {
                    'remove': true
                }
            }
        },
        success: function(data) {
            alert("removed");
        }
    });
});

{% set cart = craft.commerce.carts.cart %}
{% set cartItems = cart.getLineItems() %}
  {% for item in cartItems %}

{{item.snapshot.title}}

  {% endfor %}
{% endfor %}


texts:
In my rich text field I want to add images to the toolbar.
I have done everything that has to be done: I've added "image" to the Standar.json file and selected the Standard.json to be used for the field.

The thing is, the 'image upload' is not added to the toolbar.
If I add "list" to the Standard.json the list does get added into the toolbar.

Does anyone know why this happens and how I can fix this?


texts:
I'm having a pretty consistent issue with the user activation links sent out in the registration emails. Having a hard time diagnosing because I can't replicate it myself, but getting several users a day contacting saying their link doesn't work. In the logs I see this:

2016/10/24 16:03:59 [warning] [application] The verification code (7TU6Z3adW6CXBmPjmgYqpJI9BeNi3cLN) given for userId: 44253 does not match the hash in the database.

I have the validationKey set in the config file and not sure if that may affect it(such as invalid characters in it), or maybe something is causing the verification code to include incorrect characters in the URL that is causing it to be truncated or read incorrectly when decoding?

The users email the end client directly, so often by the time they send me the info along, they've already manually activated them so I can't further troubleshoot.

Any ideas?


texts:
I want to display the date an entry has been updated if it is later than the post date. So I've tried this:
   {% if entry.dateUpdated >= entry.post %}
      Updated on {{ entry.dateUpdated.format('j M y') }}
   {% endif %}

But the date updated displays even if it is earlier. Is this because the date is not strictly a value as such?


texts: Problem connecting to MySQL db on installing Craft 3

texts:
Having installed Craft 3 using Composer, I'm attempting to run the Craft setup. Everytime I try, I get the following error:

Testing database credentials... failed: SQLSTATE[HY000] [1044] Access denied for user 'xxx'@'%' to database 'xxx'

where xxx is the correct username and db name.
Obviously, it can't connect to the database for some reason. I have also attempted the entire install manually without Composer and get the same issue with not connecting to the db. I have also tried manually editing the .env file with the correct details after installing with Composer. No joy.

Looking at the error, I would expect the user to read: user 'xxx'@'localhost' given that I specified localhost as the server. I'm not sure why it specifies '@' instead but I suspect that is a clue.

I believe that port 3306 is used as the default TCP/IP port and that simply not specifying a port will not lead it to use Unix Socket instead. I raise this as I believe it may also be a clue to the issue - I can connect to the database using Querious (mysql database software) but only if I specify using Unix Socket instead of TCP/IP and leave the socket path blank (this using an SSH tunnel). My knowledge in this area is very shaky but I thought it might be worth mentioning in case it helps. I'm using Serverpilot.

Hopefully someone can shine a light?


texts:
I'm trying to set a fallback description in case there is none. This is the bit of code:

{% if seomaticMeta.seoDescription is empty and entry is defined %}
    {% set fallbackDescription = "" %}
    {% if entry.description is defined %}
        {% set fallbackDescription = extractSummary( entry.description ) %}
    {% endif %}
    {% if fallbackDescription is not empty %}
        {% set seomaticMeta = seomaticMeta | merge({
            seoDescription: fallbackDescription,
            og: {
                description: fallbackDescription
            },
            twitter: {
                description: fallbackDescription
            }
        }) %}
    {% endif %}
{% endif %}

But I get an error: Unknown "extractSummary" function in "_globals/_layout".

Am I doing something wrong?


texts: How can I filter which children I want to show in a sub navigation menu

texts:
I have a navigation menu setup but I want to filter out some of the children at level(2) so they aren't showing in the dropdown navigation menu. Here is how I am grabbing the children...

{% set mainEntry = craft.entries.slug(craft.request.getSegment(1)).one() %}
{% set subnav = craft.entries.descendantOf(mainEntry).level(2) %}

Home

Conference

                            {% for page in subnav %}

                                {{ page.link }}

                            {% endfor %}


texts: How to toggle main product image from multiple images

texts:
I'm having some trouble figuring out how to properly update the main product image from a set of images that are available.

Within the product detail page, I have a large default image that is shown with a set of thumbnails below from lopping through all available images associated with the product.

I'm able to loop through and display all available images for the given product using.

{% set relatedAssets = product.productPhoto.all() %}

  {% if relatedAssets|length %}
    {% for rel in relatedAssets %}

    {% endfor %}
  {% endif %}

What I'd like to do it update the large image once a thumbnail of the image set is clicked. I haven't been able to find anything related to successfully doing this which seems like a common pattern for an ecommerce site.

Any advice would be much appreciated!


texts:
I asked this question previously before Feedme was acquired by Craft, though I haven't updated Feedme & the code since now.
I'm getting the following error when processing my feeds. I'm trying to change my entries slug when they get imported but only on a certain feed - in this case - a feed with the title of 'merchants'

Argument 1 passed to craft\feedme\Plugin::craft\feedme{closure}()
must be an instance of craft\feedme\FeedProcessEvent, instance of
craft\feedme\events\FeedProcessEvent given - Plugin.php: 67

The code I'm trying to run in Plugin.php
public function init()
{
    parent::init();

    self::$plugin = $this;

    $this->_setPluginComponents();
    $this->_registerCpRoutes();
    $this->_registerTwigExtensions();
    $this->_registerVariables();

    Event::on(
      Process::class,
      Process::EVENT_STEP_BEFORE_ELEMENT_SAVE,
      function(FeedProcessEvent $event) {
        switch($event->feed['name']){
            case 'merchants':
                $element = $event->element;
                $element->slug = ElementHelper::createSlug($element->title.' '.'Coupon Codes & Promo Codes');
                break;
        }
    });
}


texts: 'png_compression_level should be an integer from 0 to 9' upon uploading image

texts: First time we see this: client tried to upload a specific PNG file (that a first sight looks ok) and Craft CMS returned the error 'png_compression_level should be an integer from 0 to 9'


texts: Entry with many fields vs plugin/custom data structure

texts:
i'm just getting my feet wet with craft and would appreciate some pointers.

Basically, what i would like to do is show and compare products. Each product will have a description, price, review, and many other characteristics (>50 in total). Items must be searchable by any single or combination of these. Data will be imported through a script (ie not manually).
Apart from that there will be articles etc (with maybe 3-6 fields) on the site.

Looking at the craft content table, it looks like an extra column is created for each field. When there are different types of entries, often many/most columns will be null.

My question is: should i be concerned about:
a) the db structure of craft entries (alternative could be to create separate table for products), especially performance wise

b) searchability of product entries. Would it be easy to search entries by combination of fields?

Not looking for a complete solution, just some pointers i can take along when deciding which way to go :)


texts:
I build a plugin for Craft 2 which imports data from an excel file into craft commerce products.

The problem is that it needs to import excels with like 10.0000 rows and 30 columns.

I made a simple page in the CP where they can upload the file and then view the progress inside of the tasks.

Running just 1 task was not good because if it crashes on the first row it just stops. I wanted to make some kind of batching with tasks so this s what I came up with:

public function startExcelImportTasks($fileName){
    $return = false;
    $dataObject = craft()->myplugin_productsInfo->getDataByExcelName($fileName);
    $grandTotal = count((array)$dataObject);
    $batchSize = 500;
    if ($grandTotal > 0) {
        for ($i=0; $i < $grandTotal; $i+=$batchSize) {
            $numberOfTasks = $batchSize;
            //if last loop set numberoftasks to total left
            if (($i + $batchSize) > $grandTotal){
                $numberOfTasks = $grandTotal - $i;
            }
            unset($dataObjectSlice, $dataObjectSliceString, $task);
            $dataObjectSlice = array_slice( $dataObject , $i , $numberOfTasks );
            $dataObjectSliceString = json_encode($dataObjectSlice);
            //create a task per batch
            $task = craft()->tasks->createTask('Myplugin_ImportExcel', 'Import excel - ('. $i . '-' . ($numberOfTasks + $i) .')', ['totalSteps' => $numberOfTasks, 'offset' => $i, 'grandTotal' => $grandTotal, 'dataObject' => $dataObjectSliceString]);
        }
        $return = true;
    }
    unset($dataObject,$grandTotal,$batchSize,$numberOfTasks,$dataObjectSlice,$dataObjectSliceString, $task);
    return $return;
}

So this is all running very well, I get tasks split up by 500 rows. My problem is memory usage, I thought when a new task would start it would free up the memory of the previous task but when I log my memory usage with memory_get_usage(true) it does not reset after the first loop and just continues to build up loop after loop until it finally crashes. It then goes to the next step starting with all free memory.

Is there any way to reset the memory for each loop? Loop 2 does not need to know ANYTHING that loop 1 needs since I slice the data and pass it to the right task.

I tried using some unsets in the code but that doesn't seem to do very much.

I also came across some subtask posts but I do not think that will change anything? I also like that the batching is shown in different tasks in the CP.

Any help is welcome,

Thanks


texts: Why does my entry language selection look different from examples?

texts:
All the examples look like this:

Mine looks like the image below where you have to select the site from that top left dropdown and then there are some enabled things on the right:


texts: localized site - except home, every page gives me a 404

texts:
I have a newly published site, where the localization does not work properly.
https://www.nomadenschaetze.com/de/
When i switch to english, it shows the right englisch homoepage. Now, when i click
another englisch site, for example contact, it does not find the templates.
https://www.nomadenschaetze.com/en/contact
The url is fine, the links have the right domain-urls, but it always goes to the 404.
In my dev- environment though, it is working:
the content and navigation changes to english,
https://dev.nomadenschaetze.com/de/
i am very confused.
my general.php looks like this:
 // Production environment settings
    'production' => [
        'siteUrl' => array(
            'nomadenschaetze_de' => 'https://www.nomadenschaetze.com/de/',
            'nomadenschaetze_en' => 'https://www.nomadenschaetze.com/en/',
        ),
        'allowAdminChanges' => true,
        'devMode' => false,
        'baseUrl' => 'https://www.nomadenschaetze.com',
        'aliases' => [
            '@root' => getenv('ROOT'),
            '@nomadenschaetze_url' => 'https://www.nomadenschaetze.com',
        ],
    ],

i have craft 3, in my web folder are a de and en folder. no .htaccess in there in these language folder.
in the web directory i have a .htacces file
<IfModule mod_rewrite.c>
   RewriteEngine On

    # language starts with DE
    RewriteCond %{HTTP:Accept-Language} ^de [NC]
    RewriteRule ^$ /de/ [L,R=301]

    # else redirect to the English version
    RewriteRule ^$ /en/ [L,R=301]

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

in the root directory i had to add a .htaccess file, because i cannot change the root directory on the server to "web".
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?nomadenschaetze\.com [NC]
RewriteCond %{REQUEST_URI} !^/web/.*$
RewriteRule ^(.*)$ /web/$1

what i am doing wrong?


texts:
I am a little puzzled by the way craft handles CSS files. Although I am used to working with SCSS and CSS assets and setting up a reasonable directory structure, I was expecting a little documentation or a best practice recommendation.

At first, I tried to create an asset folder with all CSS files. But then I realized that they could not be uploaded because they were not in the allowedFileExtensions config array.

The plugin documentation contains some info about handling plugin-specific frontend resources but it does not say anything about the general CSS files.

The most helpful information I found so far was this answer although it did not really help me with my question.

What is the recommended way to handle CSS assets? What are your best practices for asset management and setting up a frontend workflow in Craft?

Best regards


texts:
Firstly, I used WP Export All / Feed Me to migrate blog posts from a wordpress site to a craft site. The HTML from the wordpress content field has all been imported properly. Text is wrapped in p tags, headers in heading tags etc etc. However, even though the P tags are present in the html version of the redactor editor, on the page the p tags seem like they are stripped. I'll attach images to show what I mean.
This is my code in the redactor field.

Just a quick update on a large fit out project we are undertaking in Castle Donington to allow two companies to move into the space.

The majority of the first fix M&E has been completed and we are currently installing the framework to allow the toughened glass walls to be installed. As you can see from the photos, this is a high specification project that is going to completely transform the space, and create a modern and clean office environment.

This is my code for displaying the redactor field
{% if entry.type == 'blog' %}

                {{ block.text }}

{% else %}

Any help with this would be massively appreciated. Right now a workaround I have found is to delete the text, save the entry, then re-add the text and save. When I do this the p tags remain.


texts: Plugin not updating in the plugin store from changelog updates

texts:
I have a custom plugin registered with id.craftcms.com.

The plugin store currently sees it at as 2.0.0, but I have since updated the plugin to 2.0.1 (and subsequently tried to force a silent 2.0.2 update) and noted so in my changelog but the plugin store is not seeing this update.

The contents of my changelog look like this:

# Release Notes for Craft User Manual

## 2.0.2 - 2019-02-27
### Updated
- Forcing new version for deprecation issues

## 2.0.1 - 2018-08-24
### Fixed
- Deprecation Issues

## 2.0.0 - 2018-08-24
### Added
 - Initial Craft 3 release

This was lifted directly from Craft's documentation on changelogs so I'm not sure what I'm missing. Is there anything else I can try or debug?


texts: How to setup Bootstrap 4 Carousel with Craft CMS 3?

texts:
I'm hoping to get some help or guidance on a issue that I'm having. I am using Bootstrap 4 as my CSS framework and wanted to integrate a working Carousel with my web project.  I managed to get the jumbotron working with a Matrix field. See below:

I was hoping that I could create a Carousel Matrix block in a similar fashion as the Jumbotron that was created previously. Any suggestions on a proper setup?


texts: Best way to manage bulk purchase discounts for a product

texts:
I am looking to manage bulk purchase discounts for individual products.
For example if a customers buys 1 of a product it would not apply a discount, however if they purchased 10 it would apply 10% off the total price only for those items, or 15% discount for 20 quantity.
It would only affect individual product lines rather than the whole total of the cart. The user will have the option to select from a range of products, so this would need to be specifically on a product and variant level.
I have seen the $2 off discount applied in the Craft documentation, it would be good to know how this can be used within a custom module setup.
Would adjusters be the best option to use, where I can then apply the discounts and also do some checks to see if the product has a certain category?
Thanks


texts: Merge related entries from several matrix blocks while maintaining other matrix field data

texts:
I have a matrix that essentially creates categorized lists of other entries. The fields in my matrix block are "categoryName", a plain text field and "member", a entry relationship field.

I know i can output a list in with all of the blocks in order like this:

{% for block in allMembers %}
  {% for member in block.members %}
    {{ block.categoryName }}:
    {{ member.title|typogrify }}
  {% endfor %}
{% endfor %}

And this give me a list like:

Category 1: Apples
Category 1: Oranges
Category 1: Pears
Category 2: Cats
Category 2: Dogs

What I really want, though is to combine the contents of both blocks into a single array, and also pull in the category names,so i can sort them alphabetically by related entry title, like this:

Category 1: Apples
Category 2: Cats
Category 2: Dogs
Category 1: Oranges
Category 1: Pears

I know I can merge all of the related entries into a single array like this:

{% set allMembers = [] %}
{# loop through all relationship fields for this entry #}
{% for block in entry.featuredMembers %}
  {# loop through related entries #}
  {% for member in block.members %}
    {# add member to members array #}
    {% set allMembers = allMembers|merge([member]) %}
  {% endfor %}
{% endfor %}

{% for block in allMembers%}
  {{ block.title }}
{% endfor %}

But then I lose the Category Name. Is there a way to associate the categoryName field with the individual related entries before I merge them into my allMembers array?


texts:
I'm trying to import an ExpressionEngine blog into Craft. I've set up an xml feed on the EE site and limited it to two entries for testing purposes. Once it's working will import everything.

The issue I"m having is that when I run the import it fails and the feed me logs aren't helpful.

EE Blog: Finished database backup
EE Blog: Starting database backup

That's all I get.

I've done field mapping and set a unique identify for existing elements (there should be none at this point).

Sent a support email to feedme via the CP two days ago but haven't gotten a response.


texts: Commerce 3 products with dynamic options

texts:
I am well-versed in CraftCMS and am finally able to use Craft Commerce 3 for the first time on a project (first time for any version of Commerce, actually) and it's to build a platform for a butcher shop to take orders for pick-up and delivery.

One challenge is that this shop will have multiple types of quantity. For example, some products will be based on total pounds available (15 lbs. of ground beef), some on pre-created packages (more traditional item count), and others based on the length of cuts (i.e. 12" total available).

I believe I will be able to use the default Quantity field for each of these scenarios and show the type of quantity on the front end with a simple radio field.

Something I am now trying to figure out is the best way to handle products with options that could change the final product price.

For example:
Pork Shank - $8.00

Options:

Skin-on (+$0.00)
Skin-off (+$1.00)

In this example, the quantity is based on total pounds available, let's say 8.

My first instinct was to use variants, but this won't work as each variant has its own quantity field and these products will each have only one main quantity field.

I decided a good way to handle this might be a Matrix field that includes an option title and a table to enter the option label and associate cost increase.

This brings me to my main question: after ready through a variety of sources (many on Stack Exchange), it's clear that there is no way to manipulate the Commerce product/line-item price directly via the Twig templates.

This post gave me the idea that creating a custom plugin to update the product line-item price is probably the way to go. Unfortunately, it seems that this was written in reference to an older version of Commerce.

In addition, I am not confident in how I would actually trigger a custom plugin (assuming I would use the populateLineItem event, but also looking for guidance on this) via the Twig template.

I would really appreciate any guidance on how I might create a custom plugin for this particular scenario, or if there is a better way to approach this than the one I am thinking of. Thanks!


texts: How to download private assets (without public URL) from dashboard

texts:
I would like to download asset files from Craft 3 dashboard.

Those files are out of web folder because of security reason.
I made "documents" folder just under the root of the project, and the files are in there.

However, the function of "download file" does not work, although "preview file" and "Edit image" works.
I think it is strange.

Do you have any idea to download the private files?


texts: Date picker field type - quickly select year?

texts:
I need a "date of birth" field. Out of the box, the date picker only allows moving left/right by month, which doesn't work for selecting years.

Is there a way to configure the date picker that Craft uses? Or is there a better way to make a date of birth chooser?

Thanks!


texts:
Before I start to build this store on my own, I would like to ask if anyone can provide some guidelines on the following setup.
I am trying to build a store with a member area for subscribed members with an annual renewal.

What is the best way to approach this setup? Is there anything I have to consider or be concerned about? Any warning or solution on plugins that I have to consider...

I have attached an image on how I see it. Please comment if there is anything I miss or you have a suggestion on how to build it.

Thanks in advance -
Nermin


texts:
Still very new to Craft but just can't figure this problem out, it's a level above me at the moment.

I have an FAQ page as a 'single' that I would like to display all entries from a channel by default.

But all these entries will have a tag option (either 'red' or 'blue').

How would I sort these entries via a sub nav to display only all, red or blue tagged entries?

Thank you in advance.


texts:
I have a category group set up called 'gists'. I have entries that contain a category field which pulls in the category group 'gists'.

Now I need to access entries that are tied to individual categories but I need to do so by the category slug.

I cannot figure out how to make this happen. I have tried numerous things but cannot get my head around this. Here is my latest.

{% for entry in craft.entries.section('gist').relatedTo('tech').limit(10).find() %}


texts:
The installation instructions say: "A few seconds later, you should have a working Craft install!
 ... If it was successful, Craft will redirect your browser to the Control Panel." My installation route was Terminal, and all I have at the end is "*** installed Craft successfully (time: 53.862s)". So, please help me to find the URL where I can start learning to use this design facility. Thanks in advance.


texts: Updating the Database for plugin settings

texts:
I have another plugin development question.

I am now trying to learn how to work with the database.  To that extent, I have the following code:

On the templates/settings.html page I have the following code:

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

{{ forms.radioGroup({
    label: "Radio Group Label"|t,
    instructions: "Radio Group Instructions"|t,
    name: 'radioGroupName',
    options:{ "option_1" : "option_1", "option_2" : "option_2"},
    value: settings.radioGroupName
}) }}

On the records/PluginNameRecord.php page, I have the following code:

<?php
namespace Craft;

class PluginNameRecord extends BaseRecord
{
    public function getTableName()
    {
        return 'pluginname';
    }

    public function defineAttributes()
    {
        return array(
            'radioGroupName' => array(AttributeType::String, 'default' => 'option_1')
        );
    }

}

And here is the code for the models/PluginNameModel.php file (I don't know if this is relevant or not, but I'm including it just in case):

<?php
namespace Craft;

class PluginNameModel extends BaseModel
{

    public function defineAttributes()
    {
        return array(
            'radioGroupName' => array(AttributeType::String, 'default' => 'option_1')
        );
    }
}

Now, I have tested this and it creates a table and column in mysql.  However, I cannot update the data in the database.  That is to say, if I select option_2 nothing happens in mysql.  The same default value of option_1 still shows up.

Can someone please let me know what I am doing wrong?

Thanks,

Moshe


texts: Streamlining a loop with a bunch of conditions

texts:
I'm sure there must be a tidier and more efficient way of doing this so thought I'd throw it out there for some opinions.

Building a site that has the usual lists (in grid format) for Blog, Gallery, Meet the Team, etc... I'm calling these 'cards', and I'm including them with various attributes:

{% include "_modules/card"
    with {
        author: true,
        badge: true,
        date: true,
        magnify: true,
        meta: true,
        thumbnail: true,
    }
%}

Then in my card I've got:

{% if badge is defined %}

{% endif %}

{% if thumbnail is defined %}

{% endif %}

Heading Goes in Here

    {% if meta is defined %}

            {% if date is defined %}
                {% include "_modules/relative-date" %}
            {% endif %}
            {% if author is defined %}
                by John Doe
            {% endif %}

    {% endif %}

This all works as expected but I can't help feel it could be neater. There are a lot of conditions at work here for example, and this will all be part of an entries loop too. Anyone have any suggestions for streamlining this a bit? Much appreciated.


texts:
I've been building sites with ModX Revolution for about 4 months but I've heard great things about Craft. I downloaded and installed it and the interface looks great.

To perform a detailed evaluation, I need to dive in and start building a basic site. But I don't know where to start. I found the mijingo tutorials but I have to pay $39.00 then mijingo tells me that I can only get so far with a free Craft license. To get the full experience, I need to buy at least a client license.

Are there any beginner tutorials for Craft that are free or at least don't require me to commit to the client Craft license?

Thanks.


texts: Limit category choice in entry to 1 and select child category

texts:
I have a section of book entries with a categories field called "Genre". A book can fall into multiple genres. A stripped down version of the categories works something like this:

Fiction

Crime, Thrillers & Mystery

Mystery
Thrillers
Action & Adventure

Fantasy

Non-Fiction

etc

On the home page, there is to be a feature panel linking to a particular genre, let's say Thrillers for example.

For the feature panel field, I need to limit this to a single genre, but if I set the limit on the categories field to 1 and select Thrillers, it just selects Fiction.

Of course I could just remove the limit and then use twig to get only entries from the deepest selected category, but I don't want to open up the possibility that they'll select multiple categories.

Is there any way around this? I can't help but feel like the limit option on the categories fieldtype is a bit broken.

* Update for clarity *

Categories group called Genre is structured as above
Books channel has a category field called Genre, allowed to select multiple genres
Homepage has a category field called Related Genre

The intention is to choose a single category for Related Genre to output the books which have that category selected in Genre.

This is all entirely within the admin area, so code is effectively irrelevant at this point.

Perhaps some images will make this clearer:

In the entry, I attempt to select Thrillers:

But after clicking select, it has just selected Fiction:


texts: Overriding a structure section's template for a single structure entry

texts: When you create a structure section you set which template that you would like to use. Is there a way to override that for a single entry in that structure? If I have missed it in the docs I apologise but it would appear that setting a route would not work due to the order things are looked up at.


texts:
I'm currently working on a relation-heavy website with a colleague of mine and, for that reason, eager-loading stuff looks very appealing to us.
We've succeeded in eager-loading pretty much everything that we needed but there is just one kind of template that we couldn't make it work with: paginated archives

The context:
We have this archive page that loads every entry of a 'projects' section and, next to each entry, we have a list of all images that the entry contains which is between 8-20 images (remember, I said it was relation-heavy ;) ). We care a lot about performance so we decided to paginate this big entry listing.

The issue:
All this works very well except that when we tried to eager-load those images, we transformed our original query which was:

{% set allProjects = craft.entries(queryParams).limit(itemsPerPage) %}

to

{% set allProjects = craft.entries(queryParams).limit(itemsPerPage).find({
    with: [
        'gridMatrixBlock1:rowItem1',
        ['gridMatrixBlock1:rowItem1.gridimageFile', {
            kind: 'image',
            withTransforms: projectThumb
        }],
        ...
    ]
}) %}

The question:
Since .find() returns an array, we have no way to paginate this (pagination need an ElementCriteriaModel). Is there any workaround I don't know about?


texts: Can't Output Entries from Particular Blog Categories

texts:
Trying to get all entries related to a particular blog category to output to the page. Right now I just get the correct URL for any category and a blank page.

Also my categories are entered into a matrix field as one of the matrix blocks. I use a single matrix field to capture all of the content for each blog entry.

Here is my categories/_category.html template code.

{# Fetch all of the entries related to this category #}
{% set category = craft.categories.slug('') %}
{% set entries = craft.entries.relatedTo(category) %}

{# Output them #}
{% for entry in entries %}
    {{ entry.title }}
{% endfor %}

I've tried plugging in particular category slugs into the craft.categories.slug('') but no help. I'm following advice from https://craftcms.com/support/entries-related-to-category

....and

Category Entries

Any ideas on what is missing?


texts: How can I use aliases in a module / plugin?

texts:
I'm writing a module that needs to grab the path of a file.

I know I can use {{ alias('@webroot') }} in the templates to get the root web folder. Is there a way I can do this in module/plugin land?

I've been looking for PHP constants or similar, and landed on $fullpath = CRAFT_BASE_PATH . '/web/' . $filename; which doesn't feel great.

Cheers!


texts: Auto-generated title based on last entry

texts:
I am attempting to make one of my sections use auto-generated titles. I am making my first entry with a title like 8000. What I need is the second entry to be titled 8001, the third 8002, etc. Each entry must have a unique title in sequence.

This is the Title Format I tried using:

{{ craft.entries.section('scripts').last().title + 1 }}

I created a test entry after that and it successfully generated a title similar to the last entry plus one. However, when I created a second test entry, the title remained the same as the first test entry, but the slug was titlexx-1. I made another test entry, same thing, with the slug titlexx-2.

What am I missing in my Title Format?

Thanks for the help!