texts: How to flatten assets listing view (remove subfolders constraint)

texts:
Well I like in the entries listing the possibility to toggle a structure entry type between Structured and List view.

I d like to do same for my assets because I got a structured assets tree with plenty of subfolders and I want to see also the assets as a listing...

Is it possible to do that?
(ElementActions are only used for triggering action on selected elements)

In resume :
1/ How to add a button in the main menu bar, beside the search field on the right for example...
2/ How to hook into assets listing ? (when button clicked)


texts: When Using Nitro Add and it gets to the choose database engine question, the choices arent there and typing in doesn't work

texts:
I'm totally new at craft cms and nitro and I'm having trouble adding a new site. When I get to the part where it asks you which database engine to use there's no options there to choose from and typing in the database info doesn't work either.
So I'm basically stuck at this point. I'm on mac os catalina. I think I installed everything correctly (nitro and craft itself) but I'm honestly not 100% sure so if there's a way of checking that could someone tell me? I'm about to give up on this so if anyone could help at all that would be amazing. Pretty new to web development so please be kind : ) Thanks!


texts: Error when using if statement in template

texts:
I have a page that shows all photos in a category, which is set by the last url segment  and then the results re paginated. What i'm trying to do is say that if the last segment is 'all' then show all photos from all categories. So i'm trying the following code, but getting an error and i cannot see why!

Template Code:

{% set categoryName = craft.request.lastSegment %}
{% if categoryName == 'all' %}
    {% paginate craft.entries.section('photo').limit(6) as entries %}
{% else %}
{% set category = craft.categories.slug(categoryName) %}
    {% paginate craft.entries.section('photo').relatedTo(category).limit(6) as entries %}
{% endif %}

Craft error:

Internal Server Error

Unexpected tag name "else" (expecting closing tag for the "paginate" tag defined near line 12)

Line 12 is {% else %}, btw.

I have the endPaginate code further down the page after the pagination html, like so:

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

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

{% endpaginate %}


texts:
On my MAMP development server, SVG files display like this in the Assets section of the Control Panel:

On my live server, they get a black background:

When I use an SVG file inside an img tag with an transform like this:

<img src="{{ iconSVG.getUrl(iconSize) }}">

I got this working fine on the MAMP server, but on the live server the file gets transformed into a PNG with a black background.

I don't necessarily have to use a transform on the SVGs, so could leave that out, but the black thumbs in the Assets isn't that pretty.

I checked both servers, and a possibly relevant difference I can see is that the MAMP does not have imagick, whereas the live server does.

How can I fix the black thumbnail issue? Would I need to disable imagick on the live server somehow?


texts: Search against a checkboxes field's options

texts:
I have a relatively simple structure for products that I am building an advanced search for. I access the products using craft.entries.section('products'), but these products have fields with options for those fields within them.

So my question is, how do I access these? This is my attempt so far.

        {% set parameters=
            {
                section: 'products',
                limit: '1'
            }
        %}

        {% set query = craft.request.getParam('entry') %}

        {% if query %}
            {% set entries = craft.entries(parameters).relatedTo(query).order('score') %}
        {% else %}
            {% set entries = craft.entries(parameters) %}
        {% endif %}

I know this is incorrect, because I need to look at an object within an object within products and check a field belonging it. For instance, if the product was a phone, it would have something like "mobilityOptions" and under that would be "Cordless", "Desk", and "Wall".

My search form has got those mobility options through a for option in products loop of the section, followed by a for block in option.mobilityOptions.options that then makes checkboxes for each option, but to use it with the ".relatedTo" functionality I don't think it would work.


texts: AJAX page transitions with history.pushState

texts:
I'm a new craft user (previous EE user). trying to follow Zack Spear's directions (https://designbycosmic.com/journal/craft-cms-ajax-page-transitions-with-history-pushstate) for how to setup Ajax page transitions.

The final javascript example (the last code block) the new "loadPage" functions doesn't appears to have any line that actually loads the new content into $main. So when I implement the scripts as per those instructions, the fade in and out work, but the content that fades in is the same content from the previous page rather than the new content that should have replaced it.

Sorry if I'm being thick here, as I don't have a lot of Ajax experience. What do I need to add to the loadPage function to get this to work?


texts: Image transforms return cpresources URL in Craft Pro 2.5.2754

texts:
Despite having tried the tips from Image transforms returning cpresources url, I am still having issues with image-transforms.

I am running Craft Pro 2.5.2754

asset-source details as follows:

Handle: paragraphPictures
Type: Local folder
Path: ./uploads/images/paragraphPictures/
URL: /uploads/images/paragraphPictures/

image-transform details as follows:

Handle: frontpageNewsPicture
Mode: Crop
Crop Position: Center Center
Width: 492
Height: 348
Quality: Auto
Format: png

'generateTransformsBeforePageLoad' => true is set in craft/config/general.php

folder-permissions as follows:

public/images including all sub-folders and files are owned by apache:apache (the user that runs the apache service) with 777 rights

template-example

{% if entries|length %}

        {% for entry in entries %}
            {% set entryUrl = entry.url %}
            {% set picture = entry.pictures.first() %}

                        {% if picture %}
                        {% set picData = craft.norsok.getPicData(picture) %}
                        {% set maxWidth = picture.getWidth('frontpageNewsPicture') %}

                    {% endif %}

                        {{ entry.title }}

                        {{ entry.ingress }}

        {% endfor %}

{% endif %}

this is what the page-source looks like

and this is what my console tells me

GET http://norsok.tibe.no/cpresources/transforms/2?x=bptVEjjgx 500 (Internal Server Error)
GET http://norsok.tibe.no/cpresources/transforms/1?x=bptVEjjgx 500 (Internal Server Error)

the actual images are located here:

http://norsok.tibe.no/uploads/images/paragraphPictures/img-9889-kraftfor-1-foto-anita-land.jpg
http://norsok.tibe.no/uploads/images/paragraphPictures/StengelnematodeG.Taksdal.jpg

At this point I am completely baffled and pray to the Stack Exchange-gods for assistance :)


texts: Assets Control Panel searches only current folder, not sub folders?

texts: When searching for an Asset in the Assets Control Panel, does it search everywhere? Does it search in subfolders? e.g., If I search for the title "image_1", does my search need to be done on the folder "image_1" is in for the search to return anything?


texts: Image transforms getting applied even when image is smaller than the transform's width

texts:
I have a detail transform setup and here's my template code:

{% if block.type == 'image' %}
    {% for asset in block.image %}
        <img src="{{ asset.url('detail') }}" alt="{{ asset.title }}" class="{% if block.position in ['left'] %}pull-left{% endif %}">
    {% endfor %}
{% endif %}

But on the front end it's taking a smaller image and stretching it and it's become distorted. If I remove 'detail' from the url() parameter it's fine.

Here's what my Detail Transform looks like:

Any thoughts?

It also looks like all transforms are doing the same thing as well. So it's not just related to the detail transform.


texts: Can I use Rich Text field on frontend safely?

texts: I have done a commenting system based on entries. It works fine but I would like to allow to registered users to do basic formatting on their comments. What type of checking is done on the Rich Text Field? Is it protected by SQL Injection or XSS?


texts: Translating a section's title field on save

texts:
For a Single section's entry type that has the title field hidden, I'd like to translate the generated title, as per the entry's locale.

I've currently got the following in the entry type's "Title Format" field:

{section.name|t(language=locale)}

However, this doesn't translate the section.name as per the entry's locale, it appears to use the current CP locale instead (i.e., if the CP is currently rendered in English, it'll use the English translation for entries in all locales). However, if I use something like

{section.name|t(language=locale)} ({locale})

the latter locale value (inside the parenthesis) does reflect the entry's locale (it'll print something like Section Name (no) for the Norwegian version. So that's a bit odd.

Also, I've tested with a hard coded string for the t filter's language parameter (i.e. {section.name|t(language="no")}), which works as expected.

Not sure what's going on – though I'm guessing that the locale variable passed to the translation filter is somehow null (in which case Craft will use the current locale). How can I translate an entry type's Title Format based on the entry's locale?


texts: Using Label instead of Value from Dropdown

texts:
I currently have this dropdown on a front-end form, the problem I'm having is that it's saving the value where I really want to use the label in my templates such as United Kingdom instead of unitedKingdom. Is this something I should be changing in my Dashboard/Front-end/Dropdown?

          Location
          <select class="form-control" id="listingType" name="fields[location][]" required>
            {% set locationField = craft.fields.getFieldbyHandle('location') %}
            {% for option in locationField.settings.options %}
            <option value="{{ option.value }}">
              {{ option.label }}
            </option>
            {% endfor %}
          </select>

Front End

{{ entry.author.location|ucwords }}


texts: Check if current entry is in loop and add class

texts:
I'm super new to both Craft and Twig so, apologies in advance!!

I'm looking to determine if the current entry I'm on is in a loop being called on that page.

I have loop that goes through the entries of a category and displays them. If I'm currently viewing an entry that also appears in the loop, I would like to add an "active" class to the matching entry in the loop.

I have been trying to possibly match the URL segment with an answer like the one found here but I need to the segment name to by dynamic.

Currently I have:

{% for entry in craft.entries.section('category_name').limit(4) %}

{{ entry.title }}

{% endfor %}

And would like it to be like:

 {% for entry in craft.entries.section('category_name').limit(4) %}
    IF ENTRY IN LOOP MATCHES CURRENT ENTRY PAGE I'M ON.. ADD CLASS

{{ entry.title }}

    ELSE

{{ entry.title }}

    END IF
{% endfor %}


texts:
I have a category group called country, with each category being the name of a country.  I used the full name of the country.
I realize I might want to use each country's 2-digit code.  For example, AU for Australia.

How might I implement the abbreviations to associate with the category?

Put another way, how can I use the 2-digit code as an alias for the full country name?


texts: How do I convert a date stored in UTC to the user's current locale in PHP?

texts:
I have a date stored in the database in UTC.

2016-01-13 09:01:16

I can query the database and output this date just fine. But it outputs in the date in the wrong timezone.

How do I adjust a date from the database into the current user's locale?

I believe this involves using craft()->timezone at some point, with some method, but I have not had any luck. I'm retrieving the date with the query builder:

$rows = craft()->db->createCommand()
         ->select('dateCreated')
         ->from('mytable')
         ->queryAll();

Bonus points: sometimes I have multiple dates, so I need to modify all dates I get back into the right timezone.

More bonus points: at what point in the process is the best point to modify the date into the right timezone? In MySQL query? In PHP? In Twig?


texts: Multiple Tag Groups/Sets for separate channels

texts:
I have two separate channel types, let's say "News" and "Reviews" and each of those can have tags.

Is it possible to have separate tags for each of those? So News has it's own set of tags, that can't be selected when creating a new Review.

I'm coming from a Wordpress background, and in Wordpress these custom post types would have their own taxonomies. (Or News would use tags, and I would create a new one for Reviews).


texts: Registering a class library within a plugin

texts:
I am trying to instantiate a class from a third-party library from within a controller. Probably not the best place to do this but just testing.

require(craft()->path->getPluginsPath().'myplugin/vendor/ifpk/src/fsdk.php');

$app = new fSDK;

I get the following error

Fatal error: Class 'Craft\fSDK' not found in /var/www/.../controllers/MyPluginController.php on line 57

Not sure where to go with this next.


texts:
Good Afternoon.

Im trying to recover admin login information for a website I have recently taken on, however there is no craft_users table within the database.  Any help to locate the user info would be greatly appreciated.


texts:
I have a plugin called EducatorEntriesPlugin, and in the controller of the plugin, I have a method called actionExportEducator. In this method, I am logging an error using the code below, but when the action is called, the error is not logged into the log file, why might this be?

Craft::log("There was an error")

I also did EducatorEntriesPlugin::log, that doesn't do anything either.


texts: Find the nth top-level category in a nav tag

texts:
I want to output some code after the 10th top level category in a category listing. For example...

1.

1.1.
1.2.

2.

2.1.

3.
...
10.
Zoiks!

The problem is, I can't use Twig's loop.index in a conditional because it counts each of the children too (like a flat list). How can I test for the 10th top-level category?

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

    {{ category.title }}
    {% ifchildren %}

        {% children %}

    {% endifchildren %}

  {% if category.level == 1 and loop.index == 10 %}

Zoiks! That‘s a lot of categories!

  {% endif %}
{% endnav %}


texts:
I have an adjuster I am trying to get to work, but the order has to come from a specific site in order for the adjuster to be applied. The siteId is 2, but when I try to get the siteId from the Order Model I always get one.

public function adjust(Order $order): array
{
    die($order->siteId); // returns 1 no matter what site I created the order on
    if($order->siteId == 2){
        // code here
    }
}

Do I need to be passing the Site Id when creating the order? Or am I possibly messing something up somewhere?


texts: Does anyone know if it's possible to validate the size of an attachment for Sprout Forms file upload? I'd like to limit attachments to a maximum file size.


texts: HTML Cache Creates Huge Number of DB Queries

texts:
In trying to reduce the load time and DB query overhead on a Craft 3 site, I noticed a very large number of duplicate queries created when I have the HTML Cache plug in turned on. 300, on one page, for example. The total Query count balloons from 570 (itself very troubling) to 1200!
One duplicated query is:
SELECT *
FROM `htmlcache_caches`
WHERE (`uri`='') AND (`siteId`=1)

Turning off caching in the plugin removes the duplication. Has anyone come across this issue?
I'm also noticing a large duplication of the following query (nearly 50 times on one page, for example):
SELECT `structureId`
FROM `sections`
WHERE (`id`='3') AND (`type`='structure')
LIMIT 1

Any hints?


texts: How to control the format of an asset's Title

texts:
Is there any way to control the formatting of an asset's title that is created from the filename on upload?

At the moment, if you uploaded a file called Craft-CMS.pdf it would create the title as Craft Cms - where in most cases I you would expect the uppercase of CMS to remain intact.

I see there is a config setting for filenameWordSeparator, but nothing related to the pattern used to created the title - is there anyway I'm not seeing to configure this?


texts:
In channel A, we have a Neo field with a couple of different block types, in 1 of those types we have an entries field with channel B entries.

On the channel B entry, I'd like to find out if it is related to a channel A entry through that Neo field.

Going by https://craftcms.com/docs/relations and how it works for a Matrix field I have this:

      {% set partOfChannelA = craft.entries.section('channelA').relatedTo({
        targetElement: entryChannelB,
        field: 'neoField.blockType.fieldHandle'
    }) %}

But that doesn't work :)
Am I missing something or does this simply not work with a Neo field?
Thanks for helping out!


texts:
I've seen some Craft CPs that display the sidebar menu horizontally in the top of the browser as a header.  Does anyone know how this is done? Is there a plugin? I think this would be useful for clients using a smaller monitor, particularly when using live preview.

Thanks!


texts: Feed Me and Assets Field - Mapping Trouble

texts:
I'm trying to import a JSON file to map a bunch of asset paths to their appropriate related entries.  While I've followed the instructions in the docs, I'm still having trouble connecting the file path in JSON with its related Assets field.
I have the following JSON structure, with "Record Id" representing the path to the file on the server, and "Parent ID" representing a field in my section to which I can identify the correct entry to map the asset.
[
  {
    "Record Id": "http://reminc.info/uploads/Call Reports/9s0353ca7831970c344b6afd2949eade4bf42_Agrati Reilingen, D 20120-02-11_ss.doc",
    "Parent ID": "zcrm_4320009000001781082"
  }
]

I've verified that the file path maps to a file on my server, and that the "Parent ID" value matches the field within the target entry.
All this said, Feed Me is failing to import the URL to create the link to the asset.
What am I missing?
Thanks!


texts: How can I reduce the number of queries when including a related item within a for loop

texts:
I've created an alphabetical index of entries in my template. The code I'm using is in the gist below:

https://gist.github.com/jamiepittock/2635516e95317e5c6ed6

It results in a layout like the one in the following image (screenshot only shows "B":

The problem is it takes 704 database queries. If I don't include the category name ("Business People" under the Jeff Bezos entry on the screenshot) that drops to 22.

Is there anything other than caching I can do here?


texts: Fields Missing. Gone from Database as Well as Control Panel

texts:
Recently the organization I work for started a podcast and wanted to add a section on the site where people could find some information about the podcast, some links to subscribe, and more details about each individual episode.

So I created some fields, a field group, and a couple of sections and created migration files using the Migration Manager plugin. Everything was fine for over a month, I am not sure if it was the deployment of some other work or a bug but one day I was alerted to the fact that the podcast episodes on the site were missing information. I went into the control panel to add the data back and was surprised to see those fields were no longer available on the entry. I check the field layout and they were missing there too as well as in the list of fields. So I went back to my local dev environment and created new migration files using Migration Manager. After another deployment that restored the fields. I added the data back and went on with my life. It happened again shortly after and I repeated the process of creating new migration files for the missing fields.

That was a couple weeks back. It happened this morning and I decided that not only was recreating migration files not a sustainable solution but it may be causing more issues.

I logged into the database using Sequel Pro and can see that the fields and the field group no longer exist there, but it looks like the data that was previously entered still exists in the content table as it looks like a new column is created for each field in the system. Additionally, I can see duplicate fields that were almost definitely the result of my multiple migration files. Those fields have their names appended with what looks like some encoded information (ex: field_episodeTeaser_Z9E6Zcu6PN).

Has anyone run into an issue like this? At this point, I am nervous to implement any solution as I have no idea what has caused/is causing this issue. Any help would be greatly appreciated.


texts: Craft CMS 3 data structure advice for vehicle make, model, trim, year tagging

texts:
Hi i really would like some advise on best practices on setting up some data for my Craft APP.

Most of my documents will be linked to vehicle make/model/trim/year. EG Audi A5 Sport 2009-2016 and/Or Audi A5 Sportback 2017+ .

What would be the best way to do this? Would it be to create a new field type or use something like a table?

My First Idea was to do the following:

A Structure

Level 1 : Vehicle Make

Level 2 : Vehicle Model

Level 3 : Vehicle Trim

Then create a field (table) where i select either the trim or model, then select a date range.

But what i want to do is in the front end select documents by everything under Make and/or Model and/or Trim and/or Year

But i am not sure this is the best solution.

Can anyone recommend?


texts: How can I access variables only declared in a template?

texts:
I have a template inside a folder located in /templates that is not related to any entry or section:

/folder/test.html

{% extends '_layout' %}

{% set title            = 'myTitle' %}
{% set description      = 'myDescription' %}
{% set variable3        = 'hello' %}

{% block content %}

{{ title }}

{{ description }}

{% endblock %}

If I want to create a link to this page, I can use the url() function like this:

test

How can I access the variables declared on this page?


texts:
From the Creating an Archive Page for Entries article in the Craft docs. How could I limit it so that it grouped by month but limited things to 6 months?:

{% set allEntries = craft.entries.section('blog').limit(null) %}
{% for date, entries in allEntries | group("postDate|date('F Y')") %}

{{ date }}

        {% for entry in entries %}

{{ entry.getLink() }}

        {% endfor %}

{% endfor %}


texts: Issue Excluding Entries with Multiple Categories in Query

texts:
I've reference this related thread but haven't found a working solution that supports pagination and will exclude entries that have multiple categories.

The code example will not include Category One, but when an entry has Category One and Category Two it will still display because Category Two is included in the cateogries array. Is there a way to still exclude the entry even if it's second category is included?

  {# Get all the categories you want to INCLUDE #}
  {% set categories = craft.categories({
      group: 'categories',
      slug: [
        'not category-one',
      ],
      limit: null,
    }).all() %}

  {# Get entries related to your desired categories #}
  {% set latestNews = craft.entries({
      section: 'news',
      relatedTo: categories,
      with: ([
        ['image', {
          withTransforms: ['medium']
        }]
      ]),
      orderBy: 'postDate desc',
      limit: 4
    }).all() %}


texts:
% set entriesList = craft.entries.section('parks').relatedTo(entry.Line.one()).all %}
    {% if entriesList|length %}

            {% for entry in entriesList %}

{{entry.title}}

            {% endfor %}

    {% endif %}

Every Element has a Table where a Number is set
I want to order it by the Number. How can i do it?

Thanks


texts: Simple way to create a slideshow with Twig and a for loop?

texts:
I have this code, which is basically a loop in a Twig template where I show opinions:

        Opiniones de otros guardianes

        {% for opinion in opiniones %}

                {{ opinion.opinion }}

                {{ opinion.autor }}

                {{ opinion.ciudad }}

        {% endfor %}

I'd like to create a simple slideshow to show these 3 opinions. I've tried with diferent methods but they don't work. Does someone know a simple, easy way to do it? Thanks.


texts:
I have added a form to my front-end to edit the user's first and last name. Editing all the other fields is not a problem but when I try to edit the first or last name it doesn't work.

I think I might need to change name="fields[firstName]" to something else, but I don't know to what I should change it to.

<form method="post" id="loginForm" accept-charset="UTF-8" enctype="multipart/form-data">
    {{ getCsrfInput() }}

{{'Profiel bewerken'|upper}}

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

    {{"voornaam"|title}}
    <input type="text" id="voornaam" name="fields[firstName]"
    {% if currentUser.firstName %}value="{{ currentUser.firstName }}"{% endif %}>

    {{"achternaam"|title}}
    <input type="text" id="achternaam" name="fields[lastName]"
    {% if currentUser.lastName %}value="{{ currentUser.lastName }}"{% endif %}>

    {{"woonplaats"|title}}
    <input type="text" id="woonplaats" name="fields[woonplaats]"
    {% if currentUser.woonplaats %}value="{{ currentUser.woonplaats }}"{% endif %}>

    {{"postcode"|title}}
    <input type="text" id="postcode" name="fields[postcode]"
    {% if currentUser.postcode %}value="{{ currentUser.postcode }}"{% endif %}>

    {{"adres"|title}}
    <input type="text" id="adres" name="fields[adres]"
    {% if currentUser.adres %}value="{{ currentUser.adres }}"{% endif %}>

    {# Check to see if the user has a photo  #}
    Profielfoto

    {% if currentUser.photoUrl %}

        <input type="file" name="userPhoto" value="Change Photo">
    {% else %}
        {# If no photo exists, give the option to upload a new one #}
        <input type="file" name="userPhoto" value="Upload">
    {% endif %}

    {# <input type="file" name="userPhoto" value="{{ (currentUser.photoUrl ? 'Change Photo' : 'Upload') }}"> #}

<button type="submit">Opslaan</button>

</form>


texts: Permission error on session_start() after 3.5 upgrade

texts:
On my dev box, I have php/nginx running as 'jim'. I've followed the suggestions on permissions in the install docs. (744 since php is running as 'jim')
I'm getting this error...
PHP Warning – yii\base\ErrorException

session_start(): open(/var/lib/php/sessions/sess_a693hln410j5992m23otjnc7nf, O_RDWR) failed: Permission denied (13)

and my folder perms look like this...
-rwxrw-r--   1 jim jim    618 Aug 10 14:21 composer.json
-rwxrw-r--   1 jim jim 216281 Aug 24 11:29 composer.lock
drwxrwxr-x   4 jim jim   4096 Aug 18 11:55 config
-rwxrwxr-x   1 jim jim    655 Jun 23 17:36 craft
-rw-rw-r--   1 jim jim    330 Jun 23 17:36 craft.bat
-rw-rw-r--   1 jim jim   1813 Jul 24 15:54 gruntfile.js
-rw-rw-r--   1 jim jim   1037 Jul  7 18:33 gulpfile.js
-rw-rw-r--   1 jim jim    982 Jul  2 17:19 layout.html
drwxrwxr-x   2 jim jim   4096 Aug 17 15:14 logs
drwxrwxr-x   2 jim jim   4096 Jun 23 17:36 modules
drwxrwxr-x 683 jim jim  24576 Jul 11 15:28 node_modules
-rw-rw-r--   1 jim jim    420 Jul 11 15:28 package.json
-rw-rw-r--   1 jim jim 356363 Jul 11 15:28 package-lock.json
drwxrwxr--   7 jim jim   4096 Jul 16 08:38 storage
drwxrwxr-x  12 jim jim   4096 Aug  6 10:07 templates
drwxrwxr--  56 jim jim   4096 Aug 24 11:29 vendor
drwxrwxr-x   5 jim jim   4096 Jul 20 23:36 web

I've also tried opening up the following files/directories with 777, but still get the error:
.env
composer.json
composer.lock
config/license.key
config/project/*
storage/*
vendor/*
web/cpresources/*


texts: Craft 3 multisite - best practice to minimize confusion and database size?

texts:
Usage Scenario
One organization with branches in several cities. Most of the events in one city are only advertised to that one city, but some of the larger events in any given city will be advertised for the other cities. While the different branches are similar, some have many offerings (categories), and some just a few.

What we used to do
In Craft 2, we had one single URL shared by all the cities, one large set of categories which mapped to the drop-down menus, and entries as events that fall into the categories.

What we want to do
Individual URLs for the different cities, focusing on the offerings in that city, but a few from other cities.

Dilemma / Question
Since we don't need multiple versions of the events entries, it seems that we need very little of the multi-site functionality. Just needing to call different templates with different navigation and css, depending on the request URL.
In
Settings > Sections > Events --> Site Settings
is it necessary to

switch on all the light switches, and
check Propagate entries across all enabled sites?

It seems this might triple the size of the database.


texts: I can't get Dukt Videos working in a Matrix field?

texts:
I have the plugin Dukt Videos installed to latest version 1.0.31.  I setup a Matrix block field with these settings:

Field handle: videos
Matrix Block handle: videoBlock
Matrix Video Field: videoURL

For some reason this will not work:

{% for video in entry.videos %}

title: {{ video.title }}

url: {{ video.url }}

embed: {{ video.embed({ width: 300, height: 200 }) }}

{% endfor %}

I get this error: Craft\MatrixBlockModel and its behaviors do not have a method or closure named "embed".

When I try this it also does not work:

{% for blockMedia in entry.videos %}
    {{ blockMedia.videoUrl }}
{% endfor %}

I get this error: Internal Server Error. Object of class Craft\Videos_VideoModel could not be converted to string

What am I doing wrong with this Dukt Videos Plugin?


texts:
I have an Asset Source, called files, with two subfolders:

group1
group2

I also have two User Groups, with the same names.

I want everyone in “group1” to save images into files/group1; and I want everyone in “group2” to save images into files/group2.

I have a Matrix field which contains an Assets field. It is configured to:

Restrict uploads to a single folder => files/{owner.author.groups[0].name}/images
Restrict file types to Image

When a user from group1 logs in and adds an entry, the image asset folder doesn't display all the data from their images folder.

If I upload images in the Assets folder directly to their images folder and go back to create a new entry, the new image doesn't show up in the image list.

Any ideas what is going on?


texts: 404 error when trying to access a module controller action

texts:
I’m creating a module for a site for the first time and I’m having some trouble figuring out how to get the correct action url for my controller. I’m using this template for setting up the module: https://github.com/doublesecretagency/craft-businesslogic
This is the code in my controller (SendEmailsController.php):
<?php
    namespace modules\businesslogic\controllers;

    use Craft;
    use craft\web\Controller;

    class SendEmailsController extends Controller {
        protected $allowAnonymous = true;

        public function actionTestEmails() {
            echo 'TEST FROM CONTROLLER';
        }
    }

I saw this similar question & answer: "Template Not Found" error when trying to access a module controller action which is why I added the /actions/ to the url.
I have tried various iterations for the action url:
http://mywebsite.localhost/actions/businesslogic/send-emails/test-emails
http://mywebsite.localhost/actions/business-logic/send-emails/test-emails
http://mywebsite.localhost/actions/BusinessLogic/send-emails/test-emails
http://mywebsite.localhost/actions/modules/businesslogic/send-emails/test-emails
but these all result in a 404 error. I'm not quite sure where I'm going wrong here, so any advice would be appreciated!


texts: Undefined property when using cacheMethod = db

texts:
What can the issue be here? I have no clue.

Config settings are like this:

'cacheMethod'           => "db",
'cacheDuration'         => 'P2M', /*2 months*/

Undefined property: Craft\WebApp::$db

/var/www/www_cmgg_cmgg_be/craft/app/services/CacheService.php(46)

34         switch (craft()->config->get('cacheMethod'))
35         {
36             case CacheMethod::APC:
37             {
38                 $this->_cacheComponent = new ApcCache();
39                 break;
40             }
41
42             case CacheMethod::Db:
43             {
44                 $this->_cacheComponent = new DbCache();
45                 $this->_cacheComponent->gCProbability = craft()->config->get('gcProbability', ConfigFile::DbCache);
46                 $this->_cacheComponent->cacheTableName = craft()->db->getNormalizedTablePrefix().craft()->config->get('cacheTableName', ConfigFile::DbCache);
47                 $this->_cacheComponent->autoCreateCacheTable = true;
48                 break;
49             }
50
51             case CacheMethod::EAccelerator:
52             {
53                 $this->_cacheComponent = new EAcceleratorCache();
54                 break;
55             }
56
57             case CacheMethod::File:
58             {


texts:
User Access Question...

Can I use Craft to create users that can only use the site?  These users would only be viewers of the content.  They would NOT have access to Craft or any of its features.

Put another way, users login to my site and I have Craft (theoretically) setup to control their access to either the entire site or specific sections only, NOT edit or have access to any Craft features.  I don't even want them to know craft exists. '

Basically, I only want paid clients to have access to the site.


texts: Filtering search with checkboxes multiple param querystring

texts:
I have a series of checkbox like so:

       <fieldset data-role="controlgroup">
        {% for option in craft.fields.getFieldByHandle('area').getFieldType.options %}
            <input type="checkbox" name="area[]" value="{{ option.value }}" class="bg-white h-4 w-4 tickbox template_filters" />
            <label>{{ option.label }}</label>
        {% endfor %}
        </fieldset>

I want to the user to be able to select multiple but only pass through as a single parameter in a query string.
At the moment selecting multiple results in:
http://localhost:8080/directories/case-studies/?area=africa&area=europe&area=asia
Naturally this only filters my results on the last query (asia)

How can I accomplish a search on all three either merging the queries before submission i.e ?area=africa,europe,asiaOR to keep all versions but append the results to merge the query strings?


texts: Image transforms directory not being created

texts:
I've upgraded to El Capitan from Yosemite, created several Image Transforms in the CP (see pic) but they don't seem to be creating the folders in the uploads dir. I've checked folder permissions for the assets dir and all have read and write and double checked the folder paths.

I'm running on Craft Pro ver: 2.6.2796

!(http://imgur.com/a/stX27)

The code I'm using in the template is as follows:

{% set xxxlarge = transform(bgImage, 'bigImageXx') %}
{% set small = transform(bgImage, 'bigImageS') %}
{% set medium = transform(bgImage, 'bigImageM') %}
{% set large = transform(bgImage, 'bigImageL') %}
{% set xlarge = transform(bgImage, 'bigImageX') %}
{% set xxlarge = transform(bgImage, 'bigImage') %}

<picture class="ce-mast-background">
    <!--[if IE 9]><video style="display: none;"><![endif]-->
    <source srcset="{{ xxxlarge }}, {{ xxxlarge }} 2x" media="(min-width: 1281px)">
    <source srcset="{{ xxlarge }}, {{ xxlarge }} 2x" media="(min-width: 800px)">
    <source srcset="{{ medium }}, {{ large }} 2x" media="(min-width: 400px)">
    <source srcset="{{ small }}, {{ medium }} 2x">
    <!--[if IE 9]></video><![endif]-->
    <img srcset="{{ xxxlarge }}" alt="{{ entry.title }}" class="ce-mast-image" />

</picture>


texts: Eager Loading Image Transforms In Plugin

texts:
The craft docs on eager loading show you how to eager load image transforms in twig.

{% set entries = craft.entries({
   with: [
        ['coolImage', { withTransforms: ['transform'] }]
    ]
}) %}

However I can't figure out the syntax for achieving the same functionality within a plugin using the ElementCritereaModel.

I've made various attempts but they've all resulted in HUGE EXPLOSIONS of the php error variety.

$criterea->with = [
    "coolImage" => [
        "withTransforms" => ["transform"]
    ],
    "otherAssetField",
    "someCategoryField"
];

Of course above wouldn't work because you're switching between field slugs being keys/values in the array.

Using a similar syntax to the docs in twig would be:

$criterea->with = [
    "teaserImage",
    ["withTransforms" => ["peopleListing"]],
    "peoplePffice",
    "peopleCategories"
];

But that also results in explosions.

Help!!! (thanks)


texts: How do I pull an image from a child entry of a structure

texts:
I have a structure, holding areas (level 1), and properties (level 2). I use entry types to pick what template will be used.

In my entry type 'area' template I'm listing the children of 'area' ('properties').
The children (entry type 'property', has an image field that I want to pull into my area template.

Here's the code:

{% set properties = entry.getChildren() %}
{% if properties | length %}

Properties

    {% for property in properties %}

{{property.title}}

    {% endfor %}

{% endif %}

This works, except I can't figure out how to pull the imageurl from the asset 'imageBackground' that sits in the entry type 'property' field layout.

Anyone?


texts: Logistics of loose field naming and re-use with Relabel

texts:
Relabel certainly seems quite useful in being able to apply a more generic use to fields. The more I use it the more I see a use case for just creating a generic field with the same name as it's fieldtype which can be re-labeled and re-used in specific instances. Is anyone doing something similar and are there any potential issues to that approach? It seems to make things much more modular and re-usable.

So, for instance you could create an instance of fields such as Plaintext called Plaintext, Richtext called Richtext, etc. Then just relabel them and provide specific instructions in an on-the-fly basis when required. That would help to cut down on the number of fields in use.


texts: How to translate de postdate format for a multilanguage site

texts:
I have a site with 2 languages: Nl and En
Everything translates to Dutch but only the date stays in English...

I use this to get my news items:

{% for entry in craft.entries.section('news').limit(6).find() %}

{{ entry.title}} {{ entry.postDate.format('d M Y') }}

              {{ entry.title }}

{% endfor %}

The month stays in English, how can I format de post date, with the locale I'm viewing the site?


texts: How to split the user login error message between username and password?

texts:
Hoping this is possible. I want to split the username and password error message to return it separately depending whether it is username or password that is incorrect and not just a the generic (Invalid username or password) message. How do I go about this? I don't require answers as to whether it is more secure or not just whether it is possible.

Cheers


texts: How do I set a controller for my homepage

texts:
How can I set a controller for the homepage? I can't seem to find any way to override the default route to the homepage. I need to call an action from the homepage and can't find any examples of this can be done.

I have a matrixfield with entries in them and want to filter out the matrix blocks that have expired entries on the homepage.


texts:
When saving a whole bunch of users through a plugin I get the following error:

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 1835217 bytes) in /home/butpanel/public_html/cmgg/craft/app/etc/logging/FileLogRoute.php on line 59

The users are saved none the less.


texts: Sending Error Message to Template With No Logged In User - Craft 2

texts:
I'm working at getting error messages sent from my plugin to my template (on the front end), when there is no session (no logged in user).
The plugin is for LDAP authentication.

Edit: For clarification, this plugin (and the error messages) will be for as-of-yet un-logged-in users.  Would a session structure be the only way to get the messages to those end users?

I've tried this (below), but I get the error message (below):

code in the plugin controller:   craft()->userSession->setFlash('msg_template',"Credentials were not accepted.")

code in the template:

{% set message = craft.app.session.getFlash('msg_template') %}

{% if message|length > 0 %}
{{message}}
{% endif %}

error message:

Neither the property "session" nor one of the methods "session()", "getsession()"/"issession()" or "__call()" exist and have public access in class "Craft\AppVariable


texts:
So i'm trying to update a checkbox field using a custom plugin i built. I have three tiers on my site, tier one that you only get access to certain items, tier two you get access to tier one and other additional assets and tier three you get access to everything in both tier 1, 2 and 3.

When you sign up for tier two (while being signed in) the form i have shows the currentUser info already filled into the form. The only item NOT filled is a checkbox that is a terms of use, each form has a different terms of use.

I need to be able to view the user and what Terms of Use they have accepted.


texts: Displaying disabled posts only to post author

texts: I have a simple photo gallery where logged in users can upload photos. I've set the default status for all pictures to disabled, is it possible to show disabled pictures only to user who just published it, and when status is set to enabled everyone can see it?


texts: How to bootstrap / connect to another Craft instance from inside a plugin?

texts:
I'm currently writing a plugin which should connect to another Craft Instance (same server, same app folder) and run some code (start a task or execute a service function).

I looked at the bootstrap.php which looks great, but I can't include it inside the plugin, or can I somehow?

So how can I bootstrap / connect to another Craft instance from inside my plugin?


texts: Craft 3 - Resaving Matrix from frontend causing issues (Craft is not defined)

texts:
I’m having an issue with resaving a matrix block on users from a front end form. The problem is that after resaving the block and the page reloading. The styling on the page breaks until reload.  When opening the web console, a number of errors are returned that I’m pretty sure shouldn’t be in the front end:

I think I may have found the code in the craftcms vendor files that is causing this to happen. It is located in craftcms/cms/src/elements/MatrixBlock.php

Commenting out the following code seems to stop all of the errors and on reload the page is fine:

/**
 * @inheritdoc
 */
public function afterDelete()
{

    if (!Craft::$app->getRequest()->getIsConsoleRequest()) {
        // Tell the browser to forget about this block
        $session = Craft::$app->getSession();
        $session->addAssetBundleFlash(MatrixAsset::class);
        $session->addJsFlash('Craft.MatrixInput.forgetCollapsedBlockId('.$this->id.');');
    }

    parent::afterDelete();
}

Apart from this, I can’t seem to get any further into cracking the issue. Does anyone have any ideas? Thanks.


texts: Paginate entries with 'page' query parameter?

texts:
Is it possible to use a page query parameter for paginating entries with {% paginate %} instead of a dynamic segment?

So instead of http://example.com/articles/p2 i would like to use http://example.com/articles?page=2.

This would simplify interoperability with client side MVC frameworks because the query parameter would be clearly separated from a dynamic route for a single entry in articles (i.e. http://example.com/articles/a-single-article).

The only solution I can think of at the moment is to not use {% paginate %} altogether and instead calculate limit and offset for craft.entries.find(...) manually from craft.request.getQuery("page"). I hope there is an easier way?


texts:
I'm trying to get my Craft translations to work with the translation management tool Phraseapp.

The standard format for translation-files in Craft CMS looks like this:

# de.php

return [
    'good_morning' => 'Guten morgen',
    'KEY' => 'GERMAN_TRANSLATION_VALUE'
];

But this format is not supported by Phraseapp.

Is there a way to return json or yaml instead?


texts:
1.{% set workTitle = craft.request.getLastSegment()  %}
2.{% if currentUser %}
3.     {{workTitle}}
4.{% else %}
5.  {% redirect "/visit/index?artwork=workTitle" %}
6.{% endif %}

Each line of code are working fine except the line 5. I set a value on line 1. Line 3 returns the set value but on line 5 when am trying to redirect it doesn't return correct path.
Redirect returns the below path instead of the returning the set value of workTitle.

http://abc.dev/visit/index?artwork=workTitle


texts: Expire an entry according to a date field

texts:
Ich have a concert entry which I want to expire after the concert is over.

How do I do that?

I was able to hide past entries like this:

{% set present = now|date_modify("+1 day") %}
{% for entry in craft.entries.section('concert') %}
     {% if entry.konzertdatum > present %}
       {{ entry.konzertdatum|date('d. M. Y - H:i')}} - Concert Bla
     {% endif %}
{% endfor %}

But ist it also possible to expire this entry altogether os its marked in the CP?

Or would it be better to use the post_date as a concert timestamp and then show somehow only future dates?


texts: How can I pass an array to an api call from my plugin?

texts:
This isn't entirely Craft specific, but I am using this in my plugin so I guess if I get booed out - I deserve it.

I am working on a plugin that makes a call to a 3rd party API. I am using Guzzle to make the post/put requests and all is working well.

I am struggling though, now that I want to move beyond a 1:1 parameter:value query.

For example, I have this:

$client = new \Guzzle\Http\Client('http://site.com/api/');
$uri = 'users?id=' . $event->params['user']->id .
       '&first_name=' . $event->params['user']->firstName .
       '&last_name='  . $.event->params['user']->lastName;

$request = $client->post($uri, array('content-type' => 'application/x-www-form-urlencoded'));
$request->send();

So far so good.

Now I would like to add an "activities" parameter. Any user could have more than one activity. I am displaying them as a checkbox on my registration form - and I'm able to get the values. I am just not sure how to pass those values in my plugin to the api call.

$activities = $event->params['user']->activity;
$selectedActivities = array();

foreach ($activities as $option) {
    if ($option->selected) {
        $selectedActivities[] = $option->value;
    }
}

error_log(print_r($selectedActivities, true));

// [0] => 2
// [1] => 3
// [2] => 4

Each value is the id of the activity I am passing along.

How does that array get passed into my existing call? This is obviously incorrect, but here is what I am trying to do:

...
$uri = 'users?id=' . $event->params['user']->id .
       '&first_name=' . $event->params['user']->firstName .
       '&last_name='  . $.event->params['user']->lastName .
       '&activities=' .$selectedActivities;
...

I've tried using serialize() but I get some funky results.

Thank you for any suggestions!

EDIT

I have updated my calls accordingly - thank you for the tip!

I'm seeing all values come across except the activities array.

$client = new \Guzzle\Http\Client('http://mysite.com/');
$uri = 'api/students?api_token=123';

$post_data = array(
    'first_name' => $event->params['user']->firstName,
    'last_name' => $event->params['user']->lastName,
    ...

  );

$request = $client->post($uri, array(
    'content-type' => 'application/json'
));

foreach ($selectedActivities as $option) {
    $request->getPostFields('activity', $option);
}

$data = json_encode($post_data);

$request->setBody($data);
$response = $request->send();

Everything is coming across and getting saved correctly, I'm just not seeing 'activity' in the request at all.

Thank you again for your help!


texts:
I'm looking for a way to output line break from a text field.

I'm aware of the "Allow line breaks" option and I have set that to true. I've then entered text with multiple new lines. However, when this text gets output in the template, there are no line breaks.

I have tried using Twig's new line to br function, like this:

{% set address = contact.address|nl2br %}

but this creates
 tags in the text, not the markup - that is, you can actually see the
 in the browser and no actual line breaks are being created.

Am I doing something wrong here? Are there any alternative solutions?

Thanks!


texts: Detecting if page is a 'category' or 'entry'

texts:
Is there another way of detecting if a page is an 'entry' or a 'category' than the following? Maybe some global variable that I do not know of?

{% if entry is defined %}
  <!-- Code here -->
{% endif %}
{% if category is defined %}
  <!-- Code here -->
{% endif %}

I have a html code block that is included in both entry pages and category pages hence the need for this.

Thanks in advance!


texts: Is there a way to force Assets to redo transforms?

texts:
Client has uploaded a number of severely badly lighted photographs for a 'staff' section of a site and these all have had a 'staffThumb' transform applied to it on the sites pages.

I corrected the lighting on the originals in Photoshop and re-uploaded those -- how do I make assets redo these transforms? Deleting the images in the _staffthumb folder doesn't do it.

Any pointers?


texts: Integrating Yii 2 modules and frontend widgets with Craft CMS 3

texts:
I'm experienced in Yii2 framework, but I just discovered Craft CMS and I already love it.

I use to develop Yii 2 modules using their own DB tables, models, controllers and views.
I usually use Yii extensions and widgets from Krajee (http://demos.krajee.com/widgets) for the frontend, to create rather complex forms.

I'd like to integrate such modules and widgets in some pages of a Craft-managed website, using Craft for user management/access control and templating if possible.

Which structure would you recommend ?

Should I keep a separate instance of Yii 2 on the same server ?  If so, how can I integrate Yii2 views (PHP code) in Twig templates (no PHP) ?

Or should I redevelop Craft modules or plugins using Twig ?  If so, how can I integrate Yii 2 frontend widgets and extensions in Twig templates and Craft CMS modules ?

Thanks in advance for your advice.


texts:
Does anybody know if it is possible to overwrite entry.title in a template?

The following 2 options causes errors:

{% set entry.title = 'value' %}
{% set entry['title'] = 'value' %}


texts: Is there a way to avoid content duplication on multi site setup?

texts:
I have just crated a multi site according to the instructions on Crafts page.
Lets just say I have:

siteone.com with template forlder templates/siteone
sitetwo.com with template forlder templates/sittwo

It all works fine however all templates from templates/siteone can also be accessed on sitetwo by simply going to sitetwo.com/siteone/site-one-only-template

Is there a way to prevent that?

I've went through all the pages and added "_" to the template filename, then updated template paths of each single to reflect that. This now works as expected, however what's the point of site specific template folder if it's still routed to by other sites?


texts: Display entries by current entry author?

texts: I have a blog section on my site and would like a "More posts by this author" list. How would I go about this, the logic is clear but the syntax to write for it is not forthcoming.


texts: CP login error for (only) one user in particular

texts:
One of our client logins has stopped working.

When you try to login there's a spinner and then Failed to load resource: the server responded with a status of 504 () error on index.php:1

Sometimes you get a 504 on index.php?p=admin/actions/users/login at jquery.js:9827 instead.

(Running Craft v3.1.34)

Any ideas?

I've tried resetting the password as per https://craftcms.stackexchange.com/a/13966/7356 but this doesn't help, ditto for resetting the password via a 'Copy Password Reset URL' link.


texts: Configuring CraftCMS on Arcustech with Cloudflare flexible SSL returns 521 error

texts:
I have installed CraftCMS on an Arcustech VPS and successfully added a domain name. Using the domain without the shared SSL works without any problems (e.g. www.example.com / example.com). However after adding the Cloudflare shared SSL certificate and using the "Flexible" configuration option, the website returns Error 521 Web server is down.

I have configured the domain in the CraftCMS CP to contain https and added the following to my .htaccess file:

# SSL only
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !^https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Am I missing a crucial step to get the SSL working?


texts: Craft 3: fetching a single Matrix row by its dropdown field value

texts:
I have 2 Matrix fields in an entry type, both of which use Dropdown fields:

Matrix: urls
    address (block type)
        context (dropdown field values include 'own')
        address
        urn

Matrix: logos
   svg (block type)
        usage (dropdown field values include 'monoNeg')
        aspectRatio
        svg (source code)
   img (block type)
        usage (equivalent dropdown field)
        img

Entries are assigned to a footer Globals field, from which I'm pairing a urls value with a logos value in a loop to write linked logos.

I can get the relevant URL easily enough with:

{% for org in footer.footerAccreditations %}
    {% set orgUrl = org.urls.context('own').one() %}
    {{ orgUrl.address }}
{% endfor %}

Which prints the address URL just fine.

But the same approach for the svg logo isn't working. Either one of the following returns 0, even when I know for sure that the org entry in question has a monoNeg SVG source.

{% set negLogoDirect = org.logos.usage('monoNeg').one() %}
{{ negLogoDirect|length }}

{% set negLogoTyped = org.logos.type('svg').usage('monoNeg').one() %}
{{ negLogoTyped|length }}

If I run through an all loop for the logos their usage reports exactly as I would expect:

{% set orgLogos = org.logos.all() %}

{% for logo in orgLogos %}
    {{ logo.usage }}
{% endfor %}

I assume I can make my template more verbose and get what I need, but I don't see why the same approach should work for one Matrix dropdown field and not for another.

Where am I going wrong?


texts: Can the Element API export Craft Commerce orders as the element?

texts:
Background: We are considering using Craft Commerce to replace Shopify for more custom fields.
However Craft Commerce does not have simple export buttons for exporting orders, so we are looking at the Element API plugin to build our custom plugin to get each order as a order-xxx.json

Question: Can i use Craft Commerce orders as a element in the Element API plugin?


texts: Is there a thumbnail generator plugin for video assets?

texts:
I need a thumbnail image of a video which i upload as an asset. Instead of uploading an image manually I'd prefer craft to generate a thumbnail for me.

Is there a plugin I didn't find or did someone find another workaround?


texts:
In my current website-project I have to repeat myself very often. In several sections / matrix fields I use field configurations like:

Spacing (Dropdown: small, medium, large)
Buttons (SuperTable with Linkits)
...

The problem is if I add a new spacing option, I have to change multiple field configurations.

Is there an approach to move this field configuration to a "component" and use a "Buttons" field instead of creating a SuperTable field for each section again?


texts:
I followed this question like:

...
"repositories": [{
    "type": "vcs",
    "url": "git@bitbucket.org:jorgeanzola/mymodule.git"
}
],
...

"require": {
    "craftcms/cms": "^3.0.0",
    ...
    "jorgeanzola/mymodule": "^1.0.0"
},

...
"autoload": {
    "psr-4": {
        ...
        "modules\\mymodule\\": "modules/mymodule/src/",
    }
},
...

"extra": {
  "installer-types": ["craft-module"],
  "installer-paths": {
    "modules/mymodule": ["type:craft-module"]
  }
},
...

When I do a composer install, I get this error:

[RuntimeException]
craft/plugins/schematic/ does not exist and could not be created.

In my module I don't do anything with Schematic. Any idea what am I doing wrong?


texts: Is there a masked input field type for Craft?

texts:
Is there anything like the EE add-on for Craft?

This would be really useful for part numbers, etc.


texts:
I know this question has been asked a few times but no of the answers work.

I have a News channel with a Users field type as one of the layout fields.

I want to find all news entries related to user id X but the entries returned are wrong.

{# Get current member e.g URL /members/1/ #}
{% set currentMember = craft.users.id(craft.request.segment(2)).first() %}

{# Get current members news entries #}
{% set currentMemberNews = craft.entries.section("news").relatedTo(currentMember) %}

currentMemberNews contains all news. I just want the currentMember news.

Not sure what I am doing wrong?


texts: How to build a web page using different sections created in Craft

texts:
I am a beginner in Craft. I have a Craft website. There is an HTML design with me. From admin, I divided the HTML into sections and created entries based on that. All the coding related to each sections done.

My question is, from where we will combine these sections for creating a page on the website?

I want to replace some already existing sections with new sections created.
From which part I can find this one?


texts: Return previous or next enabled sibling of same parent

texts:
I want to link to enabled sibling entries within a structure and am struggling to get it working.

This is what my structure looks like:

Because I only want to fetch entries that are enabled, I followed the docs instructions and fetch previous entries like this:

{% set prevEntry = craft.entries.positionedBefore(entry).order('lft desc').first() %}

With this, when on the Prince Phillip entry, I thought that would return null for prevEntry, but it is returning the Altynia Asylmoratova entry.

How can I fetch previous and next entries that are direct siblings and enabled?


texts: Craft warning: Tried to release a savepoint, but it does not exist

texts:
I'm working on a plug-in for Craft 3. For this plug-in is a migration is needed.
When this migration runs and adds the entries, fields, and groups then the following warning occurs in the logs.
[warning][craft\db\mysql\Schema::releaseSavepoint] Tried to release a savepoint, but it does not exist: SQLSTATE[42000]: Syntax error or access violation: 1305 SAVEPOINT LEVEL2 does not exist
The SQL being executed was: RELEASE SAVEPOINT LEVEL2

This error means that the save point not exists.
I use Craft Pro 3.5.19.1 with PHP 7.4.12.
My question here is, what causes this warning?


texts: Getting Entries that were updated after a certain day?

texts:
I need to get all the entries that were updated after a certain date, I tried a couple things, but it doesn't seem to work, does anyone know how I can accomplish this?

This seems wrong to me, but it doesn't throw any error, neither does it accomplish what I want.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'affiliates';
$criteria->dateUpdated("> '2015-09-02'");

$query = craft()->elements->buildElementsQuery($criteria);
$queryResults = $query->queryAll();

$affiliates = EntryModel::populateModels($queryResults);


texts:
I'm pretty new to Craft and Craft Commerce and right now I'm struggling with the following: in the navigation I want a list item for every product type. This works with the following code:

{% for productType in craft.commerce.productTypes %}
    <li>{{ productType.name }}</li>
{% endfor %}

But how can I now link this product type to an collection template and show only products of this type?

And the second question is: If at least one product has the tag "new" I want a list item for this in the menu as well. I created a tag field for this. But how can I now check if there are products with this tag and can I link this to an collection template as well?

Thanks for your help!


texts: Customize Stripe payment intent forms when using Stripe for Craft Commerce (commerce-stripe) plugin

texts:
Is it possible to style the fields contained in the Stripe Intents form when using this plugin?

Currently the form seems to load with all the interactions but with minimal styling. I'd like to have the CC form styles identical to other form elements on the page but having a difficult time figuring out how to do so.

Any help would be much appreciated!

This is what the form currently looks like (card holder info are from the twig template and the plugin fields below)

I'm using the latest Craft 3 + Commerce 2.


texts: Access a function in a plugin from another plugin

texts: I have some functions in another plugin that I'd like to use. For example, I'm using the shortcodes plugin, and it has a function shortcode_atts that I want to use in my plugin.


texts: What is the benefit of using a calendar event plugin or building your own?

texts: I am looking at purchasing Venti 2 for events and also what it takes to build my own plugin.  Does anyone know what kind of time it takes to build a plugin that does reoccurring dates, categories and such.  Would I need to put the entries into a separate database table?  Getting back to Venti, has anyone used it and does it have enough custom functionality compared to creating my own?


texts: How to reset matrix field to have NO blocks in plugin?

texts:
I want to reset a matrix field to have no blocks in it. In a plugin, I would normally set a matrix field by doing something like this:

$blocks = [];
$i = 1;
foreach ($itemsArray as $item) {
    $blocks['new' . $i] = [
        'type' => 'myBlockTypeHandle',
        'fields' => [
            'someBlockFieldHandle1' => $item['value1'],
            'someBlockFieldHandle2' => $item['value2'],
            'someBlockFieldHandle3' => $item['value3'],
        ],
    ];
    ++$i;
}

$entry->setFieldValues([
    'myMatrixField' => $blocks,
]);
Craft::$app->elements->saveElement($entry);

But I want to do the opposite and set the matrix field to have no blocks. I have tried setting the field to an empty array but it doesn't work:

$entry->setFieldValues([
    'myMatrixField' => [],
]);
Craft::$app->elements->saveElement($entry);

There are no errors on save but the empty array gets ignored and my matrix field still has its data in it. I've tried setting it to empty nested arrays and to null but they all get ignored.

How do I reset a matrix field?


texts: Plugin sending emails to all users in an entries Users field

texts:
I have a channel set up with front end submitted entries. I want a way for users to be able to subscribe themselves to receive an update whenever the entry (or it's related entries) are updated. I was thinking one way to so this so that it can be managed on the front end would be to add a Users field to the entry and let logged in users add themselves to it.

I have a simple notification service that I am using in a custom plugin that is sending emails to entry authors, but I'm not sure how, or what would be the best way to send emails to multiple users as per the above requirement.

(p.s I'm new and limited in my plugin knowledge!)

Any thoughts or suggestions.

Thanks!


texts: Getting redirected to login page on every other CP request when using Vagrant

texts:
I'm developing on a Virtual Box on a Mac, and every time I log into the CP, I can log in successfully and click on one (maybe two) links before getting redirected to login again. I tested this on a staging server and it's working, but not in vagrant. However, I can get other things like Wordpress to allow me to login fine on the Vagrant box, so it seems to be some combination of Craft + Vagrant issue.

Any thoughts on where I might look to debug?

Note: I understand this is probably a vagrant issue, but curious if I can get any pointers of where to start looking inside of craft to find the potential problem/incompatibility.


texts: Display additional fields (and sort by) in Entries in Control Panel

texts:
I have created a Calendar channel in the Control Panel.
I have added a field Calendar Date.

Is it possible to add that field to the Entries list and sort by it?

If I use the post date as the calendar date it will not display if it is in the future?


texts:
We're looking at various CMSs for our large 11,000+ page website. We'd like to use a CMS that is appropriate for sites of that size and that will give us room to grow without impacting site speed, page load time, etc. I see other questions on this forum regarding site size, but all use CraftCMS terminology, such as 'channels', 'structures', etc to describe size.
How can CraftCMS size capability be described in pages?

Thank you.


texts: How to get the previous or next two entries

texts:
I have an entry which needs to display the previous two entries, and the next two. I see in the docs there's a nextSiblingOf method. That does nothing in a channel, and in a structure it will only return one entry. I can't see an ability to "offset" the result.

1: Is this possible in a channel

2: What do I need to do to grab the previous/next two entries in either case?


texts:
My edit profile page doensn't save all fields:

<form method="post" action="" accept-charset="UTF-8" enctype="multipart/form-data">
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="/users/{{ user.username }}">
    <input type="hidden" name="userId" value="{{ user.id }}">

    <fieldset>
      <legend>Your Photo</legend>
    {# Check to see if the user has a photo  #}
    {% if currentUser.photoUrl %}

    {# If a photo exists, give the option to change the user photo #}

    <input type="file" name="userPhoto" value="Change Photo" class="form-control">

    {% else %}

    {# If no photo exists, give the option to upload a new one #}

    <input type="file" name="userPhoto" value="Upload" class="form-control">

    {% endif %}
  </fieldset>

  <fieldset>
    <legend>Your Login Details</legend>

    Email address
    <input type="email" class="form-control" id="email" name="fields[email]" value="{{ user.email }}">

  </fieldset>

  <fieldset>
  <legend>Your Personal Details</legend>

  First Name
  <input type="text" class="form-control" id="firstName" name="fields[firstName}" value="{{ user.firstName }}">

  Last Name
  <input type="text" class="form-control" id="lastName" name="fields[lastName]" value="{{ user.lastName }}">

  Contact Number
  <input type="text" class="form-control" id="phoneNumber" name="fields[phoneNumber]" value="{{ user.phoneNumber}}">

  </fieldset>

  <fieldset>
    {% set pets = craft.fields.getFieldbyHandle('pets') %}

  <legend>Your Property Details</legend>
  {{ pets.instructions }}
  <select class="form-control margin-bottom" id="pets" name="fields[pets]">
    {% for option in user.pets.options %}
    <option {% if option.selected %}selected="selected"{% endif %}>{{ option }}</option>
    {% endfor %}
  </select>

  {% set renting = craft.fields.getFieldbyHandle('renting') %}

  {{ renting.instructions }}
  <select class="form-control margin-bottom" id="renting" name="fields[renting]">
    {% for option in user.renting.options %}
    <option {% if option.selected %}selected="selected"{% endif %}>{{ option }}</option>
    {% endfor %}
  </select>

  </fieldset>

  <input type="submit" class="btn btn-primary pull-right margin-top" value="Save Profile">
</form>

It only saves the last two fields which means that a user can't change their email address, name or phone number.

I've recently updated Craft to the latest build (Craft Pro 2.1.2566) and also changed user/saveProfile to user/saveUser.


texts: Researching Craft CMS but we are a .NET Shop

texts:
I am involved with researching various CMS solutions and Craft CMS is one of the options for our organization as an Enterprise soluton, so not just for development use cases. When it comes to development we are mostly a Microsoft shop when it comes to the front-end so my question is, and I apologize for my ignorance on this, can I have an ASP.NET web application pull content from Craft? From what I can tell it looks like Twig is the development language, which again as I understand it is a language that generates PHP. We are not a PHP shop by any means so just wondering if there is some sort of plug-in or API that I could make calls to from an ASP.NET web application to pull out content from Craft. Is there anyone doing anything like this?

Again, I apologize for my ignorance but just trying to clear up some of the high level questions being brought up.

Thanks!


texts: Cannot add more fields - SQLSTATE[42000]: Syntax error or access violation: 1118 Row size too large

texts:
I've been bumping into a field limit when attempting to mirgrate fields in, which is a massive limitation for the way the site was originally set up.

I've read a bunch of other threads where it's suggested changing the table to barracuda and dynamic

I've added this to the mysql conf:

innodb_file_per_table=1
innodb_file_format = Barracuda
innodb_log_file_size = 512M
innodb_strict_mode = 0

And I've ran ALTER TABLE craftcms.craft_content ROW_FORMAT=DYNAMIC

I've confirmed that this has all been updated in INNODB_SYS_TABLES and GLOBAL_VARIABLES in the information_schema, but it doesn't seem to make any difference.

Just as a test to see when I hit the limit, I've added a load of test plain text fields - the result is 219 custom fields:

125 TEXT
51 VARCHAR(255)
37 TINYINT(1)
4 VARCHAR(2000)
1 TINYINT(2)
1 DECIMAL(3,1)

I appreciate that refactoring some of the data structure is the way forward, but given that migrating the data won't be an easy task, I'd obviously prefer if there's some database solution to mitigate this issue quickly.

Any suggestions?


texts: Overriding isSystemOn setting for a single page

texts:
I have a staging site that has the isSystemOn set to false since I don't want people to stumble upon the site and be able to view content. I would like to have 1 page still "visible" though. This URL would a simple health check page, that I direct a monitoring service to check on. I'm stumped at overriding a system level isSystemOn config setting.

Can I have staging.example.com/my-secret-health-check-url return a valid code of 200 so my monitoring service can correctly see that my staging site is working?


texts: Syntax for permissions in comments.php config file (comments plugin by Verbb)

texts:
I'm using the comments plugin (https://plugins.craftcms.com/comments)
I'd like to define the 'permissions' settings via the config/comments.php file but can't find docs on the syntax to use.
The default reads
    // Permissions
   'permissions' => [],

which doesn't give me much to go on.
Could someone please provide an example I could work out the correct syntax from?
Many thanks!


texts: Element Criteria Model: filtering by empty values

texts:
I'm trying to use the Element Criteria Model to retrieve all entries where value X or value Y is not null?

I can get all entries where values and X and Y are not empty but not sure how to achieve this with either X or Y being not empty. any thoughts?

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

foreach ($fields AS $field) {
    $criteria->$field = ':notempty:';
}

$entries = $criteria->find();

This is what I have for AND but not sure how best to go about achieving the same query for OR.

An equivalent SQL query would be something along lines of WHERE (X IS NOT NULL && X <> '') OR (Y IS NOT NULL && Y <> '')


texts:
Can anyone help me work out why the following returns the error "The merge filter only works with arrays or hashes."?

{# CREATE ARRAY TO HOLD ALL OF TODAY'S EVENTS #}
{% set todaysEvents = [] %}

{# GET TODAY'S ONE-OFF EVENTS #}
{# RETURNS ENTRIES NICELY IF LOOPED THROUGH #}
{% set todaysOneOffEvents = craft.entries.section('events').eventDate('= '~today | date("Y-m-d")) %}

{# ADD TODAY'S ONE-OFF EVENTS TO TODAY'S EVENTS %}
{# THIS RETURNS MERGE ARRAY ERROR #}
{% set todaysEvents = todaysEvents|merge(todaysOneOffEvents) %}


texts: Migration to new server, left with default theme?

texts:
I have migrated a website that uses Craft CMS over to a new server. The instructions that I followed were outlines in this post: Migration of Craft CMS from one host to another

The domain name in question is : glosenterprise.co.uk - this is how its meant to look. Here is a screenshot of how it is looking on the server.

I am completely new to Craft CMS but to me it looks as though its not pulling in the theme that was created for the live site.

Is there anything obvious that I missing or a direction that people can point me in?


texts: How can I let the user activate a particular SuperSort filter

texts:
***I have just realised I am mixing up my filtering and sorting. I have amended the question to try and make it a bit clearer.

I'm trying to use SuperSort plugin to run different filters, but I'm struggling as only the last filter gets applied. I would like to add the filter to a button or link, so that when the user clicks on it, it activates the filter. Any tips?

search

<form action="{{ url('search') }}">
    <input type="search" name="q" placeholder="Search">
    <input type="submit" value="Go">
</form>

{% set query = craft.request.getParam('q') %}
{% set users = craft.users.search(query).order('dateUpdated')|reverse %}

{% if users|length %}

        <span{{ users|length }} results:

A-Z

Z-A

Nearby

Newest

Oldest

{% endif %}

For example:

link#1 - sort A-Z
link#2 - sort dateUpdated


texts: Get all categories from a CategoryGroupModel through API

texts:
When I get a CategoryGroup with the following

$category = craft()->categories->getGroupByHandle('productEnvironment');

I Just can't figure out how to get the categories inside this category.
Is-there any kind of relation/method ?

Thanks

Nicolas


texts: Can a plugin add JS or CSS to the control panel in Craft 3?

texts:
I want entries in a specific PlainText field for a named group to be pre-filled with random content. I am aware of the https://github.com/lukeyouell/craft-randomkeygenerator plugin and am aware that I could create my own field type, but I am intending to use jQuery to do this instead (which should be easier).

This Can a plugin add JS or CSS to the control panel? describes how to do this in Craft 2 (I assume that the code works). My equivalent in Craft3 is...

class MyPlugin extends Plugin {
    if (Craft::$app->request->getIsCpRequest())
    {
      Craft::$app->templates->includeJs('alert("xxx")');
    }
}

but $app->templates does not work. So is there a Craft3 equivalent of this line?

NB: I have already written a plugin that is adding a file volume (for encrypting files uploaded as Assets) so intend to add to that.


texts: List the categories an entry is part of?

texts:
I'm new to all of this and so far Categories from a templating point of view are confusing me a bit. I'm loving Craft so far but some concepts are causing me some headaches to adjust to!

What i'm trying to do is list the sub-categories a blog post is part of.

I have 6 categories and each has 4 sub-categories.
I only want to list the sub-categories.

So when someone is viewing the site and they click into a full blog post page, at the top i'm listing the title, author, posted date and i want to follow that with a lisrt of the sub-categories applied to that blog post.


texts: Adding active class to globally cached navigation

texts:
I have a structure which controls my main site navigation.
It's the same across the site so it is best to cache globally as opposed to a cache of the navigation or every url.

The last answer on this pages says that you can use Twig's replace filter to achieve this:
Would you use a Structure as navigation over multiple sections (channel entries, indexes and singles)?

My code below shows the active class being placed on the li tag but that doesn't work with the cache globally.

Can it be done with Twig's replace filter?

{% cache globally for 3 years %}
  {% set entries = craft.entries.section('navigation') %}

    {% nav entry in entries %}

      {# Check for entry type / get related entry #}
      {% if entry.type == 'customLink' %}
        {# Link to a custom url #}
        {{ entry.title }}
      {% elseif entry.type == 'relatedEntryLink' %}
        {% set linkedEntry = entry.relatedEntry.limit(1).first() %}
        {{ entry.title }}
      {% else %}
        {# Link to a structure entry #}
        {{ entry.title }}
      {% endif %}
      {# Repeat this for child entries #}
      {% ifchildren %}

{% children %}

      {% endifchildren %}

    {% endnav %}

{% endcache %}


texts:
I've just migrated a craft site to a staging server from a local environment and have come across an odd bug I have no idea what's causing it.

If I use the word "select" in a blog post, the entry doesn't save and instead goes to a 404 page. If I capitalise a letter, "Select" for instance, it saves fine.

It's a rich text field that has the content and this didn't happen on my local environment either. There doesn't seem to be any errors showing up in craft logs as far as I can tell either.

Does anyone have any suggestions?

Thanks.


texts: S3 Assets - uploading with Asset::SCENARIO_REPLACE - throws error: newLocation

texts:
We're programmatically uploading images to an asset volume that's stored in S3; 99% of the time this is fine, but sometimes, for some reason, the asset index is lost and craft thinks it's uploading the image for the first time when infact it already exists in S3.
When this occurs we get the error:
{"newLocation":["A file with the name FINE_NAME.jpg already exists."]}

Syncing assets via the cli/control panel (utilities/asset-indexes) doesn't add the missing files to the Assets Index.
We've now got 2 issues:

We're using Asset::SCENARIO_REPLACE so this image should be replaced.
Even if it's not being replaced, it should still 'add/index' this new asset - but it's not.

Code we're using:
$assets = Craft::$app->getAssets();
$folder = $assets->findFolder(['volumeId' => $volumnId]);

$asset = new Asset();
$asset->tempFilePath =  $path;
$asset->filename = basename( $path );
$asset->title = $title;
$asset->newFolderId = $folderId;
$asset->setVolumeId($folder->volumeId);
$asset->uploaderId = Craft::$app->getUser()->getId();
$asset->avoidFilenameConflicts = false;
$asset->setScenario(\craft\elements\Asset::SCENARIO_REPLACE);

The code we're using should force any existing image to be replaced?
The S3 bucket is private with no public access/images are delivered via imgix:
Application Info
PHP version: 7.4.12
OS version: Linux 5.4.0-1018-aws
Database driver & version: MySQL 8.0.22
Image driver & version: Imagick 3.4.4 (ImageMagick 6.9.10-23)
Craft edition & version: Craft Pro 3.5.8
Yii version: 2.0.36
Twig version: 2.12.5
Guzzle version: 6.5.5
Imagine version: 1.2.3-dev
Plugins
Amazon S3: 1.2.11
Imgix: 2.0.5
Any help would be much appricated.


texts:
Redactor fields are failing to display for my client and I'm stumped as to what might be happening.

They work fine for me and I haven't heard reports from any of the other 10+ CMS users.

It seems OS/browser specific, because the person that reached out is on a brand new computer running the latest version of Windows 10 and Chrome. When I asked them to test in Firefox everything worked fine.

Some more technical details:

The site is running Craft 2.6.3017
Chrome 67.0.3396.87
Windows NT 10.0; Win64; x64
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36

It sounds like it could be related to this question, but it's not quite the same. Has anyone else heard reports of this?


texts:
Looking at this plugin.
https://solspace.com/craft/freeform

Need a form to do this, any help would be pic guys.

Fill in form - sends email to nominated email with enquiry

If sign up to newsletter is chosen then the name is added to mailchimp list and opt in email sent

If sign up response is negative form still sends email to us, but the users email is not added to the mailchimp list or is added with a status of unsubscribe.


texts:
craft()->on('entries.saveEntry', function(Event $event)
{
    // entry slug, will be used as image name
    $EntryTitle = $event->params['entry']['slug'];

    // Get attached image
    $entry = $event->params['entry']['imgdir'][0];

    craft()->assets->renameFile($entry, $EntryTitle);
    $entry->setAttribute('filename', $EntryTitle);
    craft()->assets->storeFile($entry);

});

This init() code gets the current entry title right after it was saved, and is supposed to use it to rename an attached file.
I used a method given by another developer in the context of a saveAsset, but it doesn't seem to work in this new context (→ see Change asset name on upload).

I'm not sure i've set the $entry variable to correct data. Fact is I'm able trough the path you see above, to get access to the asset.
Please tell me where this code is wrong.


texts: Ordering Structure Sections with Structure Handles

texts:
I am using the code below to output a group of sections that have entries along with their section handle. How would I order the sections (ideally by structureId)? I'm not opposed to using supersort but I haven't been able to achieve the desired result.

{% set sections = craft.sections.getAllSections() %}
{% set entries = craft.entries.section(['first', 'second', 'third']) %}
{% set grouped = entries|group('section') %}

{% for sectionHandle, sectionEntries in grouped %}
    {% set groupSection = false %}
    {% for section in sections %}
        {% if section.name == sectionHandle %}
            {% set groupSection = section %}
        {% endif %}
    {% endfor %}

    {% if groupSection %}
        <h1>{{ groupSection.name }} - {{ groupSection.handle }}</h1>
    {% endif %}
{% endfor %}


texts:
I'm attempting to finish my first fieldtype plugin (how exciting!) but having an issue with displaying options in a select dropdown in an entry.

My ColumnWidth_WidthsFieldType has this:

<?php

namespace Craft;

/**
 * Widths Fieldtype
 *
 * Allows entries to select associated widths
 */
class ColumnWidth_WidthsFieldType extends BaseFieldType
{
    /**
     * Get the name of this fieldtype
     */
    public function getName()
    {
        return Craft::t('Column Widths');
    }

    /**
     * Get this fieldtype's column type.
     *
     * @return mixed
     */
    public function defineContentAttribute()
    {
        // "Mixed" represents a "text" column type, which can be used to store arrays etc.
        return AttributeType::Mixed;
    }

    /**
     * Get this fieldtype's form HTML
     *
     * @param  string $name
     * @param  mixed  $value
     * @return string
     */
    public function getInputHtml($name, $value)
    {
        // call our service layer to get a current list of widths
        $widths = craft()->columnWidth_widths->getAllWidths();

        // create an array for the widths
        $widthsOptions = array();

        // populate the $widthsOptions array with $widths
        foreach ($widthsOptions as $widths )
        {
            $widthsOptions[$widths->id] =  $widths->name;
        }

        return craft()->templates->render('columnwidth/_fieldtypes/widths', array(
            'name'      => $name,
            'values'    => $value,
        ));
    }
}

My columnwidth/_fieldtypes/widths has this:

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

{% set widths = craft.columnwidth.getAllWidths %}

{{ forms.selectField({
    instructions: "Select the width of your column"|t,
    id: 'columnWidth',
    name: 'columnWidth',
    options: widths
}) }}

But I'm getting this error:

Craft\ColumnWidth_WidthsModel and its behaviors do not have a method or closure named "optgroup".

The only post I found was here:

Displaying a list of fields in a form select

I'm sure I'm missing something and any help is appreciated!


texts: How to use Sprig to filter categories using a dropdown

texts:
I'm having an issue where I'm adding a dropdown to my search to filter through the first parent attribute in a category (Winter 2020, Spring 2021, and so on). The search field works, but nothing happens if I select from the dropdown (Winter 2020).
What am I missing?
{% set search = search ?? ''%}
{% set category = category ?? ''%}

{% set entryQuery = craft.entries ({
    search: search,
    section: 'articles',
    limit: 2,
    }) %}

{% set myCategoryQuery = craft.categories ({
    group: 'edition',
    level: 1,
    }) %}

{% set entries = entryQuery.all() %}
{% set categories = myCategoryQuery.all() %}

<form>
    <input sprig s-trigger="keyup changed delay:200ms" id="search" name="search" value="{{ search }}" type="text" placeholder="Search" autocomplete="off">
    <select sprig name="category" id="category" value="{{ category }}" class="form-control">
      <option value="">Any</option>
        {% for category in categories %}
          <option value="{{ category }}">{{ category }}</option>
        {% endfor %}
    </select>
  </form>

        {% for entry in entries %}

          {% for category in entry.edition.all()%}
             {{ category }}
          {% endfor %}

{{entry.title}}

          {% for category in entry.authors.all() %}
          {{ category.title }},
          {% endfor %}

        {% endfor %}
        {% if entries|length == 0 %}

No entries found

        {% endif %}


texts: How to pass dynamic arguments into Wordsmith chop parameters

texts:
I have a use case where I need to set a maxChars variable to pass into the Wordsmith plugin’s chop parameters.
So I know I can do this (with the Empty Coalesce plugin):
{% set maxChars = matrixBlock.maxChars ??? null %}
{% set intro    = entry.intro ??? null %}

{% if intro and maxChars %}
    {% set intro = intro|md|chop(limit= maxChars, unit='c', allowedTags='
') %}
{% endif %}

…

    {{ intro|raw }}

But maxChars might be null and I might want the allowedTags string to be a variable too, so it would be handy to be able to set the chop parameters as a hash and pass them in.
The following doesn’t seem to work, but is there something that does?
{# Default tags permitted #}
{% set chopArgs = { allowedTags: '
' } %}

{# Custom tag list #}
{% set tagList = matrixBlock.tagList ??? null %}

{% if maxChars %}
    {% set chopArgs = chopArgs|merge({ limit: maxChars, unit: 'c' }) %}
{% endif %}

{% if tagList %}
    {% set chopArgs = chopArgs|merge({ allowedTags: tagList }) %}
{% endif %}

…

{% if intro %}
    {% set intro = intro|md|chop(chopArgs) %}
{% endif %}


texts:
I have inherited a Craft website and need to update an existing URL, it will open a PDF document, so I need to replace an updated PDF

I have very basic Craft knowledge so need assistance.  I have added a Screenshot below showing the inforamtion behind the link which I hope helps


texts: Conditional email notification on saveUser action?

texts:
I have a simple task: one particular front-end form on a website is being used to update a logged in user's profile. It works. It uses the users.onSaveUser action.

I need to fire off notification emails when a particular input value is true on form submission.

My first attempt was a plugin that just watched the onSaveUser event; but while I could get that to send email, I could not seem to get access to the form fields in order to check whether the email should be sent or not. Therefore it sent emails whenever a user was saved, including when edited in the back-end.

Now I'm trying a plugin that has its own action - myPlugin/saveUser. But I am essentially duplicating the code in the existing users/saveUser function... and that makes it brittle. Is there not a way to get this done by just testing a field property and then passing everything over to the built-in users/saveUser action?

How would you do this?

Here's the simple plugin I had, which couldn't get the POST data and was therefor no good...

public function init() {
    craft()->on('users.saveUser', function(Event $event) {
        $this->requirePostRequest();

        // is in the relevant user group?
        if($event->params['user']->isInGroup('applications')){

            // check this is a submission from the front end form
            $applicationFormFrontend = craft()->request->getPost('applicationFormFrontend', 'default');

            // check the Consent field was true on this submission
            $consentGiven = craft()->request->getPost('fields[consentGiven]', 'default');

            NotifyPlugin::log("The value of applicationFormFrontend is $applicationFormFrontend.", LogLevel::Info);
            NotifyPlugin::log("The value of consentGiven is $consentGiven.", LogLevel::Info);

            if($applicationFormFrontend == '1' and $consentGiven == '1') {
                // Write Email

                ...

                // send the mail
                craft()->email->sendEmail($notificationEmail);
            }
        }
    });
}

EDIT, SOLUTION:

The reason I was not getting values for

$consentGiven = craft()->request->getPost('fields[consentGiven]', 'default');

is because it's the wrong style. It's why it was always getting 'default'. The fix is to use dot notation:

$consentGiven = craft()->request->getPost('fields.consentGiven', 'default');

The original code (as above) works with this modification.


texts: Disabling unused PHP functions and Craft

texts:
The php.ini file has an option called disable_functions. You can add unsafe functions to it so that they cannot be run. Does anyone have any guidelines for a good setup with Craft for this. I realize that this is somewhat sort of subjective, but I'm sure there are some features that could without a doubt be turned off that Craft will never use.

OWASP suggests the below settings. Any thoughts on this?

  disable_functions = "system, exec, shell_exec, passthru, phpinfo, show_source, popen, proc_open, fopen_with_path, dbmopen, dbase_open, putenv, move_uploaded_file, chdir, mkdir, rmdir, chmod, rename, filepro, filepro_rowcount, filepro_retrieve, posix_mkfifo"


texts: How to get instance of DiscountModel in Commerce 2?

texts:
In Commerce i got an instance of DiscountModel Class as follows:

$discount = new Commerce_DiscountModel();

Is this the right way in Commerce 2?

use craft\commerce\models\Discount as DiscountModel;
...
$discount = DiscountModel::instance();


texts:
On a entries (listing) page I'm using pagination and a fixed limit of entries set. I want visitors to be able to select (dropdown) the number of entries that should be listed (limit).

I'm not a Java or AJAX expert can someone show me the way?

   <select>
      <option value="12">12</option>
      <option value="20">20</option>
      <option value="50">50</option>
   </select>

{% paginate craft.entries({
    section: 'holidayHomes',
    limit: 12 ,
}) as pageInfo, pageEntries %}

{% for entry in pageEntries %}

          {{ entry.title }}

{{ entry.body | striptags | slice(0,300)~'...' }}

{% endfor %}


texts: Correct way to merge craft.user field arrays and use outside the loop?

texts:
I'm using preparse field plugin to limit the amount of tags a user can add to his account. I've modified the code slightly so the tags are processed as a comma, separated, list.

The plan is to integrate Selectize with the search form, so that users can choose from all available tags. As I can't use relatedTo, it'll have to involve some manipulation. I understand it isn't considered best practice to do this with Twig, but I'm not versed in PHP to build a plugin (I'm learning Python so Twig will have to do!).

The code below sets a variable to allow access to a merged array, I know there's a similar post (I'd also like to avoid duplicates, but Selectize will ignore them anyway) but I'm struggling to follow that example and use it for my requirements.

Code below:

{% set users = craft.users.group('verified') %}
{% set merged = [] %}

{% for user in users %}
  {% set tags = user.tagsSpecialismSearchable %}
  {% set specialisms = tags|split(', ') %}

  {% for specialism in specialisms %}
    {# Merge the tag arrays #}
    {% set merged = specialisms|merge(specialisms) %}
  {% endfor %}

    {# Test the output #}
    {% for specialism in specialisms %}

{{specialism}}

    {% endfor %}

{% endfor %}

{# Output the merged array #}

{% for mergedSpecialism in merged %}

{{ mergedSpecialism }}

{% endfor %}

I know I'm setting merged in the wrong place, as all it outputs is a duplicate of the last specialisms array. So how would I loop through all users and output the available tags?

I'm probably missing some conditionals to check if the user has actually set tags, so any advice in layman's terms appreciated!

Updated: Working code (Thanks @kcolls)

{% set users = craft.users.group('verified') %}
{% set merged = [] %}

{% for user in users %}
  {% set tags = user.tagsSpecialismSearchable %}
  {% set specialisms = tags|split(', ') %}

  {% for specialism in specialisms %}
    {# Check if specialism already merged #}
    {% if specialism not in merged %}
      {# Merge each specialism #}
      {% set merged = merged|merge([specialism]) %}
    {% endif %}
  {% endfor %}

    {# Test the output #}
    {% for specialism in specialisms %}

{{specialism}}

    {% endfor %}

{% endfor %}

{# Output the merged array #}

{% for mergedSpecialism in merged %}

{{ mergedSpecialism }}

{% endfor %}

For an added bonus, sort the array alphabetically:

  {% for mergedSpecialism in merged|sort %}

{{ mergedSpecialism }}

  {% endfor %}


texts: CORS preflight check failing for AJAX login form on different domain

texts:
I've built an AJAX frontend login form, using plain Javascript. It works fine until I try and access it from a different domain.
The problem is CORS and the preflight request. The preflight request doesn't contain the payload from the login form so Craft routes it to a template called 'users/login'. But as the template doesn't exist, the preflight test is returned 'not ok'. CORS looks to be setup okay on the server, because I can get around the problem by creating an empty template for users/login. Then the login form works (preflight test returns ok, so browser proceeds with main request).
What I really need is for the preflight check to not trigger a 404 and return ok, even without the proper payload. Which means Craft not routing that to a template.
Console message without template existing:
Access to XMLHttpRequest at 'http://server.localhost/users/login' from origin 'http://test.localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

General (under headers tab in Chrome):
Request URL: http://server.localhost/users/login
Request Method: OPTIONS
Status Code: 404 Not Found
Remote Address: [::1]:80
Referrer Policy: origin-when-cross-origin

Response header:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-Requested-With, Content-Type, origin, authorization, accept, client-security-token
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin: http://test.localhost
Access-Control-Expose-Headers: Content-Security-Policy, Location
Access-Control-Max-Age: 600
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
Date: Tue, 14 Jul 2020 05:49:33 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.41 (Win64) PHP/7.0.33
Transfer-Encoding: chunked
X-Powered-By: Craft CMS

I'm using Wampserver and adding those via .htaccess.


texts: Update fields structure from local to production

texts:
How can I change fields/sections structure locally while having a live site and then upload the new structure, without wiping the production site?
In Wordpress ACF you can just Sync the fields structure, here it seems I need to close down the website for development?!


texts: Craft CMS contact form plugin works locally but not in production?

texts:
Locally in a MAMP environment Craft CMS/Contact Form plugin works great! But for some reason in production on a actual live server on the internet it fails to successfully send any emails.

I'm not sure if this is because of the way email is handled by Craft? In Settings > Email, I set the transport type up to Gmail instead of the default Sendmail. But still no luck.


texts: How to pull out all user data in a template?

texts:
I'm trying to pull out user data in a template for specified user profiles whilst the current user is logged in. To do this I check on the userId being referenced and use:

{% if userId != currentUser.id %}
    {% set userProfile = craft.users.id(userId).getContent() %}
{% endif %}

This returns a user object for that user. However when I try to reference any of the fields custom or otherwise for the userProfile it returns blank apart from on userProfile.id which returns the id of the required user.

So what am I missing? I was under the impression that getContent() would pull out all custom fields and these could simply be accessed by using the dot syntax? Or does this only work on currentUser?

Cheers


texts: Use Imager plugin with AssetTransforms defined in admin panel

texts: I'm trying to use the Imager plugin with some asset transforms that I've defined in the admin panel.  Passing the name of the transform is just tossing an error at me.  Is there a way to do this, or do I need to define the transforms inline?