texts: Where do I begin troubleshooting a Form in Craft that is redirecting to /login on iPad and iPhone?

texts:
I'm not sure how to ask this question.  I have a form. It works just fine on desktops.  However when the form is submitted on iPhone or iPad it never makes it to my controller and resolves to the URL /login with a 404 (which is correct, because I don't have a /login template).

It seems this is true for custom controllers and for Craft forms like 'entries/saveEntry'.
I don't have any routes or other rules that target the 'login' url or any other URLs I'm using in the action parameter that I can determine. I've uninstalled all plugins.  Logs only report the 404 error message but they also seem to report that second page request to the 'login' URL.

I've traced the request through the WebApp.php file all the way to around line 254 where WebApp.php hands things off to the UrlManager:

parent::processRequest();

Any ideas what I should be looking for here?  I'm not even sure why this would be happening and feel I'm getting too deep as most routing in Craft is pretty straightforward.  Could there be any other, obvious settings or anything I might be overlooking?


texts: Can I get entries related to one category from a specific site?

texts:
If I can get entries in a category like this:

{% set entries = craft.entries.section('sectionSlug').relatedTo('categorySlug').all() %}

And a entries from another site like this:

{% set entries = craft.entries.section('sectionSlug').site('siteSlug').all() %}

Is there a way to combine them and get entries from another site in a certain category. The following isn't working for me:

{% set entries = craft.entries.section('sectionSlug').relatedTo('categorySlug').site('siteSlug').all() %}


texts: How can I escape Twig code to prevent it from being parsed?

texts: How do I escape Twig code to prevent it from being processed?


texts: Getting a "500 Internal Server Error" when uploading an image asset

texts:
Just giving Craft CMS a test drive. Setup a local site using MAMP Pro. Got the basic site up and running ok, admin as well. Then i wanted to try out image assets, so I created an Asset Source for images, local folder. Created my "images" folder under the public dir, and specified "images/" as the file system path for my asset source. Added an image transform.

Then I try and upload an image, and it fails, with the ajax call "/index.php/admin/actions/assets/uploadFile" returning a 500 error. I tried checking the log files but there are no error messages relating to this failed ajax call.

Any ideas what I am doing wrong? Thanks!


texts:
I'm trying to work through some issues with the field content for our Maps plugin, but I'm not sure about the best way to go about it.

Currently the value for each map field is stored as an element with the content stored in a custom table. This is useful for a couple of reasons. First, we can use the separate table to perform complex quering of elements by their geographic location or sort them by distance. Second, it allows us to take advantage of eager loading so we get the benefit of storing our content separately, while not having to worry about the N+1 query problem (assuming people with the field in their queries).

But there are some drawbacks, which is why I'm looking to change how we do it. First there's a bug where data is not propagating across sites and I can't for the life of me work out why. Second, when you eager load the field you have to get the first value of an array (entry.map[0]) to get the map content rather than just accessing it directly. And finally, having an element and everthing that comes with it seems overkill considering how simple the data is.

Idealy I'd like to either get the data for the field as part of the element query (along with the regular content), or I'd like to manually handle eager loading all the data and have it happen automatically (and not require [0] when accessing it).

Is there a correct way of storing this kind of data? Are either of my two options above actually do-able?


texts:
Is it possible to search through multiple ElementTypes?

Instead of this:

craft()->elements->getCriteria(ElementType::Entry)->limit(10)->search('Test');

Doing something like this:

craft()->elements->getCriteria(ElementType::Entry, ElementType::Asset, ElementType::Category)->limit(10)->search('Test');


texts:
I'm building a Users search page.

I want to search the members group based on the following fields that I've setup for Users:

First Name
Last Name
Company Name (handle: genericCompany, type: Plain Text)
Company Overview (handle: membersCompanyOverview, type: Rich Text)
Contact (handle: membersContact, type: Plain Text)
Contact Email Address (handle: globalEmailAddress, type: Email Address)
Contact Position (handle: genericPosition, type: Plain Text)
Services (handle: membersServices, type: Categories)
Locations (handle: membersLocations, type: Categories)

My HTML form (removed labels etc to keep form example clean):

<form id="directory_search_form">
    <input type="text" name="keywords" value="">
    <input type="checkbox" name="services[]" value="service-1">
    <input type="checkbox" name="services[]" value="service-2">
    <input type="checkbox" name="services[]" value="service-3">
    <input type="checkbox" name="locations[]" value="location-1">
    <input type="checkbox" name="locations[]" value="location-2">
    <button type="submit">Go</button>
</form>

My jQuery:

var form = $("#directory_search_form");

form.on("submit",function(event) {
    event.preventDefault();

    var errors = 0;

    if(!$("#keywords").val()) {
        errors++;
    }

    if(errors == 0) {
        $.post("/search",$(this).serialize()).done(function(result) {
            $("#results").html(result);
        });
    } else {
        alert("Please enter some keywords and try again.");

        return false;
    }
});

My Search template:

{% if craft.request.isAjax %}
    {% set params = craft.request.getPost() %}
    {% set keywords = "" %}
    {% set serviceCategories = craft.categories.group("services") %}
    {% set locationCategories = craft.categories.group("locations") %}
    {% for key in params | keys %}
        {% if key == "keywords" %}
            {% set keywords = params["keywords"] %}
            {% set keywords = keywords | trim %}
        {% endif %}
        {% if key == "services" %}
            {% set services = params["services"] %}
            {% set servicesCategories = services | join(", ") | trim %}
            {% set serviceCategories = craft.categories.group("services").slug(servicesCategories) %}
        {% endif %}
        {% if key == "locations" %}
            {% set locations = params["locations"] %}
            {% set locationsCategories = locations | join(", ") | trim %}
            {% set locationCategories = craft.categories.group("locations").slug(locationsCategories) %}
        {% endif %}
    {% endfor %}
    {% set members = craft.users.group("members").status("live").relatedTo([ "and", { targetElement: serviceCategories }, { targetElement: locationCategories } ]) %}
    {% if members | length %}
        {% for member in members %}
            {{ member.email }}<br>
        {% endfor %}
    {% endif %}
{% endif %}

This gives me all members for selected categories.  However I want to hook up the keywords field to further search users.

I also want to get only those users that are related in all categories not either categories.

I've got the keywords but if I add

.search("*" ~ keywords ~ "*")

I don't get any members for my keywords - e.g Operations Manager when there are Members in the system with Contact Position field set to Operations Manager.

I want to search by multiple keywords and multiple categories.

What am I doing wrong?


texts:
I'm using the dukt.net Twitter plugin, in a Matrix field. It works fine locally, but on our dev server, something odd is happening, when I enter a Tweet url, like:

https://twitter.com/POLITICOEurope/status/596249628892364800

It fetches the tweet from the API correctly, but then displays it in the CP and in the templates as:

https://twitter.com/POLITICOEurope/status/5.96249628892E+17

So it converts it to a float. However, in the "fields_tweets_tweet" field in the database, it lists the correct long ID: 596249628892364800

And the odd thing is that it's happening on the dev server, but not locally. Anyone an idea where to start?


texts: Two Plugins not showing in CP after pushing to staging server

texts:
Two different plugins not showing in the CP after code was pushed to staging server.

My questions:

1) Why wouldn't the plugins show in CP if plugins are present in the craft_plugins table?

2) How to troubleshoot this issue?  I'm not seeing any plugin errors in php-error.log or craft.log.

What I know:

-- Two plugins are NOT showing:

truncHTML ( my own custom twigFilter )
the "Import" plugin (
boboldehampsink v 0.7.1- latest)
Other plugins load fine.

-- Both "missing" plugins are present in the craft_plugins table.

-- Site seems to work file except for missing plugins, and related missing twig filter template error:

The filter "truncHTML" does not exist

-- My Development environment is php 5.4.24.
-- Staging is PHP 5.3.3 (where Plugins not loading)

I confirmed that all Craft required PHP extensions are loading on the staging server

-- Craft dev mode enabled.

-- a similar truncate twig filter plugin loads fine.

2014/07/30 00:51:58 [trace] [system.CModule] Loading "plugins" application component
in /var/www/craft.dev/craft/app/etc/web/WebApp.php (594)
in /var/www/craft.dev/craft/app/etc/web/WebApp.php (226)
in /var/www/craft.dev/craft/app/index.php (196)
2014/07/30 00:51:58 [trace] [system.db.CDbCommand] Querying SQL: SELECT `id`, `class`, `version`, `settings`, `installDate`
FROM `craft_plugins`
WHERE enabled=1
in /var/www/craft.dev/craft/app/services/PluginsService.php (101)
in /var/www/craft.dev/craft/app/etc/web/WebApp.php (226)
in /var/www/craft.dev/craft/app/index.php (196)
2014/07/30 00:51:58 [profile] [system.db.CDbCommand.query] begin:system.db.CDbCommand.query(SELECT `id`, `class`, `version`, `settings`, `installDate`
FROM `craft_plugins`
WHERE enabled=1)
2014/07/30 00:51:58 [profile] [system.db.CDbCommand.query] end:system.db.CDbCommand.query(SELECT `id`, `class`, `version`, `settings`, `installDate`
FROM `craft_plugins`
WHERE enabled=1)
2014/07/30 00:51:58 [trace] [system.CModule] Loading "messages" application component
in /var/www/craft.dev/craft/app/etc/web/WebApp.php (594)
in /var/www/craft.dev/craft/app/Craft.php (402)
in /var/www/craft.dev/craft/plugins/truncate/TruncatePlugin.php (13)
2014/07/30 00:51:58 [trace] [system.CModule] Loading "i18n" application component
in /var/www/craft.dev/craft/app/etc/web/WebApp.php (594)
in /var/www/craft.dev/craft/app/etc/web/WebApp.php (826)
in /var/www/craft.dev/craft/app/etc/web/WebApp.php (293)

-- I can include a stack trace detailing the twig "missing filter" error resulting from missing twig filter plugin, but I don't think this helps explain the missing plugin.

Any Ideas?  Thanks!!


texts: Missing "Plugin Store" navigation on Craft 3 admin section

texts:
I am a newbie to CraftCMS and just installed my very first Craft Project on local Xampp. Everything looks good except the "Plugin Store" navigation menu is not showing up. Is there any trick or tweak to appear the default menu?

Thanks in advance!

Here's the screenshot


texts: How can I add programmatically a Tag after SAVE_ON event in case of Assets types

texts:
We have to update the Asset after the SAVE_ON event, and the

Craft::$app->elements->saveElement($asset);

Not seems to be working (it is getting timed out). So what is the best pratice to update the Asset after the save, which event should we use for example auto-tagging?

If we are trying to save the entry, it is working like charm, maybe we should query the asset parent first?

Update some additional findings:
It's turned out it is not so easy to re-save the assets after the SAVE_ON. We need to add additional parameters - based on the class rules:

$rules[] = [['newLocation'], 'required', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_FILEOPS]];
$rules[] = [['tempFilePath'], 'required', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_REPLACE]];

Obviously the goal is to just add some tags/category to the image (eg: getting back the tags data from cloudanary auto tagging interface via the filesystem, so we are not able to use the before save event).
So if we are simply trying to save the $asset it is not going to work, because we do not have newLocation either the tempFilePath is old as well. Instead we have to change the scenario, and save the asset after that (the idea was coming after checking the ElementController)

$element->setScenario(Element::SCENARIO_LIVE);
$element->setFieldValue('fieldHandle', $ids);
Craft::$app->getElements()->saveElement($element);

I do not have better idea for Asset save (specially because the asset itself was saved, and only the fields has to be updated), but this solution is working like charm, and the same logic is applied on the CP. If only the fields are getting updated the ElementController is getting called otherwise the AssetController. Hopes it helps for future reference


texts: End user sign in and/or registration template example

texts:
I'd like to create a template that lets visitors either a) register a new account or b) sign in to an existing account.

There's a sample public registration form here: http://buildwithcraft.com/docs/templating/user-registration-form.

However, I can't find any examples of how to enable a visitor with an existing account to sign into it.

Sorry if I'm missing an obvious link somewhere.

How do you do this? Thanks!


texts: Create folder in asset volume via GraphQL

texts:
Is it possible to create a subfolder within an asset volume via GraphQL? If yes, can you point me in the right direction?
I just found mutations for file uploading, but nothing for folder creation.
Thanks!


texts: Search not searching certain words - how to fix?

texts:
I have an entry about the U.K. TV show "Being Human". If I search "being" on the back end, it comes up with 0 results, same on the front end search.
Searching for "Human" brings it up, but "Being Human" does not.
Doe the default "title" field not get indexed by search? How can I enable it if so?


texts: Video frame for video file in a Rich Text field

texts:
I am adding a video in a Rich Text field through file button in toolbar. I want to play these video in iframe. How can I do this..?

Or is there anyother option or plugin by which I can upload video which and add in richtext filed anywhere I want and show this in iframe on frontend.


texts: Unit Testing with current version of Craft

texts:
Has Craft stopped shipping with unit tests? I'm trying to unit test a plugin and have noticed from several previous answers (e.g PHPUnit testing for Craft plugins or controllers) that it was possible at some stage using Craft's local tests. Have these since been removed? There no longer seems to be a tests folder inside the latest download of Craft/app.

What is the current best practice for setting up Unit Tests using Craft 2 in a plugin?


texts: How to include search results where keyword input exists only as a category title?

texts:
I have a request to extend an existing "advanced search" form (multiple fields, including keyword and a categories dropdown) so that entries with a category that matches the keyword input are returned.

For example, let's say my entries are all book authors, and among various entry fields like their bio and their published books, there's also a Topic category, and authors may be associated with 0-n categories.

And let's say I have an author Jane Smith, and one of her selected Topic categories is Poetry, but for some reason the word "poetry" does not exist in her bio or any of her book titles or for that matter anywhere at all in her main entry, but rather only as that category selection.

How would I modify my search so that anyone typing "poetry" into the keyword search field (rather than picking it from the Topics dropdown menu field) will get back Jane Smith as one of their results?

Still pretty new to Craft, but I feel like there has to be some way. If not via clever query construction on the results template, then maybe by some kind of way to automatically replicate the text of the author's topic categories into an entry field that's never displayed to users, just only exists to get that text into a place where it's picked up by the search index? Would be grateful for any thoughts. Thanks.

Existing search (this is followed by a bunch more Twig that merges these results with results of other entry types but I don't know that any of that is relevant here):

{% set profileParams = {
    section: 'profiles',
    search: {
        query: 'title:' ~ query ~ ' OR ' ~
                     'position:' ~ query ~ ' OR ' ~
                     'jobTitle:' ~ query ~ ' OR ' ~
                     'institution:' ~ query,
        subLeft: true,
        subRight: true
    },
    order: 'score',
    limit: null
} %}

[...]

{% set profileEntries = craft.entries( profileParams ) %}


texts: Multi sites: should I use Craft 2 locales, or go with Craft 3 alpha?

texts:
I have a couple of imminent projects that will need some type of multi-site support. One is a large project that will need to share data between at least 3 sites. Where data is entered in one site and displayed on all. I've setup many sites in EE with MSM so I'm familiar with that method but never done this with Craft. I have read a few articles about how to set this up using the local function and modifying core files. I've also read about how this will be built into Craft 3.

So my question is - what route would any of you recommend taking? If I use the locale method will that the work be invalidated when Craft 3 comes out? Or is it advisable to go with the Craft 3 alpha hoping it's stable enough for production? I'm not sure when it will be released or if plugins will be compatible.


texts: FeedMe Direct Feed Link not showing in CP

texts:
The FeedMe docs state that there is a Direct Feed Link for cron usage. I'm not seeing it. All I see is the Debug, Status and Delete icon. Or is this a PRO feature?

I'using Craft 2.6.x and FeedMee 2.0.6

Cheers,
Martijn


texts: Send email with dedicated SMTP settings from a Craft 2 plugin

texts:
I have looked a lot for this but cannot find any dedicated solution. Basically I want to do this: How to send email from Craft 3 custom plugin? … but for a Craft 2 plugin.

A how-to for the global email settings would be already helpful, but ideally we would like to use not those SMTP settings in the global email settings but dedicated ones for another email address. Can this be done?

Thanks!

edit August 8th: no ideas? Any help is welcome!


texts: Ajax front-end user registration form - not returning JSON

texts:
I have a user registration form on the front-end of a site that is working well as a standard form, but when I try to use ajax submission, I'm getting an HTML response rather than JSON.

Here's the javascript I'm using

$('#register-form').submit(function(ev) {
    ev.preventDefault();

    var data = $(this).serialize();

    $.post('/', data, function(response) {

        console.log(response);

        if (response.success) {
            alert("success")
        } else {
            alert(response.error);
        }
    });
});

And this is my form code:

<form method="post" action="" id="register-form" accept-charset="UTF-8">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="users/saveUser">

Create An Account

By creating an account, you will be able to save your application progress. This is an optional step.

    Email
    <input type="text" class="form-control" id="email" name="email" {%- if account is defined %} value="{{ account.email }}"{% endif %}>

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

        Confirm Password
        <input id="password2" class="form-control" type="password" name="password2">

<input type="submit" id="form-submit" value="Register" class="btn btn-grey"/>

Already have an account? Sign In

The response var is returning the entire html page rather than JSON data.

Is there a way to trigger a JSON response for the registration form?

Note, I'm able to use similar code for a front-end login form and it's working well.


texts:
In a follow up to my earlier question, I'm focusing on cleaning up my code to keep it incredibly simple. I've moved on from the Controller and Model to the Model and Service. Typically you would have something like the following in a service method:

$record = new MyRecord();

$record->name           = $model->name;
$record->anotherField   = $model->anotherField;
// etc..

Which works and you end up defining the attributes in _attributes as an array like below:

[*:_attributes] => array
    (
        'uid' => '0'
        'name' => 'My Name'
        'anotherField' => 'Another Field'
    )

The logic that I am looking for, which I'm sure someone will tell me I am just using the wrong method, can be seen in the controller.

public function actionSave()
    {
        // require a post request
        $this->requirePostRequest();

        // assign the fields from post request
        $post = craft()->request->getPost('fields');

        // create a model, populate with the assigned fields
        $model = MyModel::populateModel($post);

        // validate attributes
        if ($model->validate()) {

            // save the record
            craft()->myPlugin->saveNew($model);

            // redirect to posted url
            $this->redirectToPostedUrl();
        }

        // grab errors from the model
        $errors = $model->getErrors();

        // return errors to the template as 'errors'
        craft()->urlManager->setRouteVariables(array(
            'errors'    => $errors
        ));
    }

In the controller code, I'm populating the model with the post with this line:

`$model = MyModel::populateModel($post);`

Is there a way to create the same behavior for the method in the service to "automagically" assign the model attributes to the $record?


texts:
The question was already asked (Possible to redirect elsewhere after saving an entry?) but this was about Craft 2.x.

Up until now I used the following code in my plugin (I took it from one of the comments from the same question):

Craft::$app->getView()->hook('cp.entries.edit', function (array &$context) {
    if (isset ($context['section']['type']) && $context['section']['type'] === 'single')
    {
        Craft::$app->getView()->registerJs("
            $(function () {
                $('input[name=\"redirect\"]').val('/');
            });
        ");
    }
});

The code did the job, but after I updated to 3.1.32.1, it stopped working, every time after entry was saved the following exception was thrown:

  HTTP 400 – Bad Request – yii\web\BadRequestHttpException
  Request contained an invalid body param

Stacktrace:

yii\web\BadRequestHttpException: Request contained an invalid body param in .../vendor/craftcms/cms/src/web/Request.php:651
Stack trace:
#0 .../vendor/craftcms/cms/src/web/Controller.php(314): craft\web\Request->getValidatedBodyParam('redirect')
#1 .../vendor/craftcms/cms/src/controllers/EntriesController.php(595): craft\web\Controller->redirectToPostedUrl(Object(craft\elements\Entry))
#2 [internal function]: craft\controllers\EntriesController->actionSaveEntry()
#3 .../vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#4 .../vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#5 .../vendor/craftcms/cms/src/web/Controller.php(109): yii\base\Controller->runAction('save-entry', Array)
#6 .../vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('save-entry', Array)
#7 .../vendor/craftcms/cms/src/web/Application.php(297): yii\base\Module->runAction('entries/save-en...', Array)
#8 .../vendor/craftcms/cms/src/web/Application.php(565): craft\web\Application->runAction('entries/save-en...', Array)
#9 .../vendor/craftcms/cms/src/web/Application.php(281): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#10 .../vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#11 .../web/index.php(21): yii\base\Application->run()
#12 {main}

Is there any chance to make it work again on 3.1.32?


texts: Set multiple entries from different categories merge or join?

texts:
So I'm using cookies to determine what entries I want to display on some specific pages. I have a lot of different cookies which will change which entries I should be displaying. I currently have around 12 different cookies so would end up with over a thoasad different possiblities. Here is an example if a person has a both the below cookies, they should see entries from all of the below sets so I would need to either merge or join these if that specific cookie was found and the entries for that match were set.

{% if getCookie('cookie1') %}
{% set cookie1Entries = craft.categories.group('resource').slug('slug1') %}
{% set cookie1Entries2 = craft.categories.group('resource').slug('slug2') %}
{% set cookie1Entries3 = craft.categories.group('resource').slug('slug3') %}

{% set entriescookie1 = craft.entries({
    group: 'resource',
    relatedTo: [
        'and',
        { targetElement: cookie1Entries },
        { targetElement: cookie1Entries2 },
        { targetElement: cookie1Entries3 }
    ]
}).limit(3).find() %}
{% endif %}

{% if getCookie('cookie2') %}
{% set cookie2Entries = craft.categories.group('resource').slug('slug4') %}
{% set cookie2Entries2 = craft.categories.group('resource').slug('slug5') %}
{% set cookie2Entries3 = craft.categories.group('resource').slug('slug6') %}

{% set entriescookie2 = craft.entries({
    group: 'resource',
    relatedTo: [
        'and',
        { targetElement: cookie2Entries },
        { targetElement: cookie2Entries2 },
        { targetElement: cookie2Entries3 }
    ]
}).limit(3).find() %}
{% endif %}

What would be the best way to merge all of these at the end of checking for cookies, and also prevent from showing duplicate entries? Not sure how I would go about joining or merging these entries, as I would need to check if entriescookie1 or entriescookie2 was also set.


texts:
Despite setting baseUrl alias with trailing slash it appears it gets stripped off in Craft 3.

CRAFTENV_BASE_URL="https://domain.test/"

  'aliases' => [
      '@siteUrl' => getenv('CRAFTENV_SITE_URL'),
      '@baseUrl' => getenv('CRAFTENV_BASE_URL'),
      '@basePath'   => getenv('CRAFTENV_BASE_PATH')
    ],

template

 {% set baseUrl = alias('@baseUrl') %}

which renders

https://domain.test

and breaks my craft 2 template links to stylesheets etc.

I can fix with

 {% set baseUrl = alias('@baseUrl') ~ '/' %}

but can't help but think trailing slash was compulsory in Craft 2.


texts: Group entries by category than by month based on Date/Time field

texts:
I would like group entries first by what category they are in, than group by month based on a Date/Time field like this for example:

Category 1

February 2017

Event 1

March 2017

Event 4 (in all categories)

Category 2

February 2017

Event 2
Event 5

March 2017

Event 4 (in all categories)

Category 3

March 2017

Event 4 (in all categories)

Here is what I'm currently using:

{% set eventCategories = craft.categories.group('events').find() %}
{% set eventEntries = craft.entries.section('event').order('dayStart asc').limit(null) %}
{% for category in eventCategories %}

{{ category.title }}

        {% for eventDate, entries in eventEntries | group("dayStart|date('F Y')") %}

{{ eventDate }}

                {% for entry in eventEntries.relatedTo(category).find() %}

{{ entry.title }}

                {% endfor %}

        {% endfor %}
{% endfor %}

Instead the output I'm getting is this:

Category 1

February 2017

Event 1
Event 4 (in all categories)

March 2017

Event 1
Event 4 (in all categories)

Category 2

February 2017

Event 2
Event 5
Event 4 (in all categories)

March 2017

Event 2
Event 5
Event 4 (in all categories)

Category 3

February 2017

Event 4 (in all categories)

March 2017

Event 4 (in all categories)

Is there a way to stop the duplicates?

Thanks in advance.


texts:
I want to archive users from a plugin, but can't seem to find the appropriate method to do so (not even in the control panel). I can suspend, delete, but not archive.

Any ideas?


texts: Getting back after forwarding to another controller function

texts:
I want to assign a new user to a user group using a variable passed in the frontend registration form. I was going to listen for the OnSaveUser event but I don't think there's a way to get the usergroup from the original post that way(?) so I've instead created a controller that forwards to users/onSaveUser using:

$forward = $this->forward('users/saveUser', false);

The idea being I'll then have access to the post after the user has been created. The problem is everything ends here and doesn't reach the rest of my function. Here's my controller:

<?php
namespace Craft;

class UserGroupController extends BaseController
{

    protected $allowAnonymous = true;

    public function actionSaveUser()
    {
        $this->requirePostRequest();

        $forward = $this->forward('users/saveUser', false);
        throw new Exception('Made It back!'); // never reached
        return TRUE;
    }

}

According to the Yii docs, false should stop the things ending, right?


texts:
I'm beginning with Craft/Twig and am developing a plugin that gets data from a Restful XML feed, and I've successfully tested it on my template.

Below, I have the working plugin code and a sample of the XML structure.  The actual data feed will return anywhere from a few to several hundred 'INTELLCONT' nodes per user ('Record').

In order to improve readability, is it possible to paginate this feed data?  Would I implement it from the plugin (php) side or rather the (twig) template side?

Here is the code I have so far:

Twig template:

{% extends "_layout" %}

{% block content %}

test

    {% set name_var = 'john-smith' %}
        {{ craft.aifeed.XmlVariable(name_var) }}
{% endblock %}

PHP Code (plugin):

<?php
namespace Craft;

    class AiFeedVariable
    {
            public function XmlVariable($optional = null)
        {
    $url = "test_bb.xml";

    $xml = simplexml_load_file($url);

    $xml->registerXPathNamespace('a','http://www.digitalmeasures.com/schema/data');//
    $xml->registerXPathNamespace('dmd','http://www.digitalmeasures.com/schema/data-metadata');

    $secondary_user_id = $optional;
    $xml_report_abbrev_bb = $xml->xpath('//a:Record[@username="'.$secondary_user_id.'"]');

    if($xml_report_abbrev_bb){
        echo '
CONTYPE is...'.$xml_report_abbrev_bb[0]->INTELLCONT->CONTYPE;
        echo '
termId is...'.$xml_report_abbrev_bb[0]['termId'].'
';
        echo '
surveyId is...'.$xml_report_abbrev_bb[0]->attributes('dmd',true)['surveyId'].'
';

        $dmd_fields = $xml_report_abbrev_bb[0]->children('dmd',true);

        echo '
dmd:IndexEntry is...'.$dmd_fields[0]->attributes()['indexKey'].'
';

    } else {
        echo 'XPath query failed b';
    }

     }
    }

    ?>

The XML file (test_bb.xml)

<?xml version="1.0" encoding="UTF-8"?>
<Data xmlns="http://www.digitalmeasures.com/schema/data" xmlns:dmd="http://www.digitalmeasures.com/schema/data-metadata" dmd:date="2012-01-03">
    <Record userId="148" username="john-smith" termId="4" dmd:surveyId="12">
        <dmd:IndexEntry indexKey="D" entryKey="Dylan" text="Dylan"/>
        <INTELLCONT id="14" dmd:originalSource="54TEX" dmd:lastModified="2017-04-18T10:54:29" dmd:startDate="2011-01-01" dmd:endDate="2011-12-31">
            <CONTYPE>Sales Tools</CONTYPE>
            <CONTYPEOTHER>Sales History</CONTYPEOTHER>
        </INTELLCONT>
    </Record>
</Data>


texts: Ge tTags from the list of displayed entries #GraphQL

texts:
query QueryEntries($section: [String]) {
  entries(section: $section) {
    id
  }
}

Result
 {   "data": {
     "entries": [
       {
          "id": "369"
       },
       {
         "id": "278"
       },
       {
         "id": "263"
       },
       {
         "id": "244"
       },
       {
         "id": "233"
       }
     ]   } }

How to put in QueryTags (variable Entries)?
 {% set query %}
  query QueryTags($EntriesID: [Int]) {
   tags(relatedTo: $EntriesID) {
     id
     title
  } }
{% endset %}

{% set Tags= gql(query) %}


texts: Best way to define non-purchasable products?

texts:
Not every item in my store is available to buy online.

What would be the best way to classify these items in Craft Commerce?
(So that the 'Buy' button can be swapped for 'Enquire')

There are multiple product categories this applies to.


texts:
I've been trying to get a quick staging environment setup on GoDaddy all day.

By using die('foo') I can tell that GoDaddy is able to reach all of my files (public/index.php, craft/config/db.php and general.php). I have created two different databases and users to try to connect to. I am also using the hostname's generated by GoDaddy.

However, even with the correct db information and knowing for a fact that Craft is able to find my db.php file, when I browser to mydomain.com/index.php?p=admin/install I'm still receiving the following error:

  Craft can’t connect to the database with the credentials in craft/config/db.php.

db.php

/**
 * Database Configuration
 *
 * All of your system's database configuration settings go in here.
 * You can see a list of the default settings in craft/app/etc/config/defaults/db.php
 */

// die('foo');

return array(

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

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

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

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

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

);


texts: cannot update Craft CMS - composer errors

texts:
I'm upgrading a site to 3.0.41.1 (not ready to go to 3.1) and when I do I get the following error. How do I resolve this?

composer update craftcms/cms
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: twig/twig[v2.6.2, v2.5.0].
    - Can only install one of: twig/twig[v2.6.2, v2.5.0].
    - Can only install one of: twig/twig[v2.6.2, v2.5.0].
    - craftcms/cms 3.0.41.1 requires twig/twig ~2.6.2 -> satisfiable by twig/twig[v2.6.2].
    - Installation request for craftcms/cms 3.0.41.1 -> satisfiable by craftcms/cms[3.0.41.1].
    - Installation request for twig/twig (locked at v2.5.0) -> satisfiable by twig/twig[v2.5.0].

in composer.json I have this

"craftcms/cms": "3.0.41.1",

All other plugins were successfully updated.


texts: How to pull entries with Date Created > start and < end?

texts:
I'm building an export plugin in Craft 2 and the entries are saved by the front-end and are never enabled, so no Post Date.  I have a form with the forms.date selectors that sends a start and end date to my controller.  How can I filter on Date Created?  After and before only works on Post Date.

I have this for now:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'contestEntries';
// Date Created >= start_date
// Date Created <= end_date
$criteria->status = null;
$entries = $criteria->find();

Thank you


texts:
OK, I have encountered the following issue:

Issue:
 Admin page gets a Craft 404 page error; home page loads fine though.

Home page: 192.168.10.95

Admin page: http://192.168.10.95/public/index.php/admin/dashboard

Clearly Craft is working, though I am not sure what is causing this to break for me. Any suggestions?  I can provide any information you may want to see, just let me know.

Thank you Craft friends!

Edit 03/14/2017 @08:24 PST

Here is the contents of my /etc/apache2/sites-availavble/000-default.conf file:

<VirtualHost *:80>

ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/public

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

I have pointed my DocumentRoot to /var/www/html/public, though did I miss something in my configuration?

Thanks again Craft friends!


texts: Internal Server Error when adding new Fields

texts:
I was adding new fields to my Craft 3 install using the field manager plugin. Suddenly I am seeing a Internal Server Error when trying to access the admin area.

The front end looks fine. Anyone know how I can quickly resolve?

In web.log I get

Setting unknown property: craft\behaviors\ContentBehavior::announcementLink in /home/forge/www.uk-cpi.com/vendor/yiisoft/yii2/base/BaseObject.php:163

In phperrors.log I get

An Error occurred while handling another error:
yii\base\UnknownPropertyException: Setting unknown property: craft\behaviors\ContentBehavior::announcementLink in /home/forge/www.uk-cpi.com/vendor/yiisoft/yii2/base/BaseObject.php:163

announcementLink is the name of the field I was adding


texts:
Is it possible to hide the preview shown by default when Matrix blocks are collapsed?

  You can collapse Matrix blocks by clicking the “Collapse” menu option,
  or by double-clicking on a block’s title bar. When a block is
  collapsed, its title bar will show a preview of its content, so you
  can still identify which block it is.

It's useful to just be able to see the content outline made up by block types clear and simple. A lot of the time in my case the preview is irrelevant so it would be great to turn this off across the board by default.


texts:
I want to display the current title of the parent structure inside the child template.

How would I do that?

Parent (Title: Bla)

Child (Here I want to display Bla)

Parent (Title: Blablu)

Child (Here I want to display Blablu)

I tried something like (in the child template):

{% set parentTitle = craft.entries.section('structure').level(1).title %}
<h1>{{ parentTitle }}</h1>

But that doesn't even result in an error


texts:
I need to get the currentSite in Element API. How can this be achieved? Is it as a slug in the endpoint URL? or as a Query param? Here is the current code:
<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;
use craft\services\Sites;

return [
    'defaults' => [
        'resourceKey' => 'suggestions',
        'cache' => false,
        'paginate' => false,
        'pretty' => true,
    ],
    'endpoints' => [
        'api/search.json' => function() {

        $searchQuery = Craft::$app->request->getQueryParam('query');
        $site = Craft::$app->request->getQueryParam('site');

        $sectionHandles = [
            'pages',
            'news',
        ];

        // Search criterias
        $criteria = [
            'section' => $sectionHandles,
            'search' => $searchQuery,
            'site' => $site,
            'orderBy' => 'score',
            'limit' => 10,
        ];

            return [
                'elementType' => Entry::class,
                'criteria' => $criteria,
                'paginate' => false,

            'transformer' => function(craft\elements\Entry $entry) {

                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                ];
            },

            ];
        },
    ]
];


texts:
I have a pop up box on a siteplan image that includes a select dropdown to let people select the apartment that they want. However, I can't get the it to go to the url when it's selected. So need some help please.

Currently when you select Plot 18 from the dropdown options it goes to:

websitename/developments/surrey/knowle-hill-park?sitemap=%2Fplot-18

however it needs to go to:

websitename/developments/surrey/knowle-hill-park/available-homes/plot-18

Can someone help show what i'm doing wrong in the form below:

<form action="{{ category.url }}">

      <select id="sitemap" class="form-control" name="sitemap" onchange="this.form.submit()">
        <option value="">Select Plot No</option>
          {% for entry in craft.entries.section('availablehomes').relatedTo(category).level(2).order('plotPrice desc') %}
          {% if entry.plotType == 'apartment' %}
          <option value="/{{ entry.slug }}">{{ entry.title }} - {{ entry.floor.label }} - {% if entry.plotAvailability == 'available' %}{{ entry.plotPrice|currency('GBP', true) }}{% else %}{{ entry.plotAvailability.label }}{% endif %}</option>
          {% endif %}
          {% endfor %}
        </select>

  </form>


texts: Can you change the URL for Assets uploaded to a Rackspace CDN?

texts:
Assuming that you're using Craft Pro, is it possible to change the URL from the long randomly generated character string to something more user friendly?

Currently: http://83af0ee9e3c8cba9844f-a33048c0ede2332addff32deec6d7158.r40.cf3.rackcdn.com/subFolder/randomImage.png


texts: Templating - Get a string of the entry's field handle

texts:
I'm passing entry fields into a macro and I'd like to be able to get a string of the field handle

myMacro(entry.field1)
myMacro(entry.field2)

{% macro myMacro(entry) %}
  {# I want a string of 'field1' here #}
{% endmacro %}


texts: Element-API: Access the first url of an asset array

texts:
I have an asset field in my current project with the handle postImage, containing multiple image files. In my element-api endpoint, I wish to access the url of the first file only.

I tried the following code:

$imgs = $entry->postImage;
$imgUrl = $imgs[0]->getUrl();

The resulting console error message says:

500 (Call to a member function getUrl() on string)

Looping through the array works fine, but I don't want all image urls, just the first one.

It's probably very easy, but that ties a knot my brain. I don't understand where the array is being converted to a string, can anyone hint me to the solution?

Thanks a lot!


texts: I am building a plugin in Craft, I want to use the Element Types, the documentation seems so hard to grasp. Can you give an example or a template code?


texts: How do I set mime-types for Craft templates?

texts:
For example, if I'd like to serve a file as application/json or application/rss+xml

I see in the RSS Feed documentation that it mentions saving a file with .rss will auto-detect and serve the correct mime-type.

However, how is this detected? Is there a set list that the CMS uses based on the extension or is it derived from the server in some way?


texts: How do I set a specific entry in a template with "set"

texts:
This won't work in a template:

{% set entry = craft.entries.id(43) %}
Titel: {{ entry.title }}

But this does:

{% for entry in craft.entries.id(43) %}
Titel: {{ entry.title }}
{% endfor %}

Is it really necessary to use the for loop? I tried to use set because I'd like to over rule the entry variable for the whole template that I'm using if a specific url is visited

{% if craft.request.segment(2)=="openings-en-trainingstijden" %} {% set entry = craft.entries.id(43) %}{% endif %} {{ entry.title }} etc..

Another example this code:

{% for entry1 in craft.entries.id(43) %}Titel: {{ entry1.title }}{% endfor %}
{% set entry2 = craft.entries.id(43) %}Titel: {{ entry2.title }}

Results in:

Titel: Openings- en trainingstijden
Titel:


texts: I'm after using a date-time field within a table cell. I suspect it requires a plugin to make this happen - has anyone done this?


texts: Whats the best way to place content without using a lot of categories?

texts:
I have a technologies magazine and recently find out about Craft CMS. It looks like I can make everything that I need to but I need advice.
So basically we are writing about smartphones, cars, computers, games and etc. All of these I can put as categories but different posts also have different sub-categories. We split our content into three sub-categories: news, tips, reviews. That means that all the categories (like smartphones, cars and etc.) have the same sub-categories (news, tips, reviews).
I'm looking for the best option for sorting all our content in Craft CMS. I was thinking to use entry types but we also want to have separate archives where people can find only smartphones news or smartphones tips. At the same time, we want to have the archive with all the tips.
The idea is to have a structure like this:
Home -> device type -> post type -> article
Url structure should be with all these components included and all of them should have the archive. I was thinking to use categories for device type and entries type for post type but it gets a bit messy. Does anyone have better ideas on how I can make this thing working for me? Thanks!


texts: Eager load Imager transforms in Craft Commerce

texts:
I am using Imager to create my image transforms. I am on a category page and I want to list all of the products.

I did a quick .with(['cf_shop_assets']) optimization and wanted to continue with the image transforms.

Frankly, I don't know where to start?

{% set products = craft.commerce.products.relatedTo(category).with(['cf_shop_assets']) %}
{% if products|length %}

        {% for product in products %}

        {% set variants = product.variants %}
        {% set variant = product.defaultVariant %}

                    {% set image = product.cf_shop_assets[0] ?? null %}
                    {% if image|length %}
                        {% set transformedImage = craft.imager.transformImage(image, {
                            width: 300,
                            quality: 90,
                            format: 'jpg',
                            bgColor: '#EFEFDE',
                            effects: { sharpen: true }
                        }) %}

                    {% endif %}

{{ product.title }}

            […]

        {% endfor %}

{% endif %}

The code works, but it only saves about 5 queries.

Would somebody be so kind to show me how to eager load Imager transforms?

I need Imager because I don't want to use transparent PNGs. There's no native way to transform a PNG to JPG and adding a background color.

Is this even possible?


texts: I'm trying to streamline my deployments for local, staging and production and would like to know if it's possible to invoke the Find and Replace method via Console. I have a multi-config in place, but I'd like to ensure that any hardcoded urls are replaced in the database.


texts: Grouping entries and ordering by section

texts:
Im grabbing entries from two sections and displaying them using the group filter.

{% set entries = craft.entries().section('extendedEvents, festivalEvents')%}
{% set allEvents = entries %}
{% set allEventsBySection = allEvents|group('section') %}

{% for section, eventsInSection in allEventsBySection %}
- results-
{% endfor %}

No matter what I do the results are coming back ordered as section2 (entry, entry, entry) then section 1 (entry, entry, entry)

How do I affect the order of the sections when displaying the results?


texts: I was able to save cards by using savePaymentSource parameter in my payment form submitting at commerce/payments/pay. But how do I use these saved cards for making payments? I am using Stripe payment method and rendering the form through {{ cart.gateway.getPaymentFormHtml({})|raw }}.


texts: How can I repopulate a matrix field on a front-end form?

texts:
I have a matrix field on my front-end form. Everything is working properly, data is saved correctly etc.

I am testing & trying to break things and I noticed I wasn't repopulating those fields if validation failed.

Here is how I am attempting to repopulate the value(s) in my front-end form:

<input type="hidden" name="fields[myMatrixFieldHandle][new1][type]" value="blockType">
<input type="hidden" name="fields[myMatrixFieldHandle][new1][enabled]" value="1">

...
value="{{ entry.myMatrixFieldHandle.blockType.fieldHandle }}"
...

When I dump the above, I am getting the whole object back. I'm not sure how to get to the actual field's value.


texts: Is there a way to see a fields variant relation in templates?

texts:
To clarify; if I have a disabled variant, and I'm looping through categories (colors) on each product like {% for variantColor in variantColors  %}...{% endfor %} which makes it still show up in the list of colors.

Is there a way to, in that for loop, check if the variant it's connected to is enabled/disabled and then disregard, similar to {% for variant in variants if variant.enabled %}?


texts: Performance issues in CP with +60k articles database

texts:
We are are working with a large dataset of over 60k articles. The craft control panel has a very hard time loading the entries list tables. Using debug I see that the queries that takes up the longest (+10s) is the one that starts likes this "SELECT sourceId AS source, targetId AS target" . Does anyone has any ideas or tips on how we can get around/fix this issue?
This is an image form the debugger on the ajax call loading a list of entries in the contents tab.


texts: Include additional fields in Craft form notification template

texts:
I'm using the Craft Contact Form template.  I need to include some additional content in the notification email.  I can't for the life of me find how to do this.

I've seen this:
P&T Contact Form Plugin: HTML Email Templates

But not sure how to apply the additional fields.  Here is my contact form template (markup removed for ease of reading).

{# form markup #}
    <select class='form__input' name="message[About]">
        {% nav link in craft.entries.section('products') %}
            <option value="{{ link.title }}">{{ link.title }}</option>
        {% endnav %}
        <option value="Services">Services</option>
        <option value="Consultancy">Consultancy</option>
        <option value="General enquiry">General enquiry</option>
    </select>

        Your email address
        <input class='form__input' id='fromEmail' name='fromEmail' type='email' placeholder='Email address' value='{% if message is defined %}{{ message.fromEmail }}{% endif %}'>

        Details
        <textarea class='form__input form__input--textarea' id='message' name='message' placeholder='Tell us more'>{% if message is defined %}{{ message.message }}{% endif %}</textarea>

{# form closing markup/submit button #}

any help, phenomenally appreciated!

Thanks
Dave


texts:
I'm trying to use different entry types for certain categories. My category group is called categories, and the slug for Features is features. I have the category group pointed to categories/_entry. As for as I can tell, I've got it set up right. I think their might just be something wrong with my switch code. This is my code in categories/_entry:

{% set categories = entry.categories.first %}
{% switch categories.slug %}
    {% case 'features' %}
        {% include 'categories/_feature.html' %}
    {% case 'news' %}
        {% include 'categories/_news.html' %}
    {% default %}
        {% include 'categories/_news.html' %}
{% endswitch %}


texts: Any plugins to add drop down for selecting template?

texts:
One of my biggest issues with craft so far is having to type out which template file a section is using, I don't understand why we don't have a location to enter all our possible templates, which could then be chosen when creating sections "new pages" etc. Or having craft know which template files exist.

Could this be possible via a plugin, or would the core need to be modified. Having to explain to a client they need to know the name and location of a template file when creating new pages isn't great.

Updated Scenario:

Simple example, say I have news post, and events, and I want an index of both as well as single news post and single events both using different templates. When a client wants to create a new event, they would need to know the name of the template that is used for single events otherwise it would default to index.html if the auto generated entry-template name doesn't exist.

When creating a new entry craft defaults to a news item or I call it a news "post". So to create a new event, I need to create a new section, and then specify the entry-template otherwise it defaults to the name of the section, and if no template exists for that entry template "which ends up being the name of the section" it defaults to the index.html template. Then they still need to assign fields to each section that is created. The assigning fields can be simplified by creating a group say called Single Events, with all the possible fields allowed for that type of section "page" this case being single events...

The only easy solution I can think of is to not use groups at all for fields, and just throw every field into each section, then in the index.html template check for each field and if it exists before displaying it. But what about not wanting to display it or displaying dynamic content based on the entry type news post vs single event vs team members vs resources vs contact forms. A solution to that is creating another field called content type with a drop down for single event, team member, resources, contact form... then in the index.html template check the value of the drop down before determining what is going to be displayed and what isn't.

My whole point is it seems like this could all be simplified by having a drop down to choose a template when creating a section since a section needs to be created so that you can create a new entry that is not a news post, and I also think once you create a new section it should allow you to either start editing that section, or take you to the field selection to add fields to that section, after you save a section it just takes you back to the sections which you then have to click edit entry types to choose which fields are used for that section.

To me it would make more sense to have fields assigned to templates, and sections are just holders for "entries" or what I call pages. Example basic-page.template has a bunch of fields assigned to it. I create a section called about us, and choose basic-page.template after saving the section allow me to start editing the entry for that "section".

Sorry for the wall of text just trying to give some examples and I hope they make sense. Just trying to understand the concept of some of this, I'm getting by but it seems odd not to allow to choose a template that is used unless you are a dev on the project and know exactly the name of the template.


texts: Trigger off canvas menu upon adding product to cart

texts:
When a user clicks 'Add to Cart', rather than redirecting them to the cart page, I would like to trigger an off-canvas menu that contains the contents of their shopping cart.

I'm using http://git.blivesta.com/drawer for the menu implementation

The menu can be toggled/opened with javascript, but I'm unsure as to how to trigger the opening of the menu when a user clicks 'Add to Cart'.

Ideally, I would like this to be possible, without reloading the page.

Has anyone implemented anything similar?


texts:
Working with the Commerce example templates.
The example template uses javascript to populate the States which is based on the selected Country. The code for the Country and State select field:

Country
<select class="address-country" name="{{ modelName }}[countryId]">
    {% for key, option in countries %}
        {% set optionValue = (model ? model.countryId : '') %}
        <option value="{{ key }}" {% if key == optionValue %} selected{% endif %}>{{ option }}</option>
    {% endfor %}
</select>
{% if model and model.getErrors('countryId') %}

{{ model.getErrors('countryId')|join }}

{% endif %}

State
{% set options = (model and states[model.countryId] is defined ? states[model.countryId] : []) %}
<select id="{{ modelName }}-stateId" data-modelname="{{ modelName }}" class="address-stateId {% if options|length == 0 or (model and model.stateName) %}hidden{% endif %}" name="{{ modelName }}[stateValue]">
    {% for key, option in options %}
        {% set optionValue = (model ? model.stateId : '') %}
        <option value="{{ key }}" {% if key == optionValue %}selected{% endif %}>{{ option }}</option>
    {% endfor %}
</select>
<input type="text" data-modelname="{{ modelName }}" id="{{ modelName }}-stateName" class="address-stateName {% if options|length > 0 or (model and model.stateId) %}hidden{% endif %}" {% if model and model.stateName %}name="{{ modelName }}[stateValue]" value="{{ model.stateName}}"{% endif %}>

All I'm looking for is a drop down for US States no other Countries will be used. I like to keep the 'model' in place though.

The javascript:

{% includejs %}
var states = {{ craft.commerce.statesArray|json_encode|raw }};

$('select.address-country').change(function ()
{
    // get the value of the selected country.
    var cid = $(this).val();
    var $states = $(this).closest('.addressBox').find('select.address-stateId');
    var $stateName = $(this).closest('.addressBox').find('input.address-stateName');
    $states.find('option').remove();

    if (states.hasOwnProperty(cid))
    {
        // We have states for this country, show the states drop down.
        $states.removeClass('hidden');
        $states.attr('name', $states.data('modelname')+'[stateValue]');

        // We have states for this country, hide the stateName input.
        $stateName.removeAttr('name');
        $stateName.addClass('hidden');
        $stateName.val('');

        // Add all states as options to drop down.
        for (var id in states[cid])
        {
            var state = states[cid][id];
            var $option = $('<option/>');
            $option.attr('value', id).text(state);
            $states.append($option);
        }

    }else{
        // hide the states dropdown, since this country has none.
        //$states.addClass('hidden');
        //$states.removeAttr('name');

        // show the stateName
        $stateName.removeClass('hidden');
        $stateName.attr('name', $stateName.data('modelname')+'[stateValue]');
    }

});

$('select').addClass('form-control input-sm');{% endincludejs %}


texts: check if a route segment matches a section entry type

texts:
So i added a route to a template that shows entries by entry types.
the way the template does it is by taking the last segment of the url, and using it as an entry slug for this filter:
craft.entries.type(craft.request.getSegment(3)).relatedTo(category)
So, how can i check if the string in the segment matches any of the entry types in that section, and if not - redirect to 404 page?


texts: Plugin Development (Craft 3): Pass variables with redirection

texts:
I'm building out a Craft 3 plugin and can't see who to pass variables with redirection from a controller.

For example, I have a controller that I want to pass back to the defined redirect value along with a variable, eg:

return $this->redirectToPostedUrl( ['order' => $order ] );

However, trying to access the order variable within my template is returning empty. The order object definitely exists before the redirection as it can be accessed from within my controller.

Any suggestions appreciated - I'm sure am overlooking something quite straightforward!


texts:
Is there any way to send a plaintext email with the "express forms" plugin? Can't seem to find a way to define it, and no information about it in the documentation.

The mail should be in plain text, not HTML formatted. But it has an attachment. Any help very much appreciated!


texts: How cumbersome is the content admin with 6 different languages

texts:
Am considering Craft for multi lingual project that will use 6 languages including Arabic. Just how cumbersome does the admin of content become when localisation and translatable  are required for content types?

I was hoping to find some screen shots and get a basic idea of what it would look like from an administrators point of view.


texts: How to create a category filter for a portfolio site?

texts:
I want to create a category filter similar to this website http://www.mypoorbrain.com/ (just a random website i found with the desired effect). Basically I want the categories to be displayed somewhere (All | Design | Web | Illustration) with the projects below. When a category is clicked, the projects shuffle to display just the projects with that category (not going to a new page).

I've looked through other category questions on here, and can't seem to find exactly how to do it (although I'm still pretty new to Craft, so I might not know what to look for with this).

Here is the code I have for the category loop (the filter)

Note: I have all of the categories I want (except for "All", not sure how to handle that) in the category group "Projects".

{# Create a category query with the 'group' parameter #}
{% set myCategoryQuery = craft.categories()
    .group('projects') %}

{# Fetch the categories #}
{% set categories = myCategoryQuery.all() %}

   {# Display the navigation #}
   {% nav category in categories %}

{{ category.title }}

   {% endnav %}

And here is my current code for the project loop:

{% set projects = craft.entries.section('projects').all() %}
{% for entry in projects %}

      {% set projectImg = entry.featuredImage.one() %}

{{ entry.title }}

 Category

{%endfor%}

So how can I accomplish this?


texts:
I'm getting a nn string when I just click on HTML (code mirror),
is there a bug from redactor ?

I have put in hide function of Redactor these lines of code:

code = code.replace('nn
', "
");
code = code.replace('
n<span', "
<span");
code = code.replace('nn<p', "<p");
code = code.replace('
n
', "");
code = code.replace('

', "");`

Is there another solution?

Thanks in advance.


texts: Log exception to a third party service like Sentry or Rollbar?

texts:
Are their any best practices?

Maybe some way to hook to craft native exception / log handler with a third party implantation so I could track my errors on services like Sentry or Rollbar?


texts: Can I add fields to the User > Account screen?

texts:
Is there any way to add to the fields shown on the 'Account' tab on the user account screen?

I know I can add fields via the layout designer, but these appear as seperate tabs.

I'd like to add "middle name(s)" as a field next to "First Name" and "Last Name" if possible?


texts: Get full file url, avoiding the siteUrl trailing slash

texts:
so I'm using an asset field for an OG Image. I need to get the full url for this and I've yet to find a clean way to do this. I figured I could just combine siteUrl and the asset url but I have a weird issue with a double slash.

<meta property="og:image" content="{{siteUrl}}{{entry.ogImage.first().url}}/>

This does what I expect except it adds a slash at the end of {{siteUrl}} and the beginning of the asset so my url is bad, leaving me with a double slash. Short of some programatical removal of the slash, is there another way to do this? Why does my siteUrl have that trailing slash? is something wrong there?


texts:
Is it possible to output the path to a given section?

I'm using this to define the section model for the contact page (a single):

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

But then, there doesn't seem to be a way to get the url from this model (according to section model page on the Craft website.

It seems this information does exist as on the backend there's a link to the Contact page next to the link to edit the section.

Many thanks.


texts: How can I get the screen size in craft cms? I mean the device width in px, so for example I can get a static map image with the exact size to fit the device screen


texts: Eager load a list of entries, then only the first asset, from the first block type

texts:
I would like to eager load:

A list of entries
Within the entries loop, the first image, from the first of a block type on a matrix field.

Loading the entries like this

{% set entries = craft.entries({
  sectionId: 12,
  with: [
    'pageContent.text:text',
    ['pageContent.images:images', {
      withTransforms: [{
        width: 100,
        height: 100
      }]
    }]
  ]
}) %}

Loading the images:

Currently, I can only seem to load an image like this:

{% for block in entry.pageContent %}
  {% if block.type == 'images' %}
    {% if img is not defined %}
      {% set img = block.images[0] ?? null %}

  {% endif %}
{% endfor %}```

I cannot seems to filter the query to the matrix down like you can when getting a matrix normally, I just receive a bunch of errors, I am trying  something like:

{% set img = entry.content.type('images').first.images[0] ?? null %}

Additionally, it appears I cannot use the loop to save a variable to use outside of it, I presume this is intentional and how eager loading works. If that is the case, would I even benefit from any optimisation on the query at all if it is looping on blocks I do not need? As an example, I would normally do something like

{% set img = entry.content.type('images').first.images.first ?? null %}

Following on from whether this is worth it... I also want to get a text field on this matrix (from the first of a block type again), but, in another position in the template. Does this mean I need to do another loop again to get the data specifically for another field?

Is there a better way to deal with this?

I hope that makes sense, let me know if not I'll do my best to clarify.


texts: How to create entry from external app webhook?

texts:
I want to create an entry in an existing channel via a webhook from zoho crm. It's pretty straightforward. Like many apps, Zoho's webhook allows you to specify destination url, the method (get or post), and what parameters to pass.

Do I need to create a plugin to receive this form post or is there another way?

I'm a plugin newbie, so any links on where to start would be helpful.


texts: Question: I am at early stages of setting up Craft.  I plan on installing on Apache & IIS to compare.  Anything I should be thinking about as I do this? Reasons one platform is better or worse than the other? Thanks!


texts: Is it possible to separate variant options on a front end add to cart form?

texts:
Is it possible to have separate variant option fields on a front end add to cart form?

For example… have a separate select field for Color and a separate select field for Size?


texts:
For news entries I want both URL's www.example.com/news/678 (where 678 stands for the entry id) and www.example.com/news/some-slug to load the same entry.

www.example.com/news/some-slug works fine because 'Entry URL Format' is used for this so the news entry contains a readable slug for SEO.

Is there a way to generate www.example.com/news/678 (with entry id) for the same entry, to display the same news entry? Is it possible to handle this with Dynamic Routing? Or generate multiple URL Formats?


texts: Searching for entries across multiple fields including a relationship

texts:
I'm trying to fetch a set of entries based on search parameters. The search is an "and" search, meaning that if criteria exist then they should all match for there to be a result returned.

I have managed to get this working with all the criteria except for one which needs to match a relationship.

My code below shows what I have so far. The relationship field is named "category" (although this actually relates to an entry in another channel).

{% set cat = craft.request.getParam('category') ? craft.request.getParam('category') : '' %}
{% set start_date = craft.request.getParam('start_date') ? craft.request.getParam('start_date') : 0 %}
{% set wage_from = craft.request.getParam('wage_from') ? craft.request.getParam('wage_from') : 0 %}
{% set wage_to = craft.request.getParam('wage_to') ? craft.request.getParam('wage_to') : 9999 %}
{% set location = craft.request.getParam('location') ? craft.request.getParam('location') : '' %}

{% set results = craft.entries({
    section: 'vacancies',
    order: 'score',
    relatedTo: [
          'and',
          { targetElement: cat },
          { field: 'category' }
      ],
    location: [
          'and',
          '= ' ~ location
      ],
    wage: [
          'and',
          '>= ' ~ wage_from,
          '<= ' ~ wage_to,
      ],
      startDate: [
        'and',
        '>= ' ~ start_date
      ]
  }) %}

It all seems to work until I add in the relationship. I know I'm not formatting this part of the query correctly but cannot work out how it should be formatted.

Basically, I am searching the channel "vacancies". The "category" field is a relationship with an entry in a channel named "apprenticeshipsCategories".

How do I do this?


texts: Structure Navigation - Not returning sub nav entries

texts:
I'm trying to set up a sub nav from a Structure Section on my site.

Current code is:

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

{{ subnav.total() }}

But my when loop through sub nav below it returns nothing.
I am outputting subnav.total above but it is returning 0, but there is a lot of entries  in the CMS.

mainEntry gets loaded with the correct info ok, but I don't get anything in subnav.


texts:
I have read through the docs and I am not sure if what I need to do is possible with array sets. I have filtered my entries using the following code"

{% set allDatabytes = craft.entries.section('databytes').limit(null) %}
{% set seriesCollection = [] %}

{% for databyte in allDatabytes %}

  {# get only the series databytes #}
  {% set series = databyte.series %}

  {# add the series databytes to the series collection #}
  {% for entry in series %}
    {% set seriesCollection = seriesCollection|merge([entry.title]) %}
  {% endfor %}

{% endfor %}

{# Output the filtered results #}

{% set filteredDatabytes = allDatabytes|without(seriesCollection) %}

  {% for entry in filteredDatabytes %}

{{ entry.title }}

  {% endfor %}

What I now need to do is add pagination to the filteredDatabytes set of content.

From The Example Below

This is my code which currently doesn't display any results. I guess you add the limit to the MyCriteria model (is that the correct term)?

{% set MyCriteria = craft.entries.section('databytes').series(':empty:').limit(10) %}

{% paginate MyCriteria as entries %}
    {% for entry in entries %}
        {{ entry.title }}
    {% endfor %}

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

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


texts: Execution timeout problem when trying to add new field

texts:
I've been having some problems since I've updated yesterday to craftcms v3.4 (was 3.3). When I try to add a new field via the admin, it takes an enormous amount of time (almost 5min, had to raise the nginx timeout and php execution timeout) on my local dev setup.
Amount of fields I have are pretty minimal for now.
I'm running following craft plugins:

"aelvan/imager": "^2.3",
"barrelstrength/sprout-fields": "^3.5",
"clubstudioltd/craft-asset-rev": "^6.0",
"craftcms/cms": "^3.0.0",
"craftcms/redactor": "^2.4",
"mikestecker/craft-videoembedder": "^1.1",
"sebastianlenz/linkfield": "^1.0",
"verbb/navigation": "^1.2",
"verbb/super-table": "^2.3",
"vlucas/phpdotenv": "^3.4.0"

Does anyone have an idea what the problem could be? Doesn't feel very manageable at the moment.

Thanks in advance.


texts: Plugin init function executed more than once

texts:
To test a service method, I'm executing it in my init function. The method adds a row to the database table with a mail address and variant id:

$this->waitingListService->add(7, 'email@mailserver.com');

However, when I refresh a page in the control page to execute the plugin init function 2, or sometimes 3 rows are being added to the database table.

Is this the default behaviour and if not, how can I fix it?

Thanks in advance,
Sam


texts:
I create a new filed type and attached it to entries. Now I need to get the entry id which the field is attached to.

I tried $this->element in my field class, but got an error said that I'm calling an unknown property.

Any way to do that please?


texts: loop through responsive images in matrix with imager plugin

texts:
I have a content block in a matrix field where I'm trying to output a loop of three sub images.

I can get it to work using the following code:

{% case "secondaryImage" %}

    {% set image = block.image.first() %}
    {% if image | length %}

    {% for image in block.image %}

    {% endfor %}

    {% endif %}

However, I want to output responsive sizes and like to use the Imager-Craft plugin with the Craft-FocusPoint plugin for this on my other images which works really well. But, I'm running into an issue whereby it's only outputting the first image three times with the following code:

{% case "secondaryImage" %}

    {% set image = block.image.first() %}
    {% set transformedImages = craft.imager.transformImage(image,
      [
          { width: 1440, ratio: 6/4 },
          { width: 1024, ratio: 6/4 },
          { width: 750, ratio: 4/3, jpegQuality: 60 },
      ],
      {
          format: 'jpg',
          allowUpscale: false,
          mode: 'crop',
          jpegQuality: 100,
          position: image.focusPctX ~ '% ' ~ image.focusPctY ~ '%',
          interlace: true
      }
    ) %}
    {% if image | length %}

    {% for image in block.image %}

    {% endfor %}

    {% endif %}

I think the issue is on the line src="{{ transformedImages[1].url }}" but I can't find what to change it to, to output the different images. The first thing I tried was removing the [1], but that doesn't work and gives an error of Key "url" for array with keys "0, 1, 2" does not exist.

Hopefully someone can help, otherwise I'll have to take it out of the matrix field and create a field for each image. But would prefer to keep it in the matrix if possible?


texts: Trim trailing spaces before each new line in a multi-line string

texts:
I have a string from a multi-line plain text field and I'd like to trim any trailing spaces before new lines.

With plain regex I would use this expression: /\s*$/gm

Using

{{ string|replace('/\\s*$/', '') }}

will trim out the last trailing space of the string (same as the trim filter would), but not before every new line.

I have tried

{{ string|replace('/\\s*$/gm', '') }}

and

{{ string|replace('/\\s*$/m', '') }}

but that doesn't have any effect.

How can I apply the m modifier to the replace filter?


texts: Add Entry Button Not Shown When Overriding Entry Sources

texts:
We're putting together a site where there is regional content managed by regional editors. I want to override the sources to only list entries from regions they are allocated to. I also want to group them by region rather than having entries for all their regions in one list.

All was going well until I tried to remove the default Craft sources by clearing the $sources array at the start. This has resulted in the New Entry button no longer being displayed.

This is my function at the moment:

public function modifyEntrySources(&$sources, $context)
{
    if ($context == 'index')
    {
        if ($this->regionalEd)
        {
            $sources = [];
            foreach ($this->regions as $region)
            {
                $sources[] = ['heading' => $region['title']];
                $sources['news:'.$region['id']] = [
                    'label'       => 'News',
                    'criteria'    => ['relatedTo' => $region['id'], 'section' => 'news', 'editable' => true],
                    'data'        => array('type' => SectionType::Channel, 'handle' => 'news'),
                    'defaultSort' => array('postDate', 'desc'),
                ];
                $sources['notifications:'.$region['id']] = [
                    'label'       => 'Notifications',
                    'criteria'    => ['relatedTo' => $region['id'], 'section' => 'notifications', 'editable' => true],
                    'data'        => array('type' => SectionType::Channel, 'handle' => 'notifications'),
                    'defaultSort' => array('postDate', 'desc'),
                ];
            }
        }
    }
}

Is there something I need to add/remove, (other than the $sources = []; line!), to allow the New Entry button to be displayed?


texts: We have a form on our website that helps us build subscribers organically. But, we'd like to be able to share a direct link to our subscribe form so that we can do direct outreach to gain subscribers. Does freeform allow you to access the form directly via a url?


texts:
There is the one way to build it, I could know, but It's complicated for maintenance, because I may add some new entry by time.

I'm trying to figure out a better way to have entry types related to a section and all sections in dropdown menu. Namely, sections have some same, some different entry types. So, when I click at any entry type at current section page, I get all those related entries to the click. It's more like filter feature, but except filtering on current page, you get redirected to a page with selected entry type's option.

Better to visualize it:

(http://www.dev.craft/ = all entry's types from all sections) = all entries from all sections and entry's types.

(http://www.dev.craft/entryTypeHandle = entryTypeHandle from all sections) = entries from all sections and entryTypeHandel.

(http://www.dev.craft/sectionHandle/entryTypeHandle) = entries from sectionHandle and entryTypeHandle

It is hard to read. You're welcome for question's comments, if anything unclear.


texts:
I'm trying to install Craft v3 on a web server currently running Craft 2. As far as I am aware all the required PHP extensions (including iconv) are installed; PHP v7.1.x

The front end works OK, but as soon as I go to the control panel I get this (devmode=true)

> PHP Notice – yii\base\ErrorException iconv(): Wrong charset,
> conversion from `UTF-8' to `UTF-16BE' is not allowed

I should note that my method of installation involves getting the site working on a local machine and then copying everything over, and editing the .ENV and general.php accordingly. There is no added content or plugins installed - just an empty Craft install (latest version).

As far as I can see the database charset is set up correctly (UTF8).

What else should I be looking at?

UPDATE: digging around further, if I run a PHP test file,  this line

> $res=iconv('utf-8', 'UTF-16BE', 'test1');

throws the same error message. So I am guessing it is a server problem.


texts: Order Entries by Category Fields (with fallback)

texts:
This is almost a duplicate of this question

I have a section which I want to sort by category field. But the categories are not mandatory.

When I apply |group('refSorter.first().title') it will throw an error:

  Key "type" for array with keys "0, 1, 2, 3, and so on"
  does not exist.

I did a workaround with a conditional statement but I guess there is a DRYer solution:

{% set refList = craft.entries.section('referenz') %}
{% set refCategories = craft.categories.group('referenzRubrik').relatedTo(refList) %}

 {% for category in refCategories %}

    <h2>{{ category.title }}</h2>

    {# testing if there is a category slug for preventing a error when no category is asigned #}

    {% if category.slug == 'kantone' %}

      {% for item in refList.relatedTo(category).order('title')|group('refSorter.first().title') %}
          {# this is beeing sorted via category title fields #}
      {% endfor %}

    {% else %}

      {% for item in refList.relatedTo(category).order('title') %}
        {# this is beeing sorted via entry title fields #}
      {% endfor %}

    {% endif %}

{% endfor %}

The must be a better way right?


texts: Dynamic postCpLoginRedirect based on user permissions

texts: I'm wondering if it's possible to set the postCpLoginRedirect config setting dynamically during plugin initialization. Seems like that's a no-go, but wanted to confirm. Ideally, I'd like to ID users with very limited CP access and direct them straight to their view's url (effectively skipping the dashboard for this user group only). I would welcome suggestions for best-practice workarounds/alternatives if dynamic setting of this property is not possible. Thanks!


texts: When using Active Record with a View (instead of Table) the primary key is not set in the record after save

texts:
I ran into a problem when saving a new record.  I have created a test below.  When saving a record using a db table, the record is saved to the db and the primary key id is updated in the record object.  Works as expected.

But if the record is saved to a db view (instead of a table), the record is saved to the db but the primary key id is not updated in the record object.  Not working as expected.

I have a third party table that I am using in a plugin that I am developing (in this example, I am calling this third party table craft_test).  I can't changed the name of the table but have created a view name with "craft_" in order to use all of crafts features.

In my example, I have a custom primary key (Member_ID) that I am using.  The issue still exists if I use the the default primary key of id (by changing the Member_ID column to id in the db, removing the primaryKey() method in the Record declaration, removing Member_ID from defineAttributes in the Record, and rennaming  Member_ID to id in the model defineAttributes).

Does anyone have an idea why the view is not working?  Is there a bug in the craft code?  Or is there a setting that I need to modify?

Accd_TestModel.php

namespace Craft;

class Accd_TestModel extends BaseModel
{

public function defineAttributes()
{
    return array(
        'Member_ID'    => array(AttributeType::Number),
        'FirstName' => array(AttributeType::String, 'maxLength' => 40, 'required' => true),
    );
}
}

Accd_testRecord.php

class Accd_TestRecord extends BaseRecord
{
/**
 * Gets the database table name
 *
 * @return string
 */
public function getTableName()
{
   // REMOVE COMMENT BELOW USE VIEW INSTEAD OF TABLE
   // return 'test_view';
   return 'test';
}

public function primaryKey()
{
   return 'Member_ID';
}

/**
 * Define columns for our database table
 *
 * @return array
 */
public function defineAttributes()
{
    return array(
        'Member_ID'    => array(AttributeType::Number, 'column' => ColumnType::PK),
        'FirstName' => array(AttributeType::String, 'maxLength' => 40, 'required' => true),
    );
}

}

Code:

    $test_model = new Accd_TestModel();
    $test_model->setAttribute('FirstName', 'Bill');

    $test_record = new Accd_TestRecord();
    $test_record->setAttributes($test_model->getAttributes());
    if ($test_record->save())
    {
        // update Member_ID on model (for new record)
        $test_model->setAttribute('Member_ID', $test_record->Member_ID);

        echo '
Model FirstName: '.$test_model->getAttribute('FirstName');
        echo '
Model Member_ID: '.$test_model->getAttribute('Member_ID');
        echo '
Record FirstName: '.$test_record->getAttribute('FirstName');
        echo '
Record Member_ID: '.$test_record->getAttribute('Member_ID');

    }
    else
    {
        echo 'failure';
    }

Database:

CREATE TABLE IF NOT EXISTS `craft_test` (
`Member_ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`FirstName` varchar(40) NOT NULL DEFAULT '',
`dateCreated` datetime NOT NULL,
`dateUpdated` datetime NOT NULL,
`uid` char(36) NOT NULL DEFAULT '0',
PRIMARY KEY (`Member_ID`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Database View:

  CREATE VIEW craft_test_view AS SELECT * FROM craft_test

Output to screen when using view:

Model FirstName: Bill
Model Member_ID:
Record FirstName: Bill
Record Member_ID:

Output to screen when using table:

Model FirstName: Bill
Model Member_ID: 7
Record FirstName: Bill
Record Member_ID: 7


texts: Is it possible for an Element Type to return multiple content tables with the getContentTableForElementsQuery() method?

texts:
I'm building a plugin where each Element created has a unique content table associated with it.  Each individual Element behaves as needed, however, when I try to create an index page that returns all of the records of this Element Type, Craft seems to assume that I'm using the default content table unless I tell it differently in the getContentTableForElementsQuery() method.

However, the results that are being returned have Elements with multiple content tables.

Am I overlooking anything here or is there a different way I should be thinking about this?


texts: How can I trigger an image transform in a Craft plugin?


texts: How should one go about using Craft with Git? [not duplicate]

texts:
I've seen many other questions about Craft deployment, some of which even use Git, but none seem to thoroughly address how one would use version control on their local development environment, push changes to a remote repository, and then pull changes down to the staging or production server.

Sure, you can handle modifications to static assets and templates this way, but those changes often require modifications to sections, entries, categories, and globals, all of which are stored in the database. How would one manage the entire website through version control?

Any help is appreciated. Thanks!


texts:
I've got News Archive pages that display all entries posted in a certain month/year. For example June 2016 shows all entries created in June of 2016!

I'm fetching the entries based on craft.request.segment (as the URL ends in /june/2016 etc). This works great for all English months, but when my URL says /juni/2016 (the German month name) it can't find any entries??

{% set month = craft.request.segment(2) %}
{% set year = craft.request.segment(3) %}

It's defintely a translation thing. Anyone know how craft.request.segment can work with locales (German and simplified Chinese) too?


texts: I am getting a 403 error after I login to the Control Panel

texts:
I have a problem after installing Craft on a live server (local with MAMP everything works fine). I could install it with composer but when I login to /admin then I will redirect to a 403 page... and everything is a 403 error till I clear cookies :/

Update:

I think my problem is that Craft somehow generates two Cookies after logging in. when I delete one, the 403 disappears and I can enter the admin dashboard, but when I logout and login again - two cookies again and the 403 error ... :frowning:


texts: Help with the latest Redactor, removing formatting options

texts:
In the past I've managed to remove a few formatting buttons from Redactor but am having trouble with the new version.
The goal is to remove 'quote', 'code' and 'heading1' from the formatting-dropdown. (see attached).

So far I have tried various ways of inserting this from the documentation:
['p', 'h2', 'h3', 'h4', 'h5']
This is the only attempt which hasn't resulted in a syntax error, but which has resulted in the formatting button disappearing completely!
  "buttons": [
    "html",
    "formatting: ['p', 'h2', 'h3', 'h4', 'h5']",
    "bold",
    "italic",
    "unorderedlist",
    "orderedlist",
    "link",
    "image",
    "video"
  ],
  "plugins": [
    "fullscreen",
    "video"
  ],
  "linkNewTab": true,
  "toolbarFixed": true
}

Please could you spoon feed me the json as I cannot seem to find the answer anywhere. Thanks in advance for your help!


texts: Sprout Email variables in custom fields aren’t replaced after update

texts:
I updated Sprout Email from 4.0.8 to 4.4.9, along with Craft now being at 3.6.15.
Since then the variables inside my (redactor) custom field aren’t replaced anymore. The email template ist basically the example template outputting basic html and: {{ email.emailBodyHtml_de }}.
The content of email.emailBodyHtml_de contains things like {firstName} and {{ siteUrl }}, but they are not replaced with the User Model values (the notification is triggered at user save).
When I add {{ object.firstName }} to the html template, it outputs the name correctly, but the variables coming from the custom field aren’t replaced.
Has something changed that I am missing?
Any hint is much appreciated.
Cheers,
Mark


texts:
I need to add an "attachment" to an email sent by Craft CMS 3.

I used a custom "Module" for this with a "Model", "Service", "Record" and "Controller"

I did some research but did not find any clear answers on how to do it.

How to send a email with an attachment?

---- Update -----

Here's what I need to do

Example :

Person A
Fill the form with file a file ( like doc, pdf etc... )

Prepare the email with the custom "module"

Do I have to upload the file somehow on the server before do the attachement in the email ?

Send the email with the file in attachement to Person B


texts: Create a link list with URLs, categories, entries

texts:
Sorry if this question has already been asked.

I'm building a website for a client. In their footer they have several list of links, and I want them to be able to change them (so not hardcoded into the code).

I'm using a "Entries" type for those linklist. It is intuitive but there are two main caveats:

They have links like "Blog" that must link to an index of a channel. Unfortuantely, because this is not an entry, it does not appear. I've found an ugly workaround that consists of creating a single "Blog", but this is a bit annoying because there is an additional single appearing for them, and this means that I need to rename the channel to something else (because Blog become already taken by the single).
They have some links that point to an external URL (they host their FAQ on ZenDesk, so the FAQ is an external URL). It therefore does not work.

For the last point, I've found a nice plugin called LinkIt (https://github.com/fruitstudios/LinkIt) that nearly tackles the problem, but with one major drawback: contrary to the Entries type, it only allows to add one link (using a matrix feels a bit overkill here and is less intuitive than the Entries stuff).

Did I miss something? I think it would be really good if Craft could have a new field type "URL", that would allow to enter a free URL with a label. It would give much more flexibility to the system.

Thanks!


texts: Add product to cart using code in Craft Commerce plugin

texts:
I want to add a specific product to a cart using its ID. I have created a module which runs on Order::EVENT_BEFORE_ADD_LINE_ITEM event. Here I am able to capture the current cart using the below code
$cart = craft\commerce\Plugin::getInstance()->getCarts()->getCart();

I can also get a Product using the below code
$product = \craft\commerce\elements\Product::find()->id([123]); // here 123 is product id

But I am not sure how to add this product to the existing cart using a code.


texts:
I'd like to set up a notification if an entry is saved in a the section 'memberNewsFeed'. The data that I would like to access is the entry title and url, and the user who made the change.

Can anybody advise of the syntax to input into rich text field that comes as standard with sprout email please?


texts: How do you add support to manage content in multiple languages in a plugin with a custom Element Type?

texts:
We have a plugin with custom Element Types that allows a user to create a field layout using custom fields.

We understand how to setup a localized site and add translation files.  This question is specifically about how to add support for the user to be able to add content in multiple languages via the custom fields as they add new Entries to a Custom Element Type.

It would be nice to see a list of all the steps we need to consider.  Ideally, the answer could double as the page we would have read in the documentation instead of posting this question =)

Update:

For reference, these are the tables that appear to have a locale column in the default Craft database.

craft_categorygroups_i18n
craft_content
craft_elements_i18n
craft_entrydrafts
craft_entryversions
craft_locales
craft_matrixblocks (ownerLocale)
craft_matrixcontent_body (and any other Matrix field's content table)
craft_routes
craft_searchindex
craft_sections_i18n
craft_templatecaches


texts: Setting up Craft's registration e-mails to be sent through GMail

texts:
I have a question regarding how to set up Craft 3 RC8 to send e-mails through a corporate GMail account.

My website's MX records are pointed at GMail through Cloudflare
I tried setting this up when my website was on Craft 2.6. I set that up and my e-mail got blocked. I unblocked it through GSuite admin account and switched back to php.
When sending through PHP mail, my e-mails get sent into spam.

So I need help on whether how to get my e-mails sent through GMail without my account getting banned, or how to make the e-mails sent through PHP not go into spam.


texts: Error when setting field length on global

texts:
I have set up several globals to store the URLs of a company’s social media accounts. Each one is a plain text field, and each one is limited to 254 characters.
This works fine with three of them, but when I came to limit the length of the link for twitter I get this error:
SQLSTATE[42000]: Syntax error or access violation: 1118 Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
The SQL being executed was: ALTER TABLE `content` CHANGE `field_twitterLink` `field_twitterLink` varchar(1016)

I have tried this several times, and I am definitely not hitting a key accidentally, the amount I’m entering is 254, the field is plain text. This matches the other fields that worked correctly.
If I omit the length, it works. And it works on the other links.
It’s not a catastrophe, but I would like to understand what’s going wrong. Any insights appreciated.


texts: How can I have created data (id) returned for a GraphQL mutation?

texts:
I have a mutation which is successfully creating an entry, but the data returned for the mutation does not include the fields I specify, such as id.
mutation saveWindowCleaningRequest($title: String!, $frontendInput: String!) {
  save_pdWindowCleaningRequests_pdWindowCleaningRequests_Entry(title: $title, siteId: 2, frontendInput: $frontendInput, authorId: 1) {
    id
    title
    ... on pdWindowCleaningRequests_pdWindowCleaningRequests_Entry {
      frontendInput
    }
  }
}

Data returned:
{
  "data": {
    "save_pdWindowCleaningRequests_pdWindowCleaningRequests_Entry": null
  }
}

Mutation result screenshot:

Subsequent entry query result screenshot, showing entry was created:

I'm running Craft 3.5.15.1 with PostgreSQL 12.4 in Ubuntu 18.04.5 LTS.


texts: Charge Plugin v2.2.1: Variable subscription amounts

texts:
What's the best way to accomplish a variable subscription amount with the Charge plugin? I.e. the Stripe payment amount needs to change from month to month.

As an example, say a subscription is £0.99 each month, and then additional purchases are £0.99 on top of this, can I update the subscription somehow before the charge date with the final amount, or can I put through additional payments each month using the Stripe ID attached to the subscription?

Thanks in advance.


texts: How can I have a dynamic uri segment for a single?

texts:
I am trying to have a dynamic uri segment for a single. I have this uri in the CP settings:

offers/listing/{slug}

Where {slug} is the entryId. For example, offers/listing/1234

I have a template at templates/listing/make-offer.twig

For the template path i have: listing/make-offer

If I navigate to site.com/offers/listing/1234 I get a 404.

However, if I make a custom route:

URI looks like: offers/listing/(slug)
Loads template: listing/make-offer

Everything works. The downside is I would like to control the content on the top of the page through the CP.

I realize, this is something more of a channel (which I still get a 404), but this page will never go anywhere. It's a content page at the top with a contact form at the bottom.

Thank you for any suggestions!


texts: How to create plugin pivot table entries?

texts:
I have a record for an entity my plugin needs and that may be related to many Entries, so I have a pivot table, much like Craft's usergroups_user table.

I'm creating and updating my table fine and I'm not looking at my pivot table. I notice the the user group approach is to delete any entries before creating new ones:

public function assignUserToGroups($userId, $groupIds = null)
{
    craft()->db->createCommand()
        ->delete('usergroups_users', array('userId' => $userId));

    if ($groupIds)
    {
        if (!is_array($groupIds))
        {
            $groupIds = array($groupIds);
        }

        foreach ($groupIds as $groupId)
        {
            $values[] = array($groupId, $userId);
        }

        craft()->db->createCommand()->insertAll('usergroups_users', array('groupId', 'userId'), $values);
    }

    return true;
}

I take it this is the best way to handle pivot tables and there is no 'sync' functionality similar to that found on Laravel's Eloquent class http://laravel.com/docs/5.1/eloquent-relationships?


texts: Customizing Craft Commerce Template Paths

texts:
Let me apologize right now that my inexperience with Craft is likely the issue here and that my question might be more general to Craft's routing features and not so specific to Craft Commerce.

I'm playing with a clean Craft/Craft Commerce installation and using the included templates in /templates/commerce. I wanted to customize the path however to /store/. I changed the directory name, adjusted the "commerce" where it was hardcoded in the templates, and changed the Product URL Format and Product Template within the Product Types to use store/ instead. Everything seems to look okay until I try to add/remove/update a product into the cart.

When that happens I get a routing error:

CHttpException
Unable to resolve the request "store/cart/updateCart".
/path/to/craft/app/framework/web/CWebApplication.php(286)

Line 286 is:

throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".'

Should I be leaving these paths alone and adjusting the URL in a different way? Any help and direction would be greatly appreciated. Thank you!