texts: Bootstrap 4 Accordion with Matrix (and SuperTable)

texts:
I'm attempting to use a combination of SuperTable and Craft's Matrix to create a reusable Bootstrap 4 Accordion element, but I'm hitting a wall.

My code so far:

{% for row in entry.contentBuilder.all() %}
    {% for block in row.components.all() %}
        {% switch block.type.handle %}
            {% case 'accordion' %}

                                            <button class="btn btn-link" data-toggle="collapse" data-target="#collapse{{ loop.index }}" aria-expanded="true" aria-controls="collapse{{ loop.index }}">
                                                {{ block.accordionTitle }}
                                            </button>

                                            {{ block.accordionCopy }}

        {% endswitch %}
    {% endfor %}
{% endfor %}

The above is obviously producing several container divs, and not the desired card divs. I've hit a snag attempting to go several layers deep with for loop nesting and if conditionals to get it right, but it's messy and nothings come worked so far.

Essentially, the idea is that my SuperTable field contentBuilder is added to the Entry layout, so that a user can create several rows and have content types to pick from. In contentBuilder is a row (field) called components, of which accordion is a Matrix field. None of this would even be necessary if Neo was ported to Craft 3 :/ I'd worked out a perfect content builder with Neo before.

Anyone have any ideas how to go about this?


texts: How can I get an S3 asset's remote path minus the bucket name from within my plugin?

texts:
My plugin takes as an argument the id of an asset. So I'm starting from here:

   $entry = craft()->elements->getElementById($entry_id);

Assuming my asset has the url http://mybucket.mycompany.com/uploads/pdfs/myfile.pdf, how can I return just 'uploads/pdfs/myfile.pdf' from within my plugin?


texts: URL Structure - advise and thoughts of best approach?

texts:
I am currently building a website for Hot Tubs and within this there will be New Tubs, Used Tubs and Hire Tubs (each will be a top level page on the navigation, and each tub will have a details page). Each tub will only exist in one of the three sections. The templates will be different and so I have decided to go for 3 individual channels.

However, any thoughts from a URL structure/SEO etc on the different approaches to URLS for sections.
I am thinking of either keeping them all separate like so:

www.domain.co.uk/used-hot-tubs/
www.domain.co.uk/used-hot-tubs/name-of-used-tub/

www.domain.co.uk/hot-tubs/
www.domain.co.uk/hot-tubs/name-of-new-tub/

www.domain.co.uk/hot-tubs-for-hire/
www.domain.co.uk/hot-tubs-for-hire/name-of-hire-tub/

Or whether they should all be structure like so?

www.domain.co.uk/hot-tubs/used/
www.domain.co.uk/hot-tubs/used/name-of-used-tub/

www.domain.co.uk/hot-tubs/new/
www.domain.co.uk/hot-tubs/new/name-of-new-tub/

www.domain.co.uk/hot-tubs/hire/
www.domain.co.uk/hot-tubs/hire/name-of-hire-tub/

or

www.domain.co.uk/used/
www.domain.co.uk/used/name-of-used-tub/

www.domain.co.uk/new/
www.domain.co.uk/new/name-of-new-tub/

www.domain.co.uk/hire/
www.domain.co.uk/hire/name-of-hire-tub/

Any input/thoughts appreciated….

EDIT: I should add this is not an eCommerce website, although the structure could lends itself to that and that the top level domain does contain the words hottubs.


texts:
We've got a client who would like to be able to create "Child" user accounts, the idea being that someone could register and then create multiple child accounts that would inherit the settings of their parent account. It would also mean that any entries created by those child accounts would be visible, and editable, by the parent account.

My current, and only, idea would be to have Parent / Children user relations fields on the users that I would read to work out what I should be displaying to or letting the current user do, but I have a feeling that this might prove cumbersome to manage down the line and messy to code at least the way I code.

Is there a clean way of doing this, or perhaps a plugin that does this already (I've looked but couldn't find anything). I'm also open to writing a plugin that would do this, I just don't really know where to start.

This will all be happening front-end, so no need to touch the control panel in any way.


texts: How can I list Entry Types of a single Section?

texts:
The following outputs all sections and their entry types, but I'm struggling to work out how I output only the entry types from the "blog" section.

{% for section in craft.app.sections.allSections() %}

{{ section.name }}

    {% for type in section.getEntryTypes() %}

{{ type.name }}

    {% endfor %}

{% endfor %}

I thought this would work

{% for type in craft.entries.section('blog').getEntryTypes() %}

{{ type.name }}

{% endfor %}

But I've hit a wall because getEntryTypes() is an unknown method.


texts: Is it possible to add to cart with a radio input rather than a select?

texts:
I'd like to add a digital product to the cart using a radio input but all the template examples I see use select. Is it possible to use a radio input?

With Select (working):

<select name="purchasableId">
  {% for digitalProduct in entry.fontProducts.all() %}
    <option value="{{digitalProduct.purchasableId}}">{{digitalProduct.slug}}</option>
  {% endfor %}
</select>

With radio inputs (not working):

{% for digitalProduct in entry.exampleProducts.all() %}

      <input
        type="radio"
        name="product"
        value="{{digitalProduct.purchasableId}}" />

{% endfor %}


texts: Recommended way to provide user feedback in the control panel?

texts:
Is there a recommended way to provide user feedback in the control panel — something like a modal window with a simple 'ok' button to dismiss?

I am writing a plugin that syncs data between users, another channel ('accounts'), and an external service (Braintree), using saveEntry and saveUser events to create/update related records as needed. I would like to provide user feedback in the way of a modal window that reports what related records were created and/or updated. What would be the recommended 'Craft' way to implement this user feedback modal? Or is there something already built-in to support this and how might I access it? I see some advice here regarding generating a generic modal window, but not sure the best way to integrate this within my plugin. Any advice would be appreciated even if very general.


texts: Get Related entries from Category besides the category of the entry itself

texts:
I have two types of related entries for the current entry.
Category:

Interviews -> Photographer
Interviews -> Skateboarder
Interviews -> Filmer
Interviews -> Owner

I am now on an entry with the child category "Skateboarder".

At first i get entries of the same child category, so random entries of the childcategory "skateboarder".

With this:

{% set relatedCategory = craft.entries({
  section: 'news',
  relatedTo: entry.newsCategory.level(2),
  id: 'not ' ~ entry.id,
  order: 'RAND()',
  limit: 3
}) %}

My second goal is now to get other entries from the parent category "Interviews" BESIDES the current childcategory (Skateboarder)..

So only random entries of the child categories Photographer, Filmer, Owner...

how do i get this? :)
thx!!!


texts: How to manage breakpoint releases when updating Craft via composer

texts:
When logged in to Craft, the "Utilities" tab will show you all the latest releases you can update to. In some cases, it will report that you have reached a breakpoint release:

  You’ve reached a breakpoint! More updates will become available after you install Craft CMS 3.1.34.3.

If I'm updating to Craft 3.2 via composer, to ensure the all the migrations get run properly and respect that breakpoint, I believe that I would need to upgrade on the command line in two steps:

Run composer require craftcms/cms:3.1.34.3
Run db migrations
Run composer require craftcms/cms:3.2.0 (or whatever the latest is)
Run db migrations

Over time, as Craft has multiple breakpoint releases it's possible that there are several breakpoint steps that need to be hit while updating from composer directly and, as far as I know, the only place to get information on breakpoint releases is via the Control Panel.

It is also possible for plugins to add breakpoint releases. So, there is a potential scenario that you have to know of and respect both Craft and plugin breakpoints. I'm not sure how Craft handles plugin breakpoints in the CP as I have not seen any do that yet, but I believe the awareness of them would also be necessary if you are doing everything from the command line.

So, it's possible if we have an older site upgrading through several breakpoints we need to do something like:

Run composer require craftcms/cms:3.0.41.1
Run db migrations
Run composer require craftcms/cms:3.1.34.3
Run db migrations
Run composer require plugin/some-plugin:1.2.3
Run db migrations
Run composer require craftcms/cms:3.2.0 (or whatever the latest is)
Run db migrations

So, my questions:

If we are upgrading to Craft 3 for the first time, should we be targeting the first breakpoint release as the initial version that we upgrade to?
Is there any good way to know which breakpoint releases exist in Craft (aside from just seeing the next breakpoint on the CP utilities tab)?
Is there any good way to know which breakpoint releases exist in Plugins?
Can you summarize the potential issues that would arise if someone skipped breakpoints while upgrading?


texts:
I set up a basic plugin using https://pluginfactory.io/

The package name is kgrote

The plugin name is siteutilities

Then I put it in a subfolder next to my Craft project folder:

/site
|-- craft
|-- craft-plugins
  |-- kgrote
    |-- siteutilities

Then I added this to craft/composer.json:

"minimum-stability": "dev",
"prefer-stable": true,
"repositories": [
    {
      "type": "path",
      "url": "../craft-plugins/kgrote/siteutilities"
    }
]

Then I ran this command in the Craft project folder:

composer require kgrote/siteutilities

Then I got this error:

  Could not find a matching version of package kgrote/siteutilities.
  Check the package spelling, your version constraint and that the
  package is available in a stability which matches your
  minimum-stability (stable).

Here is the contents of my craft/composer.json file:

{
  "require": {
    "craftcms/cms": "3.0.23.1",
    "vlucas/phpdotenv": "^2.4.0",
    "craftcms/aws-s3": "1.0.8",
    "craftcms/redactor": "2.1.6",
    "ether/seo": "3.4.3"
  },
  "autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },
  "config": {
    "optimize-autoloader": true,
    "platform": {
      "php": "7.0"
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ]
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "repositories": [
    {
      "type": "path",
      "url": "../craft-plugins/kgrote/siteutilities"
    }
  ]
}

And here is the contents of my plugin composer.json file:

{
    "name": "kgrote/site-utilities",
    "description": "Helper functions for this website.",
    "type": "craft-plugin",
    "version": "1.0.0",
    "keywords": [
        "craft",
        "cms",
        "craftcms",
        "craft-plugin",
        "site utilities"
    ],
    "support": {
        "docs": "???",
        "issues": "???"
    },
    "license": "MIT",
    "authors": [
        {
            "name": "Kristen Grote"
        }
    ],
    "require": {
        "craftcms/cms": "^3.0.0-RC1"
    },
    "autoload": {
        "psr-4": {
          "kgrote\\siteutilities\\": "src/"
        }
    },
    "extra": {
        "name": "Site Utilities",
        "handle": "site-utilities",
        "hasCpSettings": false,
        "hasCpSection": false,
        "changelogUrl": "???",
        "class": "kgrote\\siteutilities\\SiteUtilities"
    }
}

Don't really know what I'm doing wrong here. How does composer know what kgrote/siteutilities is if it's not defined in the composer.json file? Shouldn't that be part of the "repositories" config setting?


texts:
Updating a plugin to Craft 3 (also changed its name). I know this is probably something very simple, like capitalization, but can anyone point out what's wrong?

Firefox console shows a 404 for
http://f.test/index.php?p=admin/actions/dryCalendar/calendarOccurrencesField/generateAjaxMiniCalendar
and then
Type error: Response is null

So perhaps Craft is getting the request, but $this->returnJson($response); isn't terminating the request, i.e. Craft continues to try to find a page to match?

My files are set up like this:

DryCalendar.php
controllers/DryCalendar_CalendarOccurrencesFieldController.php

is

<?php
namespace Craft;
//namespace kr37\drycalendar\controllers;
use Craft;
use craft\base\Controller;
class DryCalendar_CalendarOccurrencesFieldController extends BaseController
{
    public function actionGenerateAjaxMiniCalendar() {
        ...
        $this->returnJson($response);
    }
}

and in my Garnish js is

Craft.postActionRequest(
    'dryCalendar/calendarOccurrencesField/generateAjaxMiniCalendar',
    data,
    function(response) {
         ...
    });

Thanks for any help!


texts: Best practice for channels and structures

texts: I am wondering if there is a best practice around using channels and structures. When you have a single section you can link to that section by selecting the entry for it. For channels and structures there is no "entry" that represents the landing page where I just want to display the list of entries. Do I need to create a single section as the landing page and loop entries from my channel section in order to link to that landing page?


texts:
I'm looking for a solution that will allow me to turn a CSV or JSON data file into a table on the front-end of a website. Ideally the data would be imported into the database and then output into a table on the front-end.

I've dabbled with the plugin FeedMe, but the issue is that it has to fit into a pre-defined table. Is there any way to import this data into a table that creates columns based on the data?

The exact scenario I have is that I'm uploading a sheet of points standings that include each weekend's points accumulation and the final column is the total season points. As each weekend is finished, that new weekend is inserted as a column, thus growing the table's columns which Craft's table field can't do dynamically.


texts: How to set cookie and redirect to page one time

texts:
How can I redirect a member to account page on first visit with a cookie set? My redirect is looping now.

{% if currentUser %}
   {% set name = currentUser.firstName %}
   {% do craft.lj_cookies.set('account', name) %}

   {% set redirect = craft.lj_cookies.get('account') %}

   {% if redirect == name %}
       {% redirect name %}
   {% endif %}

{% endif %}

It's not possible to visit any other URL anymore.


texts:
I have a custom fieldtype (used within Neo block) and I need to know the ID/content of entry it belongs to, when editing the entry.

I need to both populate field values based on value in other field (if present) and also perform validation on save by comparing with other fields in same entry.

So I need to know the entry content (or at least entry ID so I could fetch those) within getInputHtml and validate functions.

I know I could use $this->model and $this->element but those don't seem to provide any data related to entry


texts: Can a model or record have conditional requirements?

texts:
I have a form that spans two pages, with a required field on both pages and an optional field on both pages:

Form A - Page 1
- Question 1 (required)
- Question 2 (optional)

[User submits partial form to database]

Form A - Page 2
- Question 3 (required)
- Question 4 (optional)

[User submits partial form to database]

The Form is creating an ElementType in Craft and the questions are Custom Fields.  The user who creates the Form can arrange any number of custom fields required or optional on any number of tabs.

How do I think about validation for this workflow? When I create a Model to validate the forms being submitted, required fields should only trigger validation errors when the page they are on is submitted.

I'm happy to do more digging myself on this one if you can help point me in the right direction, but I'm not sure how to frame what I'd like to do.  Does anyone have a better framework of how to think about how to validate conditionally required fields in the context of Models, Records, Element Types, and Custom Fields?


texts: Missing buttons after upgrading site to 2.5

texts:
Same issue as found here - but no resolution: Missing buttons in settings after update to 2.5 beta

All of the orange buttons in the CP are missing but the code is there for the css and if I select a checkmark and unselect it then press return the functions still run.

The only thing I can think that may have triggered this is there was a license discrepancy while I ran the upgrade, but I can't recreate it on a new install.

It's missing on every single browser across multiple computers.


texts: When I want to add some features to my Craft site, do I need to modify the files in the craft/app folder?

texts: I am new to Craft CMS, now I run a demo site of Happy Lager, wanna add a web crawler to fetch some data to my db. I should develop a plugin to complete this feature, but if I need to change the craft/app folder? or how my services in plugin called by my site? call from the craft/app? please help me,thank you!


texts:
Are there some logs which tell, what the member does in the backend?

Something like: "User: «John Doe» Edited this entry at this and that date".

Just a bit more information than what is written on the member account:


texts: Find entries with multiple categories with an and/or twist

texts:
I have 2 categories, model and feature which I've added as a field to an entry. I want to find entries with the model category using "or" but the feature category using "and". I believe the "relatedTo" functionality only allows one kind which is very restrictive.

{% set model = [24, 25, 26] %}
{% set feature = ['AND', 46, 47, 48] %}

{%
    set entries = craft.entries({
        relatedTo: [model, feature]
    })
%}

The code above is an example, but it returns no results.
How else can I achieve this?


texts:
I want to test for the existence of disabled entries for the logged in author in a section. So far I have this:

{% set profileEntryQuery = craft.entries()
    .section('profileEntry')
    .status(null) %}

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

{% for entry in entries %}

  {% if currentUser.id == entry.author.id %}

But the status(null) checks for disabled and enabled entries. How can I get a positive if only disabled entries exist but not enabled.


texts: Plugin to "check/uncheck" all matrix blocks while editing entries?

texts: I did a brief search and didn't pull anything up. Is there a native or easy way to "check/uncheck" all matrix blocks? We have a considerable number of them and this would be extremely helpful. Thanks.


texts:
What's the syntax for the asset field upload location? What variables are available, and what operations are possible?
We're trying to use the same field to store images from various sections and want one of them to use a different pattern.


texts: Per item ie gift wrapped with additional cost in Craft Commerce?

texts:
How can we do fields linked to products that the user can personalises when buying that product, ie writes in a custom gift message and picks an option of gif wrapped with additional cost.

Our client would have a few of these on each product some with costs and some free of charge.

We have looks at variants but seem we would have to make a new product/variant for each combination which would be a lot not variants, is there another way?


texts: Update Asset Indexes for new files in s3 not working

texts:
We uploaded a lot of images to the S3 bucket that is connected to our assets in Craft, but when we run "Update Asset Indexes" on the settings page, those images aren't added to the assets in Craft.

I'm pretty sure that the settings for the asset source is correct (images that we upload via Craft are working). And it doesn't seem to be related to a time-out, because we updated the php and nginx settings, and now it finishes after ~70s instead of 60s.

What are we doing wrong?
Is it even possible to import images this way?


texts:
How is logging handled in Craft 3? There's nothing mentioned in the docs at all.

None of the below exist.

Craft::log()
MyPlugin::log()
MyPlugin::$plugin->log()

I'm not seeing any logging in any of the other plugins I've got on this site.

Halp!


texts: Feed Me: import assets with folder structure when importing entries

texts:
Can someone confirm that is currently not possible to take the folders (directories), into which an asset are imported, from the feed, when importing entries (with assets it seems to be possible)?

I am importing pages with some images inside and I want the original directory structure of the images to be recreated with nested folders when importing the entries. e.g. my images is /folder1/folder2/folder3/image.jpg and I want the imported image to be placed in subfolders /folder1/folder2/folder3/.

It would be easy to provide the information in a separate field in the feed.


texts: Craft renders unwanted quotation marks on some tags

texts:
Breaking my head over this.

On one of the tags in the HTML template. The {% for image in category.CategorieImage %} loop. Craft seems to generate 2 unwanted quotation marks ("). These characters are messing up the lay-out as the generate an unwanted line/paragraph.

                {% for image in category.CategorieImage %}

                {% endfor %}

                    {{ category.title }}
                    {{ category.categorieDescription[:80] ~ '...' }}

                    {{ entriesNbr }}Mythes

This is what's rendered on the final page in Safari using the developers panel:

                "  "

                    Sales
                    Over succes in sales zijn vele mythes. Velen zijn inmiddels zo geworteld dat ze ...

                    5Mythes

I've used CODA to show any unwanted (invisible) characters but none seems to be there.


texts: Is it possible to restrict assets in multi region/site specific similarly to how you can restrict entries?

texts:
Is it possible to assign regions to assets similarly to the way that we restrict entries to a region for multi-region/sites?

Ideally I could specify a path for each region/site as well.


texts: Redactor - formattingAdd isn't changing code

texts:
I added a custom formattingAdd to my Standard.json file in my Redactor config. It's supposed to add the attribute data-aos="fade-right" to a paragraph tag. The "Animate" format option is showing up in the CP, but when I select that format the code doesn't change (it stays just a normal p without the data-aos="fade-right attribute).

{
"buttons": ["html", "formatting", "bold", "italic", "unorderedlist", "orderedlist", "link"],
  "plugins": ["fullscreen", "video"],
  "linkNewTab": true,
  "toolbarFixed": true,
  "formatting" : ["animate", "h1", "h2", "h3", "h4", "h5", "h6", "p"],
  "formattingAdd": {
    "animate": {
      "title": "Animate",
      "args": ["p", "data-aos", "fade-right", "toggle"]
    }
  }
}

I've tried this with classes as well, like this:

"formattingAdd": {
  "note": {
    "title": "Note",
    "args": ["p", "class", "note"]
  }
}

but the note class isn't added to the p tags either.

Any ideas why the attribute and class aren't showing up in the p tags?


texts:
When uninstalling my plugin, only one table is removed. Two others are left behind.  Any suggestions what I'm doing wrong?  Could it be naming with and without the underscore?

The good:

<?php
namespace Craft;

class Calendar37Record extends BaseRecord
{
    public function getTableName() {
        return 'calendar37';
    }
    protected function defineAttributes() {
        return array(
            'event_id'   => AttributeType::Number,
            'dateYmd'    => AttributeType::String,
            'timestr'    => AttributeType::String,
            'alt_text'   => AttributeType::String,
            'css_class'  => AttributeType::String,
            'userJson'   => AttributeType::String,
        );
    }
    public function defineIndexes() {
        return array(
            array('columns' => array('event_id', 'dateYmd'), 'key' => true),
        );
    }
}

and the bad:

<?php
namespace Craft;

class Calendar37_SubsetsRecord extends BaseRecord
{
    public function getTableName() {
        return 'calendar37_Subsets';
    }
    protected function defineAttributes() {
        return array(
            'handle'              => AttributeType::String,
            'title'               => AttributeType::String,
            'categoriesToInclude' => AttributeType::String,
            'categoriesToExclude' => AttributeType::String,
            );
    }
    public function defineIndexes() {
        return array(
            array('columns' => array('handle'), 'unique' => true),
        );
    }
}

Bad #2:

<?php
namespace Craft;

class Calendar37_ViewsRecord extends BaseRecord
{
    public function getTableName() {
        return 'calendar37_Views';
    }
    protected function defineAttributes() {
        return array(
            'subsetId'     => AttributeType::String,
            'startDateYmd' => AttributeType::String,
            'endDateYmd'   => AttributeType::String,
            'htmlBefore'   => array(AttributeType::String, 'column' => ColumnType::Text, 'required' => false),
            'htmlAfter'    => array(AttributeType::String, 'column' => ColumnType::Text, 'required' => false),
        );
    }
    public function defineIndexes() {
        return array(
            array('columns' => array('subsetId', 'startDateYmd' ), 'key' => true),
        );
    }
}


texts:
I have a list of categories that I am listing out, grouping by alphabet.  The issue is the list goes A H B C D E...and so on.  Why would it go in that order?

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

{% set categoriesGroup = categories|group('title|slice(0,
1)|replace("/[^a-zA-Z]/", "0-9") | upper') %}

{% for letter, categoriesInGroup in categoriesGroup %}
{{ letter }}
{% for category in categoriesInGroup %}

{{ category.title }}

{% endfor %}

{% endfor %}


texts: After installing Craft 3 successfully, I can't access the admin panel while using the correct credentials. I get an "invalid username or password" message.


texts: I have set up a custom field for a category group. How do I get the value of this field in a loop that goes through entries? Each category in the group could have this field's value set as true or false (light switch). I.e. I need to see what category is related to the current entry and then look up the value of this field - there is some html I want to show only if the value is true.


texts: Is there a way to convert a Craft MySQL database to PostgreSQL?

texts:
I have an existing Craft installation using MySQL and I've only recently realized the error of my ways and would like to convert the database to PostgreSQL.
Is this possible?


texts:
I am following Andrew Welch's post here - https://twitter.com/nystudio107/status/1168220713158942720?lang=en

I used the gatsby-config.js file he shared here - https://gist.github.com/monachilada/af7e92a86e0d27ba47a8597ac4e4b105

However, when I edit fields in the Live Preview, I get the following error:

UNHANDLED REJECTION Schema must contain uniquely named types but contains multiple types named "Craft".

    const { createHttpLink } = require('apollo-link-http');
    const fetch = require('node-fetch');
    const store = require('store');
    const sourceNodes = require('gatsby/dist/utils/source-nodes');
    require('dotenv').config();

    const craftGqlUrl = process.env.CRAFT_GQL_URL;
    const craftGqlToken = process.env.CRAFT_GQL_TOKEN;

    module.exports = {
      plugins: [
        {
          resolve: 'gatsby-source-graphql',
          options: {
            typeName: 'Craft',
            fieldName: 'craft',
            createLink: () =>
              createHttpLink({
                uri: `${craftGqlUrl}`,
                headers: {
                  Authorization: `Bearer ${craftGqlToken}`,
                },
                fetch: (uri, options) => {
                  const token = store.get('X-Craft-Token');
                  return fetch(
                    `${uri}${token !== undefined ? `?token=${token}` : ''}`,
                    options,
                 );
                },
              }),
          },
        },
      ],
      developMiddleware: app => {
        app.use('*', (req, res, next) => {
          if (req.query.token) {
            store.set('X-Craft-Token', req.query.token);
            sourceNodes();
          }
          next();
        });
      },
    };

Any ideas?

Thanks


texts: When does Craft change or delete template caches?

texts:
My question is regarding template caching in Craft. I want to know when does Craft actually change the cache or delete old cache.

Let's say that I am caching a chunk that just displays the entry title.  Does Craft detect this change when I reload the page and hence change the cache as well? I don't know if that makes sense.

Also, I wanted some insight into the cache structure. I was caching some chunks that displayed an entry's title, description etc. The code is something like this:

{% for document in resultset %}
    {% cache using key document.entryId ~ "searchresult" %}

        {% set entry = craft.entries.id( document.entryId )[0] %}

        <div>{{ entry.title }}</div>
        ...
    {% endcache %}
{% endfor %}

When I looked into the cache tables in the database it seems like the cache is associated with an entry using the entry id.

I wanted to know how Craft knows which entry this cache relates to since the key that I have passed could have been anything and I could have cached a category or something instead of an entry. I am very confused as to how this magic is occurring.


texts: EVENT_DEFINE_ADDRESS_LINES not pushing response back to Craft Commerce

texts:
I have a plugin to reorder the address lines in Commerce. Basically to move the Phone Number to the bottom as it drives all my clients nuts.
While the final array, addressLines is the correct array and all looks ok it does not seem to be passing $addressLines back into getAddressLines function in /src/models/Address.php Am I missing the obvious here or is there a bug?
Event::on(
            Address::class,
            Address::EVENT_DEFINE_ADDRESS_LINES,
            function(DefineAddressLinesEvent $event) {
                // @var array $addressLines
                $addressLines = $event->addressLines;
                // Modify default address lines array
                $addressLinesNewOrder = [
                    'attention',
                    'name',
                    'fullName',
                    'address1',
                    'address2',
                    'address3',
                    'city',
                    'zipCode',
                    'stateText',
                    'countryText',
                    'phone',
                    'alternativePhone',
                    'label',
                    'notes',
                    'businessName',
                    'businessTaxId',
                    'custom1',
                    'custom2',
                    'custom3' ,
                    'custom4',
            ];
            uksort($addressLines, function($x, $y) use ($addressLinesNewOrder) {
                return array_search($x, $addressLinesNewOrder) > array_search($y, $addressLinesNewOrder);
          });

        return $addressLines;

    });

https://craftcms.com/docs/commerce/3.x/addresses.html#address-lines
https://craftcms.com/docs/commerce/3.x/extend/events.html#defineaddresslines


texts: How to call abstract method from interface

texts:
I would like to use a method of fileExists. It belongs to VolumeInterface.
https://docs.craftcms.com/api/v3/craft-base-volumeinterface.html

I suppose the code would be like \craft\base\Volume::fileExists($path).

However, Craft returns an error;

Non-static method craft\base\VolumeInterface::fileExists() cannot be called statically

Could I ask how I should modify the code?


texts: New shipping/billing address fields getting auto-populated (Craft Commerce)

texts:
The shipping and billing address forms in our checkout are based loosely on the ones from the example templates.
With the example templates, if you checkout as a logged in user and that user has previously saved addresses, the 'new address' form fields get pre-populated with the data from the user's first saved address.
If I output cart.shippingAddress, I can see that the user's first saved address has already been automatically assigned to the cart before the user has actually selected/entered an address.  So I presume that's why this is happening.  And I don't necessarily have a problem with a saved address being automatically selected. It's just the fact that it is pre-populating the new address form fields that is the problem.
The value attribute on the form fields looks something like this:
value="{{ cart.shippingAddress ? cart.shippingAddress.firstName : '' }}"

So obviously I can just remove the value attribute altogether to solve this problem.  But then the field would not be repopulated in the event of an error in the submitting of the form, meaning that the user would need to re-enter all their details - not ideal.
So is there any way to prevent the form fields from being pre-populated in this way?
Thanks


texts: Memory issue when updating all entries from a channel (allowed memory size of X bytes exhausted (tried to allocate Y bytes))

texts:
I'm trying to do a stock update for all entries within a channel with a cronjob once a day, and I can't achieve it, because I always get Allowed memory size of X bytes exhausted (tried to allocate Y bytes).

Entries are around 2000 and the server is an EC2 medium instance. The cron I'm using is:

0 9 * * * wget -O /home/ubuntu/cronStock http://domain.com/actions/garp/cron/changeStock

I will try to create a simpler script without all the loaders Craft calls in a controller, but I'm not sure it will work.

Code:

public function actionChangeStock()
{
    foreach ($this->getAllFromChannel('productVariants', 10) as $key => $entry) {

        //$entry = $this->getElementByField("3081001100390", ElementType::Entry, null, "variantSku");
        //$entry->enabled = false;
        $entry->getContent()->setAttributes(array(
            'variantStock'  => $this->getStockFromGarp($entry->variantSku)
        ));
        $success = craft()->entries->saveEntry($entry);

        echo $entry->variantSku.': '.$entry->variantStock.'<br>';
    }
    die();
}

protected function getAllFromChannel($channel, $limit = null) {
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = $channel;
    $criteria->limit = $limit;

    return $criteria->find();
}

How can I fix this problem?


texts: Craft can't connect to the database (using ec2)

texts:
I'm trying to set up a Craft based site with ec2 and it won't connect with the info in db.php.

I've reinstalled the Craft files and also run all .phps through http://phpcodechecker.com to check for errors and nothing. Logs all check out to be in working order. And I've followed every step exactly with this tutorial: https://solspace.com/blog/spinning-up-a-craft-cms-development-site-on-amazon-ec2

Here's what my db.php file looks like:

return array(

    // The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
    'server' => 'localhost',

    // The name of the database to select.
    'database' => 'Craft',

    // The database username to connect with.
    'user' => 'root',

    // The database password to connect with.
    'password' => '*******',

    // The prefix to use when naming tables. This can be no more than 5 characters.
    'tablePrefix' => "‘craft'",
);

I also checked .htaccess files.


texts:
Has anyone made it possible to edit entries directly in the admin area (i.e. /admin/entries/{section}) without having to go into each individual entry?

I've built a voucher system that the users need to quickly be able to tick off a number of vouchers as i.e. a family comes in - not having to open five voucher entries and tick off one at a time.

Having a light switch field where this "Voucher Status" field is would be perfect.

If that's not possible, even adding a button that I could trigger an ajax action on would be fine - I'm just not sure how to go about that either. I haven't tried to customise the admin area of Craft before.

Thanks!


texts: What is the max # of version history for any given entry?

texts: I can't seem to find anywhere mentioning what the max # of versions a given entry can have--I would assume its unlimited (given unlimited DB space).


texts:
I've setup a 'posts' section with a collection of posts. I'm trying to add pagination to the individual post entry.

I've copied the pagination code from the Craft CMS documentation but I'm having issues with the slug.

The problem is my slugs are like: posts/post-1, posts/post-2, posts/post-3 etc.

And when you click on the 'previous' or 'next' post the slug is like 'post-3/p3' which the 'p3' on the end.

How do I convert that to my normal post slug of just 'post-3'.

Thanks!

Here is my code:

{% set query = craft.entries()
        .section('posts')
        .limit(1) %}

{% paginate query as pageInfo, pageEntries %}

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

        {% if pageInfo.nextUrl %}
            Next Page
        {% endif %}


texts: Garnish - Event when selecting a category

texts:
I have a "Categories" field in my section. I want to perform some JavaScript actions when a category is selected.

Is there any built-in event which will be triggered at that point?


texts: Auto generating slug with custom fields or ID

texts:
I'm not sure I've seen this exact question, but I'm curious how I can include custom and/or auto-generated parts of a slug. It's not the URI creation, but the slug itself.

For Instance:

{slug}-{id} would turn into lorem-ipsum-dolor-sit-amet-123456 on submit

and from there on the variable {{entry.url}} would be example.com/lorem-ipsum-dolor-sit-amet-123456.

I know ExpressionEngine had an option in the Channel preferences called URL Title Prefix, so this would go along those lines, but more auto-generated than a predefined set of words.

If it changes things, this is specifically for Commerce and Digital Products at the moment.


texts: Repopulate dateTime field in plugin settings page

texts:
In my plugin settings page, I have a startDate input which is a dateTime field.

_settings.html

{{
    forms.dateField({
     'label': 'Start Date'|t,
     'instructions': 'Choose a date'|t,
     'id': 'myStartDate',
     'name': 'myStartDate',
     'placeholder': 'mm/dd/yyyy',
     'value': settings.myStartDate,
     'errors': settings.getErrors('myStartDate')
    })
}}

My data is getting saved correctly - I can see it:

json

  ....
"myStartDate": {
    "date": "2015-04-13 05:00:00
}
  ....

So I thought cool. I just need: myStartDate.date and all is well. No luck.

What is curious to me, is when I fill out my start date, but my form fails validation, the date that I have entered is correctly repopulated. I don't have to re-enter the date.

But, once I successfully submit my settings, and then come back, my date field is no longer populated.

I've tried myStartDate and myStartDate.date and myStartDate|date("m/d/Y") but all with no luck.

I feel like I'm abusing this community with so many questions lately. I know the dateTime field needs to be a dateTime object - and I assume that's why it's not working for me. I'm not passing it what it needs.

Thank you for your time!


texts:
I am new to craft and I need help to understand how plugins work.
I am trying inject these functions to the CraftVariable

{% for item in craft.plugin.exampleFunction(test).hide("noTitle") %}

craft.plugin.exampleFunction(test) is working perfectly
but .hide() is not. Can anybody tell me how to call this function?


texts: Sprout Forms - Redirect to same page with query string

texts:
I'm looking to redirect the user to the same page that they were on, with an additional query string.

Is this possible?

Thanks
Adam


texts: Importing Blog posts from Drupal into Craft

texts:
I am using InstaBlog plugin to manage Blogs in Craft. I would like to import some 1000 blog entries from Drupal. I know it has an option to import blogs from WordPress. I was wondering if this can be done from Drupal?

Any help is highly appreciated!


texts:
Is Craft's .search() diacritic-insensitive?

(If not, is there a way to make it so?)


texts: Is it possible to create a new asset from an image URL?

texts:
I've created several entries from a feed from the eBay API, but I would like to add images to the entry too!

I've managed to get an array of URLs, which I would like to import into an assets field that I have on the new entries.

I saw a post from Brandon from a couple years back suggesting it was not possible to do this, unable to find anything more up-to-date.

Could I grab the image with cURL in my plugin then create a new AssetFileModel and some how sync the temp image file with Craft somehow? As a follow up question how would I add multiple images to the assets field on my new entry?

Thanks
Joe


texts: Entries by non-contiguous postDate years

texts:
I'm trying to display and paginate entries by years, that aren't necessarily contiguous.

{% set limitPerPage = 6 %}
{% set eagerFields = [
    'title',
    'press_release_name',
    'press_release_date',
    'press_release_body',
] %}

{% set pressEntries = craft.entries({
    section: 'pressReleases',
    with:    eagerFields,
}).limit(null) %}

{# I plan on building the query dynamically later, I just want test syntax here #}
{% set dateQuery = 'and, >= 2012-01-01, < 2013-01-01' %}

{% paginate pressEntries.postDate(dateQuery).limit(limitPerPage) as pageInfo, pageEntries %}

This works fine, but I'm wondering how to build upon the dateQuery to return more years with something like:
'and, >= 2012-01-01, < 2013-01-01, >= 2014-01-01, < 2015-01-01'

Is this possible?


texts:
A client of mine uploads multiple, complex SVGs (2MB and larger) to an asset field. Unfortunately, Craft CMS isn't able to automatically generate thumbnail images (with a reduced filesize, not just rescaled!). As a result, the control panel pages for entries render unbearably slow or even crash in the browser, as all SVGs are loaded into the same view.

Is it possible to set up Craft to display a generic icon for SVGs instead?


texts:
Has anyone had any success with Printmaker PDF plugin?

I’m not sure where to put the tags?  The only way I can get the template to actually load is to add the Printmaker tags at the end of the document.  In which case, the "Download CV" link further up the page doesn’t work.  It seems {{ pdf.url }} HAS to appear AFTER the Printmaker tags.  If I move the Printmaker tags further up I get the error "Internal Server Error - Requested HTML document contains no data.”.

Also, i’ve linked to a print stylesheet and when I do get a document to be created the print.css is ignored?

Thanks


texts:
I'm trying to create a Modal and have a question:
my code is:

Modal header

            {{ include('srgooglemaps/infobubble/addEntry'}}

<button id="newInfoBubble"  type="button" class="btn submit" value="test">new</button>

Javascript

$("#newInfoBubble").click(function(){
    $modal = new Garnish.Modal($('#my-modal'));
});

How do I manage to make overscroll auto working? My included template is higher than the modal and I would like to add a scrollbar or another option to make everything visible.


texts: How can I get the type of a field using Twig?

texts:
I would like to loop through all the fields of a field layout tab form the current entry.

This is working fine to get the field name and value:

{% for fieldLayoutField in entry.getFieldLayout().getFields() if fieldLayoutField.tabId == 50 %}
    {% set field = craft.app.fields.getFieldById(fieldLayoutField.id) %}
    Field name: {{ field.name }}
    Field value: entry[field.handle]
{% endfor %}

But I need to go a step further, by checking the field type, and then handle something different depending of the type.

Example:

{% if field.type == 'dropdown' %}
    <select>
        {% for option in field.options %}
            <option value="{{ option.value }}">
                {{ option.label }}
            </option>
        {% endfor %}
    </select>
{% endif %}

As {{ field.type }} and {{ entry[field.handle].type }} aren't defined, I can't guess properly when this is, for example, a Plain Text field or a Dropdown field.

I could guess some fields type, by some checks like bellow, but it sounds very dirty:

field.columnType
returns text if a Plain Text field.
field.options | length returns true if a Dropdown field.

For some others, like the Lightswitch field, I don't know exactly how to guess the type properly.


texts: Why is ElementsService forgiving of an element type whose populateElementModel() method doesn’t return an actual element model

texts:
In the 2.3 release notes, one item reads:

  ElementsService is now forgiving of an element type whose populateElementModel() method doesn’t return an actual element model.

I'm curious what the use case is here — When would populateElementModel not return a BaseElementModel, and why would that be okay?


texts: Craft Commerce: Variable "product" does not exist

texts:
My shop has one product. As such there isn't much point in me having a page displaying all products.

When I paste in my template code for my single product into Cart Commerce's main index template I get the error Variable "product" does not exist on the following code:

{% for purchasable in product.variants %}

    <option {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %} value="{{ purchasable.purchasableId }}">{{ purchasable.description }} {{ purchasable.price|currency(cart.currency) }}</option>

{% endfor %}

Why is this being thrown up and how do I remedy this?


texts:
I wrote a little plugin that reads some entries (Events) from my events section, orders them in a calendar-like structure and returns them to be displayed in a template. (I couldn't do this twig-only)

Now, I would like to use {% cache %} on the calendar. I know that Craft normally busts the template cache when updating/adding an element if it detects, that those elements were used in a cached template.

Now as I am fetching the elements in my custom plugin with

$criteria = craft()->elements->getCriteria(ElementType::Entry);

I assume, that Craft can't know when to bust the cached output of the plugin.

Is there a way (with the TemplateCacheService for example) to make sure that this cache also gets busted when saving/updating one of my events?

I wonder if I can do this just in twig or if I would have to put a hook before the element gets saved? How does it relate to the cache key?

Any hints, which direction to take?

Thank you,

Robert

Update:

Okay, I'll provide some more details:

My Plugin looks (simplified) like this:

// MyPluginVariable.php:
public function getMonthWithEvents($month, $year)
{
    ...
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'events';
    $criteria->date = ['and', '>='.$monthStart, '<='.$monthEnd];
    $eventsInMonth = $criteria->find();

    $month = [];

    // Put events in month array with dates etc....

    return $month;
}

In the twig template, I do this:

// agenda.twig
...

{% cache %}

    {% set month = craft.migrosAgenda.getMonthWithEvents(10, 2016) %}

    {% for day in month %}
        ...
        <div class="day">
            {{ day.date|date('d.M.Y') }}
            {{ day.event.title }}
            {{ day.event.date }}
        </div>
    {% endfor %}

{% endcache %}


texts: Craft 3 This field’s Volume configuration is invalid

texts:
I just upgraded a Craft 2 site to 3, and am getting this error from one of my matrix blocks.

This field’s Volume configuration is invalid

This what it looks like in backend:

Oddly enough, I went into settings and resaved the field, not touching anything else, and now I can atleast see the images:

However, I cant save the entry now, and am greeted with the same error:

This field’s Volume configuration is invalid

** Updated Volume Assets Screenshot **


texts: User Profile page - one user can only access one page

texts:
I'm new to craft, in fact I haven't built a site with it yet, but am looking forward to getting my teeth into this interesting and seemingly very flexible CMS.

I am about to embark on a medium sized website build and have a question that is kind of a deal breaker for choosing the CMS. My question is:

Can I create users that have their own profile page, who can only edit their own page and do nothing else? This won't be a public registration, but administered internally, however they must be able to maintain a profile containing images, text and predetermined layouts that they can choose between.

Thanks guys!

Brad,
Thanks so much for your response.

Regarding the URL - could it be configured to be something like mydomain.com/members/membername instead of passing a url option?


texts:
I need to implement quiz feature in which a few questions will be asked to user.

Could anyone please let me know if there is any plugin for it.


texts:
I'm using the Element API and would like to return content based on it's handle. The two handles I am trying to return are called appLogo and appVideo:

'api/featured-apps.json' => [
  'elementType' => 'Entry',
  'criteria' => [
    'section' => 'apps',
    'appFeatured' => '1',
  ],
  'transformer' => function (EntryModel $entry) {
    return [
      'title' => $entry->title,
      'logo' => $entry->appLogo,
      'video' => $entry->appVideo,
    ];
  }
],

This does not work, do I need to access images/videos in a different way? Ideally, I'd like the relative path returned for both logo and video.


texts: Programmatically create a product using Craft Commerce 2?

texts:
The docs for v1 mention a method craft()->commerce_purchasables->saveElement().

This is omitted in the docs for v2. Does anyone know how I can create a product programmatically in PHP?

    $product = new Product();
        $product->title = "Test Product 1";
        $product->typeId = 2;
        $product->enabled = true;
        $product->promotable = true;

    $variant = new Variant();
            $variant->isDefault = true;

    $product->setVariants([$variant]);

    Craft::$app->getElements()->saveElement($product);

With the above code I get the following error:

Call to a member function getProductTypes() on null

I know the typeId is correct, because I can output it on a product template with {{ product.typeId }}


texts:
I'm updating a site from Craft 2 to Craft 3 and can't find the equivalent of the 'Category Sources' plugin? It's really useful when it comes to restricting the source for related entries by the category the entry belongs to. Does anybody know of an alternative solution?

Thanks.


texts: Craft Commerce: Sub total before tax in cart?

texts:
I'm looking to get the sub total of all items in the car before and tax is added on. The example shop code doesn't seem to have this implemented. Is it possible to do?

  Total Discount: {{ cart.totalDiscount|currency(cart.currency) }}

  Total Shipping: {{ cart.totalShippingCost|currency(cart.currency) }}

  Total Tax: {{ cart.totalTax|currency(cart.currency) }}

  Total Tax (inc): {{ cart.totalTaxIncluded|currency(cart.currency) }}

  Item Total: {{ cart.itemTotal|currency(cart.currency) }}

  Base Discount: {{ cart.baseDiscount|currency(cart.currency) }}

  Base Shipping Cost: {{ cart.baseShippingCost|currency(cart.currency) }}


texts: Is it possible to disable dev output in a template when devMode is true?

texts: For example the template just outputs JSON, which breaks when Craft's devMode logging is added.


texts: How would you recommend integrating craft with Algolia

texts:
Has anyone had experience integrating craft with algolia: https://www.algolia.com for realtime search of craft entries.

It seems like there are a few potential approaches with their Php and Js libraries. Does anyone recommend a particular approach or best practice for integrating a service like this with Craft.


texts: How to apply multiple Twig filters to text - SOLVED

texts:
**

After continuing to play around with this I realized that I did not need to add nl2br, adding hacksaw was actually removing the formatting from the rich text field.  I opened a new question here
 if anyone can help or has encountered this issue any help would be appreciated.

**

I have a line

{{ workItem.summary | hacksaw(words='75', append='...') }}

I need to add

 nl2br

to it.  I have tried

{{ workItem.summary | nl2br | hacksaw(words='75', append='...') }}

and

{{ nl2br (workItem.summary hacksaw(words='75', append='...')) }}

Neither worked.

Can anyone shed some light on the syntax I need to get this to work correctly?


texts: 301 redirects are inserting "index.php" into URLs

texts:
I'm in the process of moving a site from one domain to another, so I'm setting up 301 redirects on the old domain. Everything goes well, except when the 301 redirect happens, "index.php" is inserted into the URL.

Here's the relevant code in my ".htaccess" file:

<IfModule mod_rewrite.c>
    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\.newdomain\.com [NC]
    RewriteRule ^(.*)$ http://newdomain.com/$1 [L,R=301]

    RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
    RewriteRule ^(.*)$ http://newdomain.com%{REQUEST_URI} [R=301,L]
</IfModule>

FWIW, I've verified that "omitScriptNameInUrls" is set to "true" and my server does support PATH_INFO.


texts: Pull Matrix Block from Multiple Entries without Showing Duplicates

texts:
I have a set of entries I am pulling ID. (group)
Each of those entries has a Matrix Block. (people)
That Matrix Block Type (person) has an entries field.
In some cases the same entry (person) is assigned to multiple entries in the group via the Matrix Block.
I want to show the matrix blocks from my group only once without duplicates.
Pseudo Code
{% set group = craft.entries.id([100,200,300]) %}

{% for entry in group %}

    {% for person in entry.people %}

        {% if person not already displayed %}

            {% set person_entry = person.entry.one() %}

            {{ person_entry.title }}

        {% endif %}

    {% endfor %}

{% endfor %}


texts:
I'm using eager loading for retrieving some images for my gallery:

{% set employments = craft.entries({ section: 'employments', with: ['photo] }) %}

This works fine and I can see all images on my page.

I'm using focuspoint (https://github.com/smcyr/Craft-FocusPoint) with imager for resizing the images. I've set a different focuspoint for every image.
But whenever I try to get the focuspoints of a image:
photo[0].focusPctX, all images have the same focuspoints (50).

Whenever I try to retrieve the images without the eager loading function, it works fine.

I've created a new issue @focuspoint github.

Is there someone that had the same problem, or has a solution for this?


texts: Accessing array/object attributes in Twig

texts:
There are three methods for that:
object.attribute

object['attribute']

attr(object, 'attribute')

How are these different from each other?


texts: Filter conditions on related UserModel in custom Record

texts:
My plugin has a custom ResponseRecord with relations to a UserRecord and ElementRecord as follows:

public function defineRelations()
{
    return array(
        'user' => array(static::BELONGS_TO, 'UserRecord', 'user_id', 'required' => true, 'onDelete' => static::CASCADE),
        'element' => array(static::BELONGS_TO, 'ElementRecord', 'question_id', 'required' => true, 'onDelete' => static::CASCADE),
    );
}

Can I query custom fields on the user or element models when querying with findAll() on this custom ResponseRecord record? If not, is there a more efficient way than iterating through all ResponseModel and UserModel?

For example, I need to query where user.industry (custom text field) is 'Agriculture' and where the ResponseRecord's year attribute is 2016.


texts: I have a "/5minutes" url in routes.php and people keep typing in "fiveminutes". Is there a way to call a 301 redirect directly in routes.php or would I need to set up an action in my plugin (or alternatively mess with server settings)?


texts: Extend a Commerce (v2) order template in the control panel

texts:
Is there a way to extend (extend, not replace) the default Commerce order templates in the control panel?
I'd like to display important custom fields in a prominent way on the first tab. (and not tucked away on a second tab as is normal with custom fields)


texts: Using data within a mixed attribute type to query Craft entries dates

texts:
I wish to have a custom fieldtype which contains the standard datetime field abilities along with storing an extra piece of data. I have created a custom fieldtype for this with a mixed attributetype to store the data as JSON.

However I am having problems when I try to query some of the data from the frontend.

For example to pull out a specific piece of data I am currently doing:

variableName.date

This correctly pulls out the date I have stored. However when using this in the example:

craft.entries({ type: 'sectionName', customFieldtype.date: '>=' ~ now|date(c) }).order('customFieldtype.date asc').first()

I get errors as when Craft converts this to SQL it's converting these to column names and customFieldtype.date doesn't exist.

Is there any way around this bar having to re-create the built in craft entries calls in pure SQL?


texts: Customize activation and other system emails

texts:
Just as the title indicates, I'm looking for a way to customize the email template of the "click here to activate your account" email that is sent to users when they register. I would also like to know if its possible and how to do this with other system email templates, such as the reset password link email.

Edit:
I see you can edit the plain text emails at Settings > Email > Messages however I would like to be able to define a twig template to handle creating HTML versions of these.


texts:
I recently upgraded a site from Craft 2 to Craft 3, so I'm trying to figure out what was deprecated and caused this error.

At the top of the page I have this

{% set solutions = craft.entries.section('solutions').level(1).all() %}

And I'm trying to invoke a dropdown menu like so

    {% nav solution in solutions.limit(1) %}
        solutions(current)
    {% endnav %}

        {% nav solution in solutions %}

                {{ solution.title }}

        {% endnav %}

Before I didn't have .all() at the end, but only the first menuitem was showing up.
When I added .all() in, I get the error "Impossible to invoke a method ("limit") on an array."


texts: Extending Assets with oEmbed video references

texts:
Disclaimer: I'm new to Craft, making the jump from WordPress and looking for implementation advice to a specific requirement.

In addition to images, I would like to be able to manage oEmbed video references (mostly Vimeo URLs, and any associated metadata) from one central location: Assets. This way, when specifying the media assets for an entry, I can manage images and video together in one field, and can use drag & drop to order my content.

My intention is to extend the Assets UI with an additional button (after "Upload Files", called "Add oEmbed") that will generate a static file which acts as a pointer to the embed-able video.

Is this a sensible approach? If not, how would you suggest I go about it?


texts: What's the best way to link to an entry in a template?

texts:
I have the following code and I'm looking for the best way to link to another entry page.

request a quote

I tried something like this with no luck:

request a quote

Here's the entry: http://grab.by/Ax6s

Thanks in advance for the help.


texts: Parse html on first and last occurrence of a matrix block type in a series of that same block type

texts:
I'd like to wrap a series of block.type (images and description) in a div. So at the first iteration of this block type it needs to parse the start of the div. In the last iteration of this block type it needs to close the div.

I tried something like this, if there is a next block from the same type but no previous block, start the div and visa versa:

{% for block in entry.detailMatrix %}
    {% if block.type=="images" %}
        {% if block.next().type == 'images' and not block.prev().type == 'images'%}
            <div class="section" >
        {% endif %}
            {{block.image}}
            </div>
        {% if block.prev().type == 'images' and not block.next().type == 'images'%}
            </div>
        {% endif %}
    {% endif %}
{% endfor %}


texts: ResaveAllElements task generates fatal error after adding locale

texts:
After adding a new locale to the site, the ResaveAllElements task started going off, and after a while stopped progressing. When i checked the logs it said:

PHP Fatal error:  Maximum execution time of 30 seconds exceeded in .../craft/app/framework/db/ar/CActiveRecord.php on line 694

I thought the point of tasks and subtasks was to prevent this thing from happening, but i might have misunderstood how it actually works.

Unfortunately i have little to no control over the server configs (apache and php).
How can i work around this problem?

Craft Pro 2.3.2644

OS: Debian GNU/Linux 7.8 (wheezy)

PHP 5.4.36


texts: Architecting a Solution with many Sites within a Site (Chapters) - How many sections can Craft Handle?

texts:
I am working on a plan for a site build that includes national content as well as many chapters' content. The latter has a number of requirements that are leading me to using separate sections including a structure for general pages and news, and events channels.

So looking at 3 sections per chapter and starting with around 20 chapters with more to come over time.

I am not worried about the manual setup of these (albeit it's not ideal); however, I am concerned about hitting limits either in the interface and/or performance of Craft that I just may not be as familiar with.

As chapter numbers grow, will this be too many sections for Craft to handle?


texts: Multiple instances of Craft in same hosting account root

texts:
I want to have multiple instances of Craft, ideally running inside the same cPanel account root.
I note from the doc on Directory structure that there are separate config path variables that can be set for:

CRAFT_CONFIG_PATH
CRAFT_STORAGE_PATH
CRAFT_TEMPLATES_PATH
CRAFT_VENDOR_PATH

If these system assets for a given Craft instance are in a per instance child folder above web root, what are the implications for the location and variants of:

modules
.env
composer.json
composer.lock
craft

Should these all be duplicated per instance into the same child folder as well?


texts: How I’ll get an entryId based on a given URL?

texts:
I want to configure deeplinks for an app and want to set up 'universal links'. Right now I'll send an entry id to the element api to get the right content. But with universal links I didn't have a entry id, only a url. Based on the url I'll need to get the right entry instead of based on the entry id.

Down here is my current endpoint to get the right entry based on a id. But if I didn't have an id how can I get the entry id based on the url.

for example website.com/pages/welcom has entry id 123, in the app I can open it with sending 123 to the api endpoint. With universal links I open a link from my mail app for example then the app launches and I can send 'website.com/pages/welcom' to the api but how I'll get the right content from that page that has entry id 123.

'api/pages/<entryId:\d+>' => function($entryId) {

        requireLogin();

        return array(
            'elementType' => 'Entry',
            'criteria' => ['section' => 'pages', 'id' => $entryId],
            'transformer' => function(EntryModel $entry) {

                $bodyBlocks = [];
                foreach ($entry->contentBlokken as $block) {
                    switch ($block->type->handle) {
                        case 'tekst':
                            $bodyBlocks[] = [
                                'text' => $block->description->getParsedContent(),
                            ];
                            break;
                    }
                }

                return array(
                    'id' => $entry->id,
                    'title' => $entry->title,
                    'description' => $bodyBlocks,
                );
            }
        );
    },


texts: Testing / Fixtures: setup Entries in Structure

texts:
Background: I have experience with vanilla PHPUnit testing of projects, but this the first attempt at both testing a Craft project and using Codeception for testing.

Case: I have a section of type structure of maximum 2 levels deep. The URL I want to test, i.e. /some-section/some-entry shows content of both the parent and children, which is aggregated through some business logic.

Problem: I am having trouble setting this up in fixture files. I created a fixture class the extends the EntryFixture class. But I have not figured out how to create a data file that creates the parent-child relation.

When I go through the code, that relationship would normally be made through setting the newParentId. But no ID exists. I have not figured out a way to define this in the data file. For now I am going to use two fixture classes, one for the parent entries, and one for the child entries. In the fixture class for the child entries I then overrule the getData-method so that I can resolve the actual parentId by querying the database for the previously loaded fixture records.

However this does not seem the cleanest way and I wonder if I am missing the obvious solution here?


texts:
I have a craft2 site running quite happily with 8 languages.

I noticed recently that a dropdown selection of category entries is not working when the locale is changed to chinese (locale = 'zh').

So the list of countries to search on does not  render fully - only some countries are shown.

Here is the real world example
https://seafarerhelp.org/en/seafarers-directory
https://seafarerhelp.org/zh/seafarers-directory

check out the search country dropdown. It is using this template code:

{% set countries = craft.categories({
    group: 'locations',
    limit: null,
    level: 1,
    order:['title asc']
   })
%}

In english we get the full list.
In Chinese (select the locale) we get only a handful.

Other countries seem fine. I am stumped. Have looked for oddities in structure but can find none. Ironically this area of the site is not translated but this doesn't present any problem with other locales/languages


texts:
I'm expanding my Craft website with a small Module, internal to this project. The module currently only defines a new input-field (extending craft\base\Field).

I have dumped the autoloader from composer and my config/app.php only contains the registration of this module:

<?php
return [
    'modules' => [
        'simple-markdown-editor' => [
            'class' => \codeisland\simplemde\MarkdownModule::class,
        ],
    ],
    'bootstrap' => ['simple-markdown-editor'],
];

This setup works and the new field shows up in the Admin CP. But: as far as I understand the bootstrap-entry, it's only needed if the module needs to be executed on every page render. The Craft documentation says as much:

  TIP: If your module doesn’t need to get loaded on every request, you can remove its ID from the bootstrap array.

Since the module only defines an input-field for the Admin CP, it doesn't need to be loaded on every request. But if I remove it from the bootstrap-array, it's not loaded at all.

Do I need to add additional config? Or am I just misunderstanding the documentation?


texts: How could I include another template on a click with ajax?

texts:
I am a newbie with ajax and I have to display a template only when clicking on a button. This template is weighing and it will be on all pages, so I want to use ajax.

Someone can help me?


texts:
I’ve been carefully following the instructions laid out at http://una.im/2013/08/13/the-absolute-beginners-guide-to-setting-up-craft-on-mac.html# and http://a73cram5ay.blogspot.com/2015/04/installing-craft-cms-on-mac-os-x-using.html to get Craft up and running. I’ve meticulously followed the steps on both, but am stuck in the same place either way. I’m a total noob, so hoping it isn’t something stupid I’ve overlooked.

Step 5 in the Almost Profound guide and P5 in the a73cram5ay guide are not working for me. I have the MAMP site started and the tab is open in my browser (Chrome). I’ve tried both the socket and standard connections (images of my settings attached). Still, neither will connect.

I get the message:

Connection Failed!

Unable to connect to host 127.0.0.1, or the request timed out.

Be sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently 10 seconds).

MySQL said: Can't connect to MySQL server on '127.0.0.1' (61)

I am the administrator and have privileges…

What am I doing wrong? I really want to try out Craft : (

Thanks for your time,

Shawn


texts: add categories to sitemap plugin through the renderSitemap hook

texts:
I'm trying to setup a sitemap using the craft-sitemap plugin, however it only covers sections by default and I need to add category groups into it, as half of the URLs are in categories.

I can see the Service Methods section in the docs that says that "There’s several service methods made available to add items to the sitemap."

Hooks
renderSitemap

Add a renderSitemap method to your plugin to add items via the various service methods listed below.

Here’s an example plugin hook method with comments:

addCategoryGroup(CategoryGroupModel $categoryGroup, [$changefreq, [$priority]])

Adds all categories in the group to the sitemap.

$group = craft()->categories->getGroupByHandle('news');
craft()->sitemap->addCategoryGroup($group);

But I'm not sure where to start. Where does the hook code go? As I'm assuming I'd have to create a new file, as it will need to be separate from the sitemap plugin as that will be overwritten if there are any updates.

I would appreciate some advice on this please?


texts:
I'm working on a site that was partially built by another dev and am having some trouble with Sprout Forms.

It's partially working but when I add a new field (sailSeries) to the template (it exists in the sprout forms control panel) I get this error:

Craft\SproutForms_EntryModel and its behaviors do not have a method or closure named "sailSeries".

Expanding on what the original dev has I added the sails series inside this for loop at the bottom.

{% for tab in form.getFieldLayout().getTabs() %}
    {% set fields = tab.getFields() %}

    {% for field in fields %}

      {% set required = field.required %}
      {% set tabId = field.tabId %}

      {% set field = field.getField() %}

      {% if field.handle == 'contactType' %}
       {% set dropdownField = field %}
      {% endif %}

      various more fields

      {% if field.handle == 'sailSeries' %}
        {% set  sailSeries = field %}
      {% endif %}

    {% endfor %}
{% endfor %}

The the code later in the template to have the field display:

    {% set submittedDropdownValue = attribute(submittedEntry, sailSeries.handle) %}

      {{ sailSeries.name }}
        <select id="sailSeries" name="sailSeries">
        {% for option in sailSeries.settings.options %}
            {% set defaultValue = option.default ? option.value : null %}
            {% set selectedDropdownValue = submittedDropdownValue != '' ? submittedDropdownValue : defaultValue %}

            <option value="{{ option.value }}" {% if selectedDropdownValue == option.value %}selected="selected"{% endif %}>{{ option.label }}</option>
        {% endfor %}
        </select>

As soon as I add this in I get errors. Not sure why or how to troubleshoot. Please advise.

Revised code and now I'm getting this error:

  Variable "sailSeries" does not exist.

no clue why this is happening.


texts: How to pull all images in [body] Matrix fields

texts:
I'm working on a basic portfolio site wherein each entry or "project" has a body Matrix field with various blocks for various types of images. I'd like to make an index of all projects showing one slideshow/carousel for each project containing all images within that project.

The problem is that I don't know how to query all images at once = All images, all blocks, in the order they appear in the entry.

Here's my specific code in use. It's almost there but due to the 0 in image[0] it's only pulling in the first image from each instance of each Matrix Block. For example, there are two instances of the block called imageHalf and it pulls the first image from each.

I don't understand how to avoid this integer....

{% for block in entry.body %}

{% switch block.type %}

{% case "imageFull" %}

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

{% case "imageHalf" %}

{% case "imageCouple" %}

{% endswitch %}

{% endfor %}


texts: How can I get a lightswitch to work with order() in craft.entries?

texts:
I'm getting mixed results when using a lightswitch field together with order('RAND()') and I wonder if I'm doing something wrong.

For example, this code gives me the correct results:

craft.entries.section('section').lightSwitchField('1').first()

... but this selects entries from all entries in my channel instead of just the ones with the lightswitch field switched on.

craft.entries.section('section').lightSwitchField('1').order('RAND()').first()


texts: Timezone in Craft different from timezone in plugin

texts:
In general.php I've set 'timezone' => 'Europe/Oslo'.
When saving entries through the CP they are saved with the correct time. Also, date_default_timezone_get() from my plugin returns Europe/Oslo.
However when I save something via the plugin, e.g.
$something = new Something();
...
$something->save();

the dateCreated field saves with the wrong time. In my case; 2 hours earlier than the Europe/Oslo time.
What am I missing here?


texts: Get entries relatedTo multiple categories

texts:
I have searched and tried a few different ways but none have worked so not sure what is wrong.

Example say I have a few categories case studies, featured, articles, videos...

I have tried this way

{% set category = craft.categories.group('resource').relatedTo(
    'and',
    { targetElement: featured },
    { targetElement: case studies }
) %}
{% set entries = craft.entries.relatedTo(category).limit(3).find() %}

I have tried this way

{% set category = craft.categories({
    group: 'resource',
    relatedTo: [
        'and',
        { targetElement: featured },
        { targetElement: case-studies }
    ]
}) %}
{% set entries = craft.entries.relatedTo(category).limit(3).find() %}

I am wanting to find entries that use two categories together example case studies, and featured category.


texts:
Hey guys I am getting this error:
unserialize(): Error at offset 0 of 60695 bytes
when i push a backup of my local db to my staging environment.
I am using craft 3.
Any ideas? Clearing the /storage/runtime/cache didn't work.

More info here:
The value that php is trying to unserialize() and failing to do so looks like json (The value of info config, see picture below).
Looking at an old version of a db dump, that value looks like it was proper serialized data.
At some point, craft started storing it as json?


texts:
is it possible to specify the Redactor config file when creating a Redactor field programmatically?

I was hoping I could do something like the following but have had no success:

$bodyField = $fields>createField([
    'type' => 'craft\\redactor\\Field',
    'groupId' => 1,
    'name' => 'Body',
    'handle' => 'body',
    'settings' => [
       'redactorConfig' => 'Simple.json'
    ]
]);

$fields->saveField($bodyField);


texts: How to return errors from a model back to the template?

texts:
I'm working on validation with Craft. I have a custom plugin that allows public submission. However, I want to make sure I can pass errors back to the template. The key is trying to make my code as "dynamic" as possible. Meaning I do not want to specify the errors one by one.

Here is my sample controller (keep in mind I don't care what the model says is required, trying to keep the code agnostic of the model.)

public function actionSave() {

    // require a post request
    $this->requirePostRequest();

    // assign specific fields we are listening for
    $post = craft()->request->getPost('fields');

    // create a new Request model
    $model = MyModel::populateModel($post);

    // validate the model attributes
    if ($model->validate()) {
        // save the record

        // redirect to posted url
    }

    $errors = $model->getAllErrors();

    craft()->urlManager->setRouteVariables(array(
        'errors'    => $errors
    ));

}

Using $model->getAllErrors() returns an array as listed below:

array
(
    0 => 'Name cannot be blank.'
    1 => 'Details cannot be blank.'
    2 => 'Email is not a valid email address.'
)

How would I return that array to specific fields in my template like so:

{% if errors.email is defined ? errors.email | length %}
    <div data-alert class="alert">
        {{ errors.email }}
    </div>
{% endif %}


texts: Craft 3: .find() deprecated but .all() fails?

texts:
.find has been deprecated and we are told to use .all() instead. This seems to work for cases that don't have Eager Loading going on, but fails when eager loading is tried.

My working Craft 2 code might be:

{% set mixedContent = entry.mixedContent.find({
    with: [
        'singleImage:image',
        'imageGallery:images',
        'download:file',
        'relatedItems:relatedItems'
    ]
}) %}

Simply transposing ".find" with ".all" results in the following error:

Error: Call to a member function getQueryBuilder() on array

Switching the syntax I tried:

{% set mixedContent = entry.mixedContent({
    with: [
        'singleImage:image',
        'imageGallery:images',
        'download:file',
        'relatedItems:relatedItems'
    ]
}).all() %}

But got this error:

Calling unknown method: craft\elements\Entry::mixedContent()

What am I doing wrong?


texts:
Is it possible to group by a field within a matrix field.
I have a channel of players which holds their details.
I have a structure for teams which includes a matrix field for a Player.

The Player matrix has 2 fields:

1 - Position (Drop down with: Goalkeeper, Defender, Midfielder)

2 - Entries field linked to Players Channel.

When accessing the matrix is it possible to Group the blocks by the Position field?


texts: Resource for setting up Craft CMS Fields

texts:
It's a good 7 months after the last time this question was asked. I've been developing sites for a long time, expert with Wordpress, some Drupal, Joomla when forced. I can understand a good part of Craft but there really isn't the basic tutorial you'd generally see with other software that gives you an idea how to construct a site. The Happy Lager demo is more of a very quick showcase of how neat CraftCMS can be but it doesn't really go into just the very basics, like setting up fields properly.

I have seen the sparse resources. The paid video, which includes how to install the software, is not an option. Is there still nothing that does a reasonable job of just running through the process and approach to setting up a basic site using the system? In addition, are there any resource repositories, e.g. plugins, etc. so you don't need to reinvent everything? Thank you.


texts: (How) can I fill a visitor's cart by using a link?

texts: When using Commerce 2, is there a way to fill a client's cart with the contents of an (inactive) cart, by using a link? Use case: abandoned cart email.


texts:
I'm trying to load an entry based on the following url:

/artists/nameOfArtist/nameOfCategory/myEntry/thumb

This URL follows the structure of my entries: Artist > Category > Entry

So, I'm thinking that something like this should work:

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

- This gets me the variable from 'myEntry' segment.

{% set artistParent = craft.request.getSegment(-4) %}

- This gets me the variable from 'nameOfArtist' segment.

Then, I want to find the 'project' entry that lives under 'nameOfArtist'.

{% set entry = craft.entries.slug(project).descendantOf(artistParent).first %}

but this is not working. What am I missing? Or is there a better way of doing this?


texts: How can I set up a filter URL like example.com/category/foo/type/bar/country/usa

texts:
Given a category based set of entries/products, and a filter system based on tags, how would I accept (one of) the following urls and let one template process them all (not interested in the processing, just want to know how to set up the route):

example.com/category/foo -> category page, containing products
example.com/category/foo/type/bar -> category page, filtered by relation to tag (group = 'type') with value 'bar'
example.com/category/foo/type/bar/country/usa -> category page, filtered by multiple relations (filters)
example.com/category/foo/country/usa/type/bar -> category page, filtered by same relations as above

This would be more SEO-friendly than example.com/category/foo?type=bar&country=usa

Anyone done this before?


texts: Password-Protect Sections - Newbie Template Code

texts:
I was wondering if someone could take a minute for a newbie to show the template code for a section index page that needs to be private - accessible only to "clients" (pre-registered as users in a private group - I am assuming).

I am confused about the permissions in the users section of the CP as they only show permissions to edit/view assets etc.... not templates.

Someone asked a similar question and the response was "yes it is easy - go look at the User Model" - however I am just starting to figure all this out so need a little help!!

Thank you


texts: Override permissions for Craft Commerce saveProduct controller

texts:
I'm creating products using a frontend form which submits to commerce/products/saveProduct but it only works when I'm logged-in. They're really complicated products which need to be created on-the-fly.

If it were my own plugin controller I was using, then I could just add protected $allowAnonymous = true; but as it isn't, how would I go about this?


texts: How to set different file size upload limits for different Asset Sources

texts:
How can I set file size upload limits on a per-Asset Source basis?

I can only see how to set a global maxUploadFileSize in the general config.

I'm sure I must be missing something obvious though, as this is something that was even possible in EE1! :-) It's a common use case to have a lower limit on some upload destinations to keep clients from uploading massive files (e.g. images), and to allow a higher limit on certain upload destinations for general file downloads.

Otherwise, we will have to use a 10mb limit for everything globally (as an example), and the clients can then upload images up to that size (which can happen with high resolution images). This will waste storage space and potentially run into PHP memory issues when resizing high resolution images for the front-end. :-/


texts:
Hi I have like 2000 users in my system. I would like to get a count of the active ones, so I did it like this:

{{craft.users.group('member').count()}}

but this returns the count with the limit of 100, so when I remove the limit

{{craft.users.group('member').limit(null).count()}}

I got this error

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /Users/alex/git/website/craft/app/models/BaseModel.php on line 280


texts: Sorting an array of entries according to a fixed list/array of items

texts:
I want to sort an array of entries in a specific order. Every entry has a 'shoptype' and I want to show all entries for type A, than type B, than type C.

A partial solution would be to iterate over them (if shoptype == A){ then show all A entries} but than I can't write a conditonal around it to hide the title when there are no shops of type A.

So now I group them using the group twig filter and hide if the group has no items. But I can't sort them the way I like (it's not alphabetical, it's a fixed order that I want).

Idealy I would need something like this in supersort:

'SortAs', ['shoptype A', 'shoptype B', 'shoptype C']

So an array of strings that my shopType field can contain which my array is grouped by.


texts: Multi-user blog "repost entry" functionality

texts:
In our Craft Pro site we've enabled public registrations and allow anyone to create an account and make entries in a "blog" channel.  These entries are then filtered via URL segments - so /blog/ will show a listing of entries by each user.  A user can create different entry types (video/audio/text/etc) which are handled by different templates.

I'm trying to add the ability for a user to "reblog" or "repost" another user's entry - I'm not sure of the best way to do that though.  The ideas I've had are:

Create a new entry type (reblog), with a field that stores a reference to the original entry ID and allows the user to add a comment
Use a custom plugin to create an entry as above
Clone the original entry data into a new entry and allow the user to edit it
Create a new channel for reblogs which the user doesn't have permission to post to via the CP, and try to hack around that using a plugin and frontend forms

My issue is that, for usability reasons, I'd very much prefer to hide the original entry ID reference field (if this is handled through the CP) but I don't know if that's possible?  We're relying entirely on the CP for creating entries at the moment, so it'd be a bit clunky if we moved the handling of reposts to a separate section of the site.

Also if I simply reference the original entry ID in a field, while it would be cleaner than cloning the original entry's content (assets/etc) and creating a new post for the current user, I'll most likely still have to create a new entry type (reblog) to house the new post, which would then appear in the "Entry Type" dropdown when accessing the create entry page, which would be pretty confusing to the end user, unless I made the original entry ID some kind of custom FieldType with a live-search sort of feature?

I'm beginning to think that perhaps the best way is to handle this through a plugin / frontend form, but that feels super hacky.

Any suggestions on how best to approach this issue?  I'm totally open to any and all ideas!


texts: How to override default root URL of plugin?

texts:
how can I override default root URL behavior via routes? I did following but not working:

'pluginname/' => array('action' => 'pluginName/Controller/actionName');

my template file name is index


texts: Ajax User registration sometimes forbidden 403 error

texts:
I am experiencing a very weird issue. I have a simple user registration form:

<form method="post" action="" accept-charset="UTF-8" id="addTeacherForm">
    {{ csrfInput() }}

    <input type="hidden" name="action" value="users/save-user" />
    <input type="hidden" name="fields[schoolId][]" value="{{ currentUser.id }}" />
    <input type="hidden" name="groups[]" value="3" />

        Username *
        <input id="username" type="text" class="form-control" name="username" required />

         E-mailadres *
        <input id="email" type="text" class="form-control" name="email" required />

        Password *
        <input id="password" type="password" class="form-control" name="password" required />

        <button type="submit" class="btn btn-primary btn-submit float-right">
            Docent toevoegen
        </button>

</form>

I have an event listener for the form submit and I submit the form using ajax. This code works perfectly most of the time, but sometimes (like 20% of the time) I get a 403 forbidden error in the console. When I comment out the hidden groups[] input field I don't experience this issue at all.

It is also worth noting that even though I get this error the user is created but doesn't get added to the group.

I'm starting to think this is a craft 3 issue.

Can I somehow solve this?

Thanks!


texts: Unknown error occurred after install on MAMP

texts:
Successfully installed Craft on MAMP but whenever I load the dashboard, I get the error message "Unknown error occurred". The message clears after a few seconds. The CMS appears to be functioning correctly except when I create a Section, it only allows me to select Single as a type.

Can anyone shed light on this error?


texts: Getting line items + shipping and their tax rates in a plugin

texts:
I'm working with an external system that requires me to send line items + their tax rate, and the shipping as it's own line item + any tax applied to the shipping.

The format expected looks something like this:

"items": [
    {
        "reference": "11",
        "name": "The Fleece Awakens",
        "quantity": 13,
        "unit_price": 5250,
        "tax_rate": 2500
    },
    {
        "reference": "9",
        "name": "Romper for a Red Eye",
        "quantity": 3,
        "unit_price": 4000,
        "tax_rate": 2500
    },
    {
        "reference": "2",
        "name": "Fedex",
        "quantity": 1,
        "unit_price": 180,
        "tax_rate": 1500
    }
]

The price and tax rate is multiplied by 100.

This gets even more complex depending on how the tax and shipping rules are setup.

I'm trying to cover everything, like:

When a shipping method has a base rate + perItemRate
When tax is applied either to item price or item shipping cost, or item price + shipping cost
When tax is included

How would I consistently get it in the format like this, while accounting for any adjusters (tax, shipping, sale/discounts)?

I noticed adjusters has optionsJson->lineItemsAffected, which might be interesting.

However, I don't know enough about the complex tax/shipping system or how adjusters work in general to foresee all the different combinations of adjusters.


texts: How do I programmatically add assets to an assets fieldtype on a Matrix

texts:
I have a json file with a bunch of id's & associated images.

The id's relate to existing entries in my Craft installation.

I have a Matrix field called Content with a block type called allImages - the allImages block type has a single field called images defined as an Asset field type.

What I would like to do is import the json file & update the existing entries with the images as defined in the json.

I cannot for the life of me figure out how to add images to the Matrix field in code. There are plenty of samples around submitting post variables from a custom form to the saveEntry action.

Any tips would be greatly appreciated


texts: How can I get the dimensions of a video asset?

texts: The video itself hasn't any dimensions (width and height) within its object. But Craft saves a thumbnail, right? How would I get to the thumbnail to get its width and height? Or is there something more simple?


texts: Using multiple 'search' parameter values to filter entries

texts:
I'm trying to filter entries down based on keywords and also if they have selected a letter that matches the first letter of an entry title on Craft 3.

So far I have this:

{% set keywordParam = craft.request.param('keyword') %}
{% set characterParam = craft.request.param('filterByCharacter') %}

{% set entriesParams = {
   section: 'people',
   level: 1
} %}

{% set searchArray = ['OR'] %}

{% if characterParam|length %}
   {% set searchArray = searchArray|merge(['title:' ~ characterParam ~ '*']) %}
{% endif %}

{% if keywordParam|length %}
   {% set searchArray = searchArray|merge(['title:' ~ keywordParam]) %}
{% endif %}

{% if searchArray|length %}
   {% set entriesParams = entriesParams|merge({ search: searchArray }) %}
{% endif %}

{% set peopleEntries = craft.entries(entriesParams) %}

At the moment this is producing the error:

  Undefined index: query

I've narrowed it down to this line(s):

{% if searchArray|length %}
   {% set entriesParams = entriesParams|merge({ search: searchArray }) %}
{% endif %}

But I can't figure out what is wrong with this, and what could be going wrong!

An example URL is:

  http://localhost:3000/our-people?keyword=sach&filterByCharacter=M


texts: How to fetch specific users OR admins with the ElementCriteriaModel?

texts:
I'm getting all Users from specific UserGroups like this:

$criteria = craft()->elements->getCriteria(ElementType::User);
$criteria->groupId = array(1, 3);
$users = $criteria->find();

But how can I additionally fetch all admin Users?

I tried to add the admin attribute, but this hasn't changed anything:

$criteria->admin = array(false, true);

I assume that's because the ElementCriteriaModel has to match all attributes, but there isn't an admin which has a UserGroup with the ID 1 or 3. But how can I tell the criteria to perform a "OR" fetch?

P.S. I know I could merge two fetched criterias but I want to use a "clean" solution.


texts: Getting Wordpress 404 when accessing /craft/admin

texts: My current site is with Wordpress in the folder /blog. My new Craft install is in a sibling folder /craft. When i try to load brianfeeney.us/craft/admin, i get the wordpress 404. Must be an .htaccess issue, right? Can't figure out or find the solution anywhere.


texts: Way to getNext() within the same category

texts:
I'm trying to get the next and previous entries in a structure but I only want the next or previous ones within the same category?

Is it possible to do something like this?

{% set next = entry.getNext().relatedTo(category).first() %}


texts:
I'm working on a custom payment gateway, and the concept of tax adjustments are giving me some headache.

How is this adjustment system, especially regarding tax, supposed to be used? Would it be normal, or at least make sense, for some stores to use both included and excluded tax on certain items?

Lets use this example:

The Last Knee-High    $60.00
Exclude               $3.00 (5%)
Included              $1.75 (3% inc)
Total USD:            $63.00

The payment provider I'm integrating with require the tax amount and tax rate to be sent with the order to the API.

The tax amount is marked as VAT in the overview, would it then be correct to send:

$3.00 5% VAT ?
$1.75 3% VAT ?
$4.75 X% VAT ?

Or is it just not likely that any company would need both included and excluded taxing in the store? For European stores I looks like its custom to display prices inc tax/vat, while US it looks more normal to include the tax/vat in the cart, not while browsing. So I can't just say that VAT = excluded tax or included tax.

Hopefully I've explained my question well enough for someone to shed some light.


texts: upgrade issue Yii Framework from version 2.0.15.1 to 2.0.16.1

texts:
I tried installing a site I developed on my work mac (high sierra), pushed to its repo, pulled it down at home on my mac (mojave)and on running composer update get this displayed in my terminal:

Seems you have upgraded Yii Framework from version 2.0.15.1 to 2.0.16.1.

and in the browser get this

PHP Warning – yii\base\ErrorException
Declaration of craft\web\twig\Environment::compileSource(Twig_Source $source) should be compatible with Twig\Environment::compileSource(Twig\Source $source)

I tried deleting the vendor folder and running composer install but get the same, however when I delete all database tables and allow craft to reinstall it's fine (albeit no content!!!) I have no idea how to resolve this, any tips appreciated!


texts: When using "Title Format", quotes in fields are entitized when saving to title field

texts:
Example: section called people

Title format: {firstName} {lastName}

When I save an entry with the name _Michael "That Guy" D'Esopo, it saves and reads in the entries list screen as Michael &quot;That Guy&quot; D&#039;Esopo.


texts:
I have created an event to transform the entry data before rendering the page so that it's ready to render components in the template.

Event::on(View::class, View::EVENT_BEGIN_PAGE, [$this, 'transformSingleEntry']);

Here's an example of what the function looks like. I've cut out most of the code, but essentially at the end of the function I have a $transformed_entry variable that I want to add to the twig context.

public function transformSingleEntry() {
  $entry = Craft::$app->urlManager->getMatchedElement();
  // ... do stuff
  $transformed_entry = [
    'title' => 'test',
    'url' => 'test',
  ];
  // Add $transformed_entry to the page context
}

I cannot find anything in the Craft documentation to help here. Any ideas?


texts: Loop through Matrix Block fields within a Switch Case and retain HTML structure

texts:
I'm struggling to get my head around the syntax to output information in a correct HTML structure.  At the moment I have this:

{% for block in entry.menuBuilder %}
{% switch block.type %}
{% case 'menuItem' %}

{{ block.dishName }}

{{ block.dishDescription }}

{{ block.dishPrice }}

{% case 'subHeading' %}

{{ block.heading }}

{% endswitch %}
{% endfor %}

This code is working in that it's displaying the information for me but unfortunately it opens and closes the UL for every item so I end up with:

Name

Description

Price

Name

Description

Price

Name

Description

Price

 ... etc

What I need to achieve the UL to open, loop through all instances of the Block using just the LI and then close:

Name

Description

Price

Name

Description

Price

Name

Description

Price

I've tried adding a for-loop around the LI but I just get errors or nothing at all.

Hopefully this will be simple to somebody!? :D

Many thanks


texts: Commerce Manage Settings for User Groups

texts:
When setting User Group permissions for users for Craft Commerce, there are explicit options for:

Manage Orders
Manage Products
Manage Promotions

But nothing is listed for Manage Settings. Is this not controllable for User Groups? Seems like it definitely should be... some users would be allowed to manage product info but not Settings, while some users would need access to Settings for updating Tax or Shipping options.