texts:
In my custom Twig tag I am trying to reference a class in the Twig_Node compile method, however I receive an error every time stating it can't find it.  What would the path be to a custom plugin class for the Twig_Node?

  Fatal error: Class 'PluginCustomClass' not found in /Volumes/Grid/Devbox/www/event.craft.dev/craft/app/vendor/twig/twig/lib/Twig/Environment.php(403) : eval()'d code on line 431

public function compile(\Twig_Compiler $compiler)
    {
        $compiler
            ->addDebugInfo($this)
            ->subcompile($this->getNode('pluginTarget'))
            ->raw(', ')
            ->subcompile($this->getNode('elementsTarget'))
            ->raw(') = new \PluginCustomClass(')
            ->subcompile($this->getNode('criteria'))
            ->raw(");\n");
    }


texts: Showing Profiling Summary Report data in the frontend

texts:
I'm trying to debug why certain pages on a site are slow using the 'Profiling Summary Report' data that is logged to the console when devMode is enabled.

For easy viewing, I've tried to output the values in a flash message on the front end of the site using the following code, placed in the init() function of a plugin:

if ( craft()->config->get( 'devMode' ) && craft()->request->isSiteRequest() )
{
  $debugInfo = 'Time: ' . sprintf( '%0.5f', Craft::getLogger()->getExecutionTime() ) . 's' . "\n";
  $debugInfo .= ' — ' . 'Memory: ' . number_format( Craft::getLogger()->getMemoryUsage() / 1024 ) . 'Kb';
  $debugInfo .= ' — ' . 'Queries: ' . count( Craft::getLogger()->getLogs( '', 'system.db.CDbCommand' ) );
  craft()->userSession->setFlash( 'debug', $debugInfo );
}

They successfully log values (that look correct for seconds, kb's and query counts) but they are different to what is displayed in the console.

Update: These are the values from 4 different page loads. I have a suspicion that these are referring to a different process, not the current page, as they're too consistent.

Time: 0.14093s — Memory: 12,458Kb — Queries: 5
Time: 0.14069s — Memory: 12,217Kb — Queries: 5
Time: 0.13179s — Memory: 12,218Kb — Queries: 5
Time: 0.13125s — Memory: 12,218Kb — Queries: 5

Does anybody know why this might be? I had a feeling it was logging the values of a different process to the console. Is getLogger() relative to where it's called?


texts:
Aside from Defining Transforms in the template (http://buildwithcraft.com/docs/image-transforms) is there a way to go back and trigger an image transformation?

We've got a number of assets that have been uploaded to rackspace that need image an image transformation but the transformation was created after the images were uploaded.

Is there a way to kick this off?


texts: How can I force a download of entry data to an excel file?

texts:
The website I'm building enables users to book places on events. This is simply a form which creates an entry in a channel containing 2 fields: "related user" and "related event". In the control panel I've written a simple plugin which displays all the entries in that channel exactly the same as the control panel normally would do, but now I can display any fields I want instead of just title and post date.

My client wants to be able to export the entry data from the control panel into Excel (xls or csv). What's the simplest way to do this? I read somewhere about changing http headers to force a download of a file, so can I just force a browser download of a dynamically generated page containing a table of all that entry data?

When I say "force a download" I mean I probably just need a button that says "Export", but it should download the file instead of opening it in the browser.


texts: How can i apply "current" class for category nav?

texts:
I've browsed the questions and answers here and i can't find anything that works for what i'm trying to do!

I am using this as the main menu of my site (so it is in _layout.html)

{% nav category in craft.categories.group('artCats') %}
{% set entryCount = craft.entries.relatedTo(category).total()

{{ category.title }}{% if category.level == 2 %}({{ entryCount }}){% endif %}
  {% ifchildren %}

      {% children %}

  {% endifchildren %}

{% endnav %}

It's a drop down menu that shows how many posts are in each sub category. All works nicely!

However, no matter what i try, i can't seem to dynamically assign a class to the current page. I think i'm misunderstanding in general how this is done in Craft.

I see a lot of solutions that are basically saying "if url segment is "fishcake" then add my class" but to me, that's not dynamic at all! Dynamic would be if i add a new sub-category, the menu will add my desired class to that menu item if i visit, without me having to add a new if statement in the Twig code.

Am i able to do something like "if the category.url of this link matches the current url, do this" ?


texts:
I just noticed that none of my recent changes in an entry don't show up in the entry-versions button in the CP.

Is it possible that these entry versions are triggered by the task runner? Because I lately disabled it 'runTasksAutomatically' => false, ?

I added a second locale to the entries and since then, the versions don't show up anymore?


texts:
I'm trying to get prev/next entry using positionedAfter and positionedBefore filters but getting weird order on results because order('postDate desc') seems to be ignored.

{% set prevSibling = craft.entries.positionedAfter(entry).order('postDate desc').first() %}

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

Can anyone help?


texts: How do I setup my fields for a tumblr-like blog

texts:
My blog has different post types, e.g. full blog post, quick status, quote, image post, how would I go about it? Is the logical way to setup a single Matrix Field with each block representing a different post type? Is there a better way of doing it?

Stating the obvious for clarity. A full blog post would have the usual stuff (title, body, image). Status has just content without a title, it's just a quick note. Quote has text and quote author and link, again no title.


texts: How reference "Craft" js object in jquery scope

texts:
I have this function within my <script> tags:

$('.btn').click(function()
{
    var data = {
        title: "This is a title"
    };

    Craft.postActionRequest('plugin/controller/action', data, function(response) {
    });
});

The "Craft" function returns as "TypeError: Craft is undefined". I'm guessing I somehow need to reference the scope to the function but I can't seem to get it to work.

I tried adding _self = this outside my jquery click function and reference Craft like "_self.Craft" but that didn't do it.

What am I missing here?


texts: Craft 3 FeedMe - Help accessing deeper XML nodes

texts:
I'm importing data from an XML file.
I'm having trouble accessing some of the deeper nodes in the xml file.

Example of my xml here (chapter being the repeating item):

<chapter>
<title> Title – Version 5.0.11.110 </title>
<subtitle> Release Notes </subtitle>
<info>...</info>
<sect1>
<title> Improvement </title>
<sect2>
<title> AP - Accounts Payable </title>
<itemizedlist>
<listitem xml:id="A50-3451-1">
<para>
Allow edit for Shipment Comment on Both Shipments after Post Invoice if Edit Shipment After Posting is enabled.
</para>
</listitem>
<listitem xml:id="A50-3487-2">
<para>
Make AP Generate Payment form and report all fields from AP Transaction.
</para>
</listitem>
</itemizedlist>
</sect2>
<sect2>
<title> CB - Cash Book </title>
<itemizedlist>
<listitem xml:id="A50-3314-3">
<para>
Added StatementID, StatementLineNo and PeriodReconciled as available fields for the transactions band on the CB Unreconciled Transactions layout, making it easy to see if a transaction which is unreconciled as at the period reported on is on a statement, and reconciled subsequently.
</para>
</listitem>
</itemizedlist>
</sect2>
</sect1>
<sect1>
<title> Bug Fix </title>
<sect2>
<title> ALL - All Modules </title>
<itemizedlist>
<listitem xml:id="A50-3400-1">
<para>
Fix possible A record already exists with that Layout (..) code - Error message.
</para>
</listitem>
</itemizedlist>
</sect2>
</sect1>
</chapter>

And my template code so far:

{% set params0 = {
    url: 'https://sitename/downloads/ReleaseNotes.xml',
    type: 'xml',
    element: 'chapter',
    cache: 60,
} %}

{% set params1 = {
    url: 'https://sitename/downloads/ReleaseNotes.xml',
    type: 'xml',
    element: 'sect1',
    cache: 60,
} %}

{% set params2 = {
    url: 'https://sitename/downloads/ReleaseNotes.xml',
    type: 'xml',
    element: 'sect2',
    cache: 60,
} %}

{% set feed0 = craft.feedme.feed(params0) %}
{% set feed1 = craft.feedme.feed(params1) %}
{% set feed2 = craft.feedme.feed(params2) %}

{% for node in feed0 %}

{{ node.title }}

    {% for node in feed1 %}

{{ node.title }}

        {% for node in feed2 %}

{{ node.title }}

{{ node.itemizedlist.listitem.para }}

        {% endfor %}

    {% endfor %}

{% endfor %}

I've ended up using multiple feeds as I couldn't get to the "para" node at all. This maybe wrong.
I thought that
{{ node.itemizedlist.listitem.para }}
 would do the trick.
Can someone offer some help please.


texts: How do you add tags to tag field when saving an entry?

texts:
I'm working on a custom import plugin which needs to import a load of content to fields including categories and tags. Categories is working fine using a comma separated list of category ids:

        $entry = new EntryModel();
        $entry->authorId  = $eventObject->author;
        $entry->enabled   = true;
        $entry->postDate   = $eventObject->postDate;
        $entry->getContent()->title = $eventObject->title;
        $entry->getContent()->setAttributes(array(
            'slug' => $eventObject->slug,
            'locationText' => $eventObject->locationText,
            'date' => $eventObject->eventDate,
            'overview' => $eventObject->overview,
            'eventWebsite' => $eventObject->eventWebsite,
            'eventCategories' => $eventObject->categories,
            'location' => $eventObject->location,
            'eventTags' => 1453,
        ));

I just can't get tags importing at all, also need to create new tags where a tag doesn't already exist! Testing with the id 1453which is an existing tag id.


texts:
i am new to craft.
Is there a connection between the control panel sorting setting for structure entries and the template output.

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

Changing sort method in control panel should leads to different outputs in template. Is that right?

Goal is to output entries in sort order related to control panel sort settings.

What did i do wrong?


texts:
We're using Solspace Freeform for a multi-stage application form on a client site. We need to store each stage in the CMS - is this possible?

Thanks!


texts: I'm working with a fairly large data set in one of my channels and I was hoping there was a way maybe in admin to show me all the live entries where certain fields are empty. I want to be able to easier find where I'm missing data. Any suggestions?


texts:
I explored the events plugin (from https://github.com/pixelandtonic/Events) and I understand the most of that. Now I will try to make the events localized.

The Event itself has no localized field, just the fieldLayout fields. Do I have to save a second record in the event db or did I just have to save the element with the corresponding locale id?

Can you give me a hint what steps are needed that I can edit them in two languages?

So far, I load an existing event

craft()->elements->getElementById($eventId, 'Events_Event', $locale);

with the new locale parameter and create the edit form, putting the locale as hidden field to the form ('de' instead 'en'). The fieldLayout fields are showing the 'de'-icon above the input fields.

When I try to save it, I pass through the locale in the $event variable to
craft()->elements->saveElement($event)

I do not pass it to the $eventRecord because the $eventRecord itself didn't have a locale.

The event will be saved, just not in 'de' but in 'en'.

Do I have to tell the elementtype or the model that it can be localized to make it work?


texts: Getting invalid verification code for email confirmation

texts:
I am using Craft CMS as a backend for react Next app. On our live site we are sometimes getting complaints from the user about error when user try to verify code sent in the email.

This case doesn't happen with every user but very for random users. For this reason I am not able to find the reason for the issue and fix it.
Everytime I see following information in the log file.

  2020-05-27 10:17:35 [-][-][-][warning][craft\services\Users::isVerificationCodeValidForUser] The verification code (gqkZpvgTZDMNSXRyNuXE4ksxpNOlBOl) given for userId: 99965 does not match the hash in the database.
  2020-05-27 10:17:35 [-][-][-][info][application] $_GET = [
      'p' => 'ACT/craft-rest-api/user/verify-email'
      'code' => 'gqkZpvgTZDMNSXRyNuXE4ksxpNOlBOl'
      'id' => 'ef2156d6-306b-4a88-80bb-25ca26562702'
  ]

Here is the information about the system.

PHP version 7.4.5

OS version  Linux 3.10.0-1127.el7.x86_64

Database driver & version   MySQL 8.0.20

Image driver & version  GD 7.4.5

Craft edition & version Craft Pro 3.4.21

Yii version 2.0.35

Twig version    2.12.5

Guzzle version  6.5.4

Imagine version 1.2.3-dev

Plugins:-

Amazon S3   1.2.8

Architect   2.3.3

CKEditor    1.0.0-beta.3

Comments    1.5.6

Contact Form    2.2.7

Craft-Rest-Api  1.1.0

Enforce password    1.0.0

Image Resizer   2.0.9

Klaviyo Connect 3.1.3.2

Redactor    2.6.1

SendGrid    1.2.0


texts:
My system crashed while docker/nitro was open. After a reboot and restarting docker/nitro it appears all my databases are missing. Here's the response when trying to do nitro db commands:
» nitro db ssh
Select a database to connect to:
Enter your selection:

No databases to select from. Before the crash, there were four or maybe five databases. Any ideas on how to proceed?


texts: Front End Form with Dropdown in Matrix - Adding New

texts:
I've got a Matrix field called Emergency Contacts (handle: emergencyContact) that I'm setting up so that users can add/update on the front end.  It has one block type - contact - with 4 fields:

Name (Plain Text - handle: contactName)
Relationship (Dropdown - handle: contactRelationship)
Phone (Input Mask - handle: contactPhone)
Email (Plain Text - handle: contactEmail)

I have everything displaying correct when I show existing information.  However, when they go to enter a new emergency contact, I can't figure out the right syntax to populate the dropdown menu to populate with the options for them to select.

Below is my code.  I've tried several different things, most of which gave me an error.  This is my latest attempt.

<input type="hidden" name="fields[emergencyContact][new1][type]" value="contact">
<input type="hidden" name="fields[emergencyContact][new1][enabled]" value="1">

    <fieldset class="cell small-3">
        Name<input type="text" name="fields[emergencyContact][new1][fields][contactName]">
    </fieldset>
    <fieldset class="cell small-3">
        Relationship
        <select name="fields[emergencyContact][new1][fields][contactRelationship]">
        {% for option in contactRelationship.options %}
            <option value="{{ option.value }}">{{ option.label }}</option>
        {% endfor %}
        </select>
    </fieldset>
    <fieldset class="cell small-3">
        Phone<input type="text" name="fields[emergencyContact][new1][fields][contactPhone]">
    </fieldset>
    <fieldset class="cell small-3">
        Email<input type="email" name="fields[emergencyContact][new1][fields][contactEmail]">
    </fieldset>

Anyone able to help me get this resolved?


texts:
Is it possible to register multiple EventHandlers?
I mean something like this:
    Event::on(
        Entry::class,
        Entry::EVENT_AFTER_SAVE,[
           NotifyWhenCookPostedArticle::handle,
           RunSomethingElse::handle,
           DeSomethingDifferent::handle
        ]

I tried it and got a PHP Warning – yii\base\ErrorException call_user_func() expects parameter 1 to be a valid callback, second array member is not a valid method
Is there a notation or helper to get this to work?
Thanks in advance .
Michael


texts: Modify/add to price based on custom field?

texts:
Is there a way to modify a variant's price based on a custom field in the product?

To clarify, Let's say I have a matrix field with a block that has a text input with the handle name and a numeric input field with the handle price. This is then outputs as a radio button select list in the template like "Original" and "Name". When the "Name" radio button is selected, the price is picked up from the field price in that matrix block. The user could then add to cart with the modified price.

Any way to do this without plugins, or is there a plugin available for this logic? I'm not PHP savvy, so any light that can be shed on this is much appreciated. Ideally there's a way to do this within the template.


texts: getDirtyAttributes() not showing changes

texts:
I've got an event listener in a custom plugin where I want to check to see if the users email updated, but it doesnt show that attribute as dirty, even though I know it should be:
Event::on(User::class, User::EVENT_BEFORE_SAVE, static function (ModelEvent $event) {
    /** @var \craft\elements\User $user */
    $user = $event->sender;

    Craft::info('USER::EVENT_BEFORE_SAVE');

    Craft::info($user->getDirtyAttributes());
});

When I update the users name or email from the admin panel, I get an empty array in my logs

2021-02-03 17:20:18 [-][25250][-][info][application] USER::EVENT_BEFORE_SAVE
2021-02-03 17:20:18 [-][25250][-][info][application] []

From the API:

Returns whether an attribute has changed since the element was first loaded.

The way I have read that is whenever something changes on the model, it will be recorded in the above method output
What am I doing wrong/missing here?


texts: How do I create a well formed CSV or XML to succesfully import entries with assets and categories?

texts:
The source website is in ExpressionEngine and I know how to get data out, but I don't know how to structure it and succesfully import entries into Craft where assets and categories also imported. I have tried the plugin FeedMe (XML) and I also tried the plugin Import (SVG).

How to work with categories and sub categories an how to use multiple assets with import? Thanks in advance!

<?xml version="1.0" encoding="UTF-8"?>
    <products>
        <entry>
            <title>My product title</title>
            <slug>my-product-title</slug>
            <![CDATA[
My body text
]]>
            <assets>
                <![CDATA[
                    http://www.mywebsite.nl/root/path/image1.png,
                    http://www.mywebsite.nl/root/path/image2.png
                ]]>
            </assets>
            <category>
                <![CDATA[
                   Lightning,
                   Cities,
                   Standard,
                   Special
                ]]>
            </category>
        </entry>
    </products>


texts: Open pop on click of custom action and get filled data

texts:
I created a new custom action.

A new button is added in getAvailableActions() as we can se in below screenshot in red marked rectangle, now when i click on that button
 (Cusotm Action) i want to open a pop up box ( i used Default pop up js lib.

Template File path : /craft/plugins/tagmanager/templates/_mergetags.twig

{% includeJsResource "tagmanager/js/tagmanager.js" %}

{{ "Merge Tags"|t }}

Modal header

js part

$(function () {
  $modal = new Garnish.Modal($('#mergetags-modal')); //create a new modal
  $modal.show();
});

Not able to open pop up correctly.

Thank you.


texts: Install Craft on VPS with centos 7 and vestacp

texts:
I downloading craft with Composer, but when i move on example.com/index.php?p=admin nothing happens. In the logs:

PHP Warning:  require_once(): open_basedir restriction in effect. File(/home/User/web/example.com/vendor/autoload.php) is not within the allowed path(s): (/home/User/web/example.com/public_html:/home/User/tmp) in /home/User/web/example.com/public_html/index.php on line 11
PHP Warning:  require_once(/home/User/web/example.com/vendor/autoload.php): failed to open stream: Operation not permitted in /home/User/web/example.com/public_html/index.php on line 11
PHP Fatal error:  require_once(): Failed opening required '/home/User/web/example.com/vendor/autoload.php' (include_path='.:/opt/remi/php70/root/usr/share/pear:/opt/remi/php70/root/usr/share/php:/usr/share/pear:/usr/share/php') in /home/User/web/example.com/public_html/index.php on line 11


texts: I wonder if we have a form allowing file uploads for front end users, does Craft or its plugins have certain feature to scan for virus / malicious content, before saving it? If not, what would be the best practice to handle front-end users' uploads? E.g. shall it be handled by the hosting server, or is there a 3rd party library / service that can help?


texts:
Is it possible to get a list of category groups without having to loop through all categories to get their parent group name?

UPDATE:

Just making this question clearer, as it's related to using elementapi. Ideally, I'd like to get a list of category groups via elementapi.

This is what I currently have:

'api/menu' => function() {
  return [
    'elementType' => ElementType::Category,
    'paginate' => false,
    'criteria' => [
      'group' => ['stages', 'series', 'disciplines'],
      'limit' => null,
      'with' => ['group']
    ],
    'transformer' => function(CategoryModel $category) {

      $group = $category->group ?? null;

      return [
        'id' => (int)$category->id,
        'title' => $category->title,
        'slug' => $category->slug,
        'summary' => $category->summary,
        'group' => [
          'id' => (int)$group->id,
          'handle' => (string)$group->handle,
          'name' => (string)$group->name
        ]
      ];
    }
  ];
},

I'd want to structure the data by categorygroup rather than cateogries, something like this (it doesn't work because CategoryGroup is not an elementType) but wondering if there is another way to get the same result?:

'api/menu' => function() {
    return [
      'elementType' => ElementType::CategoryGroup,
      'paginate' => false,
      'limit' => null
    ],
    'transformer' => function(CategoryGroupModel $categoryGroup) {

      $categories = craft()->elements->getCriteria(ElementType::Category)->group($categoryGroup->handle);

      $cats = [];
      foreach($categories as $category) {
        $cats[] = [
          'id' => (int)$category->id,
          'title' => $category->title,
          'slug' => $category->slug
        ];
      }

      return [
        'id' => (int)$categoryGroup->id,
        'title' => $categoryGroup->name,
        'handle' => $categoryGroup->handle,
        'categories' => $cats
    }
  ];
},


texts: Override the postDate for entries so their URL works on the frontend?

texts:
Is it possible to override/disregard the postDate for all entries in a section so that they are visible on the frontend even if this date is in the future?

I realise I could add a dedicated date field — but keen to avoid this if possible as the fields for this entry are already quite complicated!


texts: While I know the back button does this perfectly well, I was wondering if there was a good way to "return to" a paginated page using a previous request or something? Wanting to do this server-side rather than relying on JS. Thanks.


texts: How can I pass a null value to commerce?

texts:
I am populating a drop-down with product variants like this:

<select name="mySelect" class="form-control">
<option value="">Select</option>
{% for purchasable in product.variants %}
    <option {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %}
        value="{{ purchasable.purchasableId }}">
            {{ purchasable.myProduct.label }} &ndash; {{ purchasable.price|currency(cart.currency) }}
    </option>
{% endfor %}
</select>

This is not going to be a required field, so its possible a user could submit without making a choice.

The error I currently get is:

Not a purchasable ID

Which makes complete sense since I am not passing anything to the cart.

Is it best to have a product called "Select" and just have it be zero dollars? Or is there a way - maybe custom plugin - that will skip the input if it has no value?

EDIT

Or do I force the user to make a choice of "No thanks" (or whatever is applicable) then that option has a price of zero dollars...

EDIT 2

If the user does not make a choice, then Craft gets really angry because I have not passed in a valid purchasable ID (a null value).

In the screenshot, the profile is optional. The user doesn't have to pick one. If they do, all is well since they have chosen a valid purchasable. The selected default value is null.

EDIT 3

Well, I guess for now I take everything back. I've tried several times to break it but I can't today. I haven't changed anything that I can think of, but this seems to be working. If I don't choose anything, I am taken to the /cart page as expected.

<option value="">Select Profile</option>
    {% for profile in profiles %}
        <option value="{{ profile.defaultVariant.purchasableId }}" data-price="{{ profile.defaultVariant.price|currency(cart.currency) }}">
            {{ profile.title }} &ndash; {% if profile.defaultVariant.price == 0 %} Included with registration {% else %} {{ profile.defaultVariant.price|currency(cart.currency) }}{% endif %}
        </option>
    {% endfor %}


texts:
I have a channel on my site which holds the products and services available.
Each has various categories to narrow it down. I want to build a product selector and not sure the best method to go about it.
Concept is in image:

The first 3 questions are filters by categories which apply to each product/service. The Q4 is a price which each product/service has.

I already have a page set up with a custom route which filters the products based on the categories e.g:

/products-services/inks/sales-marketing/tiles  which is
/(to load template)/category/category/category

And that currently filters the products as required.

What is my best way to build the product selector? I'm guessing it is to build a url somehow and link to the above route I have already set up?
Could it be done with a structure with a sub level for each question?


texts: Twig search function doesn't work after upgrading to Craft 3

texts:
My client's Craft 2 site includes several templates which use search functions to return a product entry by an ID, like so:
{% set product = craft.entries.section('Product')
    .search('externalidentifier::' ~ craft.request.getParam('eid'))
    .one() %}

This has been working without issue.
They just upgraded to Craft 3 however, and now these search functions don't work. As a troubleshooting step, it works for me if I manually loop through all entries and grab the matching item as shown here:
              {% set eid = craft.request.getParam('eid') %}
              {% for prod in craft.entries.section('Product').all() %}
                  {% if prod.extenralidentifier == eid %}
                  {%     set product = prod %}
                  {% endif %}
              {% endfor %}

...but that only illustrates that the matching entries do exist and should be found with the search function. Any ideas why the search function would stop working after an upgrade to Craft 3?


texts:
I hope I worded the title correctly. I'm trying to output whatever structure's page I'm on - I want the descendants of whatever page that is. I'm currently using this, which at first appeared to work, but then my css styling doesn't get applied to any of the other entries.  See below:

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

        {% for entry in messages %}
          {% for image in entry.seriesArtwork %}

          {% endfor %}

{{ entry.title }}

 {{ entry.postDate|date('M j, Y')}} • {{ entry.speaker }}

      {% endfor %}
{% endif %}


texts:
Is it possible to choose which plugins appear in the main admin navigation?

I've installed Entry Count (https://github.com/putyourlightson/craft-entry-count) and it's now showing in the navigation (under Users).

In this case, I'd prefer to just access Entry Count via Settings > Plugins.


texts: How do you install a plugin through the command line?

texts:
I would like to install and enable plugins through the command line in a way that can be scripted, and which replicates the same steps as are taken when you install a plugin through the Craft control panel.

What commands are necessary to accomplish this?

Would this be enough?

composer require repo/plugin-name
./craft install/plugin plugin-slug

Will these two commands also install the plugin migrations, enable the plugin, and update the project.yaml file, just as if I had installed the plugin through the control panel?

Is it also necessary to run ./craft migrate/all? Or ./craft clear-caches/all?

Also, is it possible to install a specific plugin edition (e.g. Lite or Pro) through the command line?

Thanks!


texts: hacksaw plugin - displaying first 100 characters

texts:
I want to display first 100 characters from a rich text field.

I tried this:

{% set sumtext =  entry.bodyContent.type('text').first().text|hacksaw(chars='100', append='...') %}

But if there was a new paragraph in the first 100 characters and no full stop - both paragraphs are just joined together without a space.

I then tried:

{% set sumtext =  entry.bodyContent.type('text').first().text|hacksaw(allow='<p>', chars='100', append='...') %}

But the  gets displayed on the screen instead of the new line.

what is my best method to display the first 100 characters from a rich text field?


texts:
I'm using the following code for now:

Route (in the control panel)
    recipes/{slug} loads _recipes/restaurant

In the template to define the restaurant and list its items
    {% set restaurant = craft.entries.section('restaurants').slug(craft.app.request.getSegment(2)).one() %}

How do I change it to {slug}-recipes to make it work?

Advanced routing (in routing file) is preferred for performance.

Thanks.


texts: The safest way to edit core Craft files?

texts:
I've been tasked with adding a column to the Entries screen to show some custom data that gets saved against each new post. To do this, I've edited craft/app/elementtypes/EntryElementType.php and added a new table attribute, which does what I need and shows the column.*

However, I'm wary though that updating Craft involves removing the /app directory and replacing it with the one from the latest release.

Is there an advised way I should make tweaks to core files like the one I mentioned? Or, is the only solution to do something like...

Add PHP comments around any core code I tweak
When preparing for an update, compare the old /app against the new one in GitHub
From there, search through the changes to find the comments I've added
For each comment I find, I should manually recreate the changes in the correct places within the new version of /app

* Just to clarify, I was using an older version of Craft when I wrote this post. Having updated to 2.6, I now see that choosing which columns to show on the Entries screen is a baked-in feature. Nice :)


texts: Translated pages load a white empty page on localised site

texts:
I'm running Craft CMS 2.6.2949 on PHP 7.0.10.

I have set up 3 locales: nl_be, en and fr.

I have set the following config into general.php

    '.dev' => array(
    // ...
    'siteUrl' => array(
        'nl_be' => 'http://xxx.dev/',
        'en' => 'http://xxx.dev/en/',
        'fr' => 'http://xxx.dev/fr/'
    ),

I have set the section to translateable and set some fields to be translateable.

I have translated some entries.

When I open the entry in the main language (nl_be) the website load with the desired template and styling. http://xxx.dev/nieuws/2016/we-installeerden-net-dit

When I open the translated version
http://xxx.dev/en/news/2016/we-just-installed-craft

I get a white, empty page. It seems like the template is not loaded.

Any ideas? Thanks a lot in advance.

This is the first time I'm trying Craft and I really love it. Great work Pixel & Tonic!

Bart


texts: Does Craft have a timeout setting for template requests?

texts: I created a RSS feed template and setup a route to it.  If I output more than 40 entries I get a timeout on both FeedBurner and FeedValidator.  Is there a setting in Craft that updates a timeout time or could it be something else going on?


texts:
I can access Craft admin page at work, but I cannot access the admin page at home.
Is it limited by IP address in the code?
The whole site is hosted at vendor's server with Plesk web host edition.

I am new to Craft. Does anybody have any suggestion?


texts: Does Craft have somewhere where I can setup log rotation for the craft.log file, or do admins have to manage that manually?


texts: Can Craft be used on same site as other eCommerce Solutions

texts:
Is it possible to have a Craft installation on the same site as another ecommerce solution like OpenCart or OSCommerce?
Reason being those and some others are already linked with Sage and would like to keep the general content of the site updated using Craft.


texts:
Here's an odd one: I have a site with many users, only a few of them admins. Any admin user can login either via the /admin control panel or through a frontend login, which follows the example from the documentation.

Any non-admin users will be rebuffed on either login with an "Invalid username or password" message. Even more odd, if an admin user attempts to "Login as" a non-admin user from the control panel, it simply takes them back to the dashboard with a "Logged In" message, but keeps them logged in as their original admin role.

Any ideas on what maybe to look for or test?


texts: Database migrations on environments - in which env do I apply updates to Craft and Plugins?

texts:
When developing a Craft 3 site on a multi-environment setup, where would I apply the Craft and Plugin updates?

Should I apply them locally and then commit and replace the database in the dev env, or in dev env and then pull down the database?

Or does Craft have some versioning of the database through db migrations that will help this issue? (Is this where project.yaml comes into play?)


texts:
I have installed and used the Contact Form Extensions plugin a few times but this time it's not working. I can see it in the CP but when I click to install it throws the error:

  Invalid plugin – craft\errors\InvalidPluginException
  'No plugin exists with the handle "contact-form-extensions".'

When I install it the command line does say something about Carbon 1 being deprecated but not sure if it's related?


texts: Displaying assets from Craft's cart AJAX response

texts:
So, I'm currently building out an eCommerce site for a client. I'm adding products to the cart via AJAX. I'm then sliding out a 'Cart' view panel with the current cart contents, which is being updated with Craft's JSON response for the cart. (Via response.cart)

My problem is this: I need to display the thumbnail image of a product, and there doesn't seem to be anywhere I can get the asset field (or any fields) associated with the product. There is no purchasable key in the cart object, just a purchasableId. I've looked in the snapshot object within lineItems, and in the product object within that snapshot object. There doesn't seem to be any asset field (or any field) attached to this information at all.

I know I can make an additional request to fetch that information, but I'd like to avoid that if at all possible; I'm hoping it's just buried somewhere in the response.

Any help is greatly appreciated! Let me know if I need to clarify something.


texts:
I'm currently implementing a search function on a website based on craft, and I was wondering if there was a way of actually showing a small snippet of text that shows in what context the search actually matched.

At the moment the result simply returns the corresponding {{entry.title}}, however I would like the result to also display something like [...] a chain of mountains with the highest *peak* being around x-thousand metres [...] when 'peak' was the search term.

Is there any way to achieve this within Craft?
thanks


texts: Does anyone use Craft CMS to set up an intranet for client?

texts: I heard that Wordpress has a BuddyPress plugin could set up as intranet which has shared files, shared calendars, chat .. etc feature. Does Craft CMS has any plugin to do a similar feature?


texts:
I have a list of dates which are grouped by year and date and also checks if there is a entry in that year:

{% set allSubmissions = craft.amForms.submissions(
  {
    formHandle: 'reservation',
    limit: null,
    order: 'datum asc',
  })
%} {# Gets all the entries #}

{% set izgrad = now | date('Y-m-d') %} {# format now #}
{% set alteAnmeldung = allSubmissions.dateCreated | date('Y') %}

{% for year, entriesInYear in allSubmissions | group("datum.year") %}

  {% if year >= alteAnmeldung %} {# only show the current and future year #}

{{ year }}

      {% for month, entriesInMonth in entriesInYear | group("datum|date('m')") %}
          {% for day, entriesInDay in entriesInMonth | group("datum|date('d')") %}
            {% for item in entriesInDay %}
              {% if loop.first %}
                {% if izgrad <= item.datum %}

{{ item.datum | date('d.m.Y') }}

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

  {% endif %}

{% endfor %}

This works and the list looks like this:

But the code looks horribly inefficient. (this creates 74 db queries). I think there must be a better way to write this. Is it possible to group the fields with less steps for example?


texts:
I noticed this morning a deprecation error popped up for SproutForms.  I have version 2.2.2 (which I believe is the latest).  Here's the deprecation error:

Message
PathService::setTemplatesPath() has been deprecated. Use TemplatesService::setTemplatesPath() or TemplatesService::setTemplateMode() instead.

Origin
/home/xxx.com/craft/app/services/PathService.php (321)

I also am showing this in my craft error log:

Level   error
Category    application
Message There was a problem getting the update feed for “Web Forms”, so it was skipped: [curl] 35: [url] https://sprout.barrelstrengthdesign.com/craft-plugins/forms/releases.json


texts: How do you determine if the current field is required from a fieldtype class?

texts:
I need to run validation in a custom fieldtype but only if a field is required.

How do you determine if the current field is required from within a fieldtype class?


texts: Hide (or disable) an entry field in CP depending on user group permission?

texts:
So I am trying to hide (or disable) a field in the "Edit Entry" view in the CP.

I know how to test a user group :
{% if currentUser.isInGroup('groupHandle') %}

But I cannot find a hook in Craft Doc to change the rendering of my field ?
Perhaps with getInputHtml()? But I dont understand exactly how...


texts: Email Messages – If current email type is html or text

texts:
I am adding a logo to the email message When someone creates an account: via Settings > Email > Messages, the image displays/renders correctly when viewed as "HTML / Rich Text" within mail clients, however; when the email is viewed as plain text, the html for the image is still output (as plain text) rather than being omitted.

Is it possible to conditionally render output from within the message depending on if the type of email content currently being parsed by Craft is for text/html or text/plain?

Desired usage:

{% if html %}
    This is the text/html part of the email message.
{% elseif plain %}
    This is the text/plain part of the email message.
{% endif %}

For reference the message content is currently:

<img src="http://www.example.org/admin/resources/rebrand/logo/logo.svg" width="200">

Dear X,

As a registered user...

Aside: This assumes that Craft processes the email message twice within the same process, once as plain and again as html. If this is not the case then this would likely be unachievable. I do not have an HTML Email Template set within Settings > Email.


texts: I know how to display every next entry, but is it possible when there is no next entry it displays the first one and if there isn’t a previous display the last entry?


texts: Has anyone come up with a solution where matrix blocks can be scheduled and expire?

texts:
To replace my current CMS I will need to have parts of pages change without the whole page change. As I'm looking at using matrix blocks for building pages, it would seem to be easy for an editor to schedule matrix blocks...

Is there a way to do this or a better approach?


texts:
How do I capture user events in Craft 3? I looked at the documentation but couldn't figure it out. I need to capture after user registration events and after user save events.

Here is what I tried, I know it's not correct but I think I'm pretty close

Event::on(
    Users::class,
    Users::EVENT_AFTER_USER_SAVE,
    function (PluginEvent $event) {
        // do something
    }
);


texts: Suggestion for field layout for an ancestor table

texts:
I need to create an ancestor tree where you can specify (in a single entry) the names of ancestors about 3 levels deep. Basically, I need a table with varying column numbers (2 at first level, 4 at second, 8 at 3rd level), but I also need it to be easy and intuitive to administrate.
I'm just looking for input from fellow implementors to spark some ideas on how this is solvable.
One idea is to use a matrix where you can add 1/2/3rd level entries, but that opens up the possibility for errors and wrong order of content which I need to account for.
Another idea might be to just have 14 fields for it, and then separate them by tabs or something. Also, the new craft 3.5 layout possiblity on fields are an improvement but only allows up to 4 columns (on desktop) which makes it a bit bulky. It's mostly the administrative layout that is the problem I'm trying to solve, they will always have a fully populated family tree.
I've also looked at some field plugins, but it's hard to tell if a plugin solves this nicely since descriptions are often very sparse, so I'm hoping someone can share their experiences.
To get an idea on what I'm trying to solve:


texts: add text or image to Craft Commerce confirmation email through the CMS

texts:
I have a customer that wants to modify the order confirmation email.  I set up a new Entry for order confirmation to include a content block that goes to the email/email_confirmation file.

When I check in the browser or preview it works perfectly. When I actually send the email it doesn’t appear.

1) It works in the browser with:

{% if entry.basicContentBlocks %}
// html code
{% endif %}

2) The Commerce plugin only seems to read from information in Commerce.  I tried to pull in the data:

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

3) I tried making a global variable that used the email confirmation entry:

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

It seems the email is loaded and sent before the entry information.

Is there a work around to allow customers to add information or pictures from the CMS?

Thank you for your help,


texts:
I am having an issue whereby a form field is causing errors with Sprout Forms & Sprout Email to function.

I have found the root of the problem in that the field, fullName was causing errors, so changing it to contactFullName seemed like a good idea, as not to confuse matters with Craft's own field fullName.

When checking the logs after making these changes, sproutemail.log was still indicating an error related to the fullName field. Strange! I had changed this! It seems that there is a craft/storage/runtime/compiled_templates/03/****.php where *** is a long string filename used. Going to Settings -> Refreshing the compiled templates did not fix this either, so what can I do to refresh this compiled template to reflect my changes?

Thanks in advance.


texts: How can I load the templates from a module?

texts:
I'm creating a module that contains some predefined templates. How can I load them directly out of the vendor folder? I've tried doing

Event::on(View::class, View::EVENT_REGISTER_SITE_TEMPLATE_ROOTS, function(RegisterTemplateRootsEvent $event) {
    if (is_dir($baseDir = $this->getBasePath().DIRECTORY_SEPARATOR.'templates')) {
        $event->roots[$this->id] = $baseDir;
    }
});

That part seems to be working, cause if I dump it, I get:

[
    'my-module' => '/app/modules/mymodule/src/templates'
]

In my module, I have a templates/test.twig

But when I do mysite.com/test, I still get a 404.

I've also tried a different approach, in the routes.php, I put:

'test' => ['template' => '@modules/my-module/test'],

Still nothing.

Is there something I could differently?


texts: Preserve ICC color profile on image transformations

texts:
Is it possible to configure Craft to preserve the ICC color profile?

I did test JPG images saved in "sRGB IEC61966-2.1" profile and the files returned from Craft transformations are always saved in plain "RGB", oversaturated and just not as nice.

Imagick is installed.


texts:
I was wondering if it's possible to modify the status of an Entry within a plugin?

I've tried setting the status property but I get a readonly error.

$entry->status = $status


texts: There are no sites in the config file on nitro add

texts:
When i try nitro add command to they return "There are no sites in the config file" what should i do?
Unable to locate a webroot, setting to web.
Enter the webroot [web] web
Added tutorial.test to config file
Apply changes from config? [yes] yes
Mounting ~/Nitro/projects/tutorial to nitro-dev
Adding site tutorial.test to nitro-dev
Applied changes from /home/pedro/.nitro/nitro-dev.yaml
[sudo] senha para pedro:
There are no sites in the config file.


texts:
In craft 2 I had a simple plugin that I used to run some php code. I could call the function like this.

{{ craft.pluginname.functionname }}

However I have been unable to do the same thing in craft 3. I have created a new plugin for craft 3. Moved my functions to the main plugin file in src.

Is there a new way to call a function from a plugin in craft 3?

Ok got it figured out.

author below = root plugin path in vendor folder

In main plugin file had to add

use author\pluginname\variables\variablename;
use craft\web\twig\variables\CraftVariable;

Updated init event to

Event::on(
    CraftVariable::class,
    CraftVariable::EVENT_INIT,
    function (Event $event) {
        /** @var CraftVariable $variable */
        $variable = $event->sender;
        $variable->set('pluginname', variablename::class);
    }
);

Created variables file in variables folder src/variables/variablename.php

namespace author\pluginname\variables;
use author\pluginname\mainClassName;
use Craft;

class variablename
{
    //Custom Functions Here
    public function test() {
        echo 'Test';
    }
}

Then from a template I was able to use

{{ craft.pluginname.test }}


texts: Is it possible to fulfil orders partially? For instance when only two of four products are in stock, would it be possible to ship the two items immediately?


texts: Is there a better way than stacked if else

texts:
i am using a slider in my template, and depending on if the user filled out values in the craft matrix (slides can have up to 4 rows) i want to have twig compile only the necessary code. I am not sure if my attempt is way too long and it could be archived much easier. thanks a lot for the help

    {% for block in entry.slideitemtop %}
    {% set Bild = block.ImageSlideTop.first() %}
    {% if block.textCSlideTop is empty and block.textBSlideTop is empty and block.textASlideTop is empty and block.headlineSlideTop is empty %}

    {% elseif block.textCSlideTop is empty and block.textBSlideTop is empty and block.textASlideTop is empty %}

        {{ block.headlineSlideTop }}

    {% elseif block.textCSlideTop is empty and block.textBSlideTop is empty %}

        {{ block.headlineSlideTop }}
        {{ block.textASlideTop }}

    {% elseif block.textCSlideTop is empty %}

        {{ block.headlineSlideTop }}
        {{ block.textASlideTop }}
        {{ block.textBSlideTop }}

    {% else %}

        {{ block.headlineSlideTop }}
        {{ block.textASlideTop }}
        {{ block.textBSlideTop }}
        {{ block.textCSlideTop }}

    {% endif %}
    {% endfor %}


texts:
Is it possible to control if some content shows that's within a Matrix field if a lightswitch field on the entry is false.

I expect not as you're inside the matrix loop.

{% for block in entry.section3 %}
 ...
{% if block.applyButton %}
 ...
   {% if entry.applicationsClosed('not 1') %}
    {% for asset in entry.applyButtonDocument %}
     apply
    {% endfor %}
   {% endif %}
...
{% endif %}
....
{% endfor %}

I don't want to put the lightswitch within the Matrix as that would put it in an illogical place and would be needed to be switched multiple times.

It's being used as more of a global setting across the page to change various bits of content.


texts: Craft database and Github - using multiple computers. Issue

texts:
I have Craft set up and am using it for the first time. It seems to be ok. I am using git to back up my project to Github and push/pull it between computers as I partly work on my desktop (Windows) but also work on my laptop (Mac).

My issue is that when I pull to another PC often Craft database stuff is not the same. I lose changes made e.g. images that I’ve uploaded (even though they are in the actual Craft Image folder in my folders) or Matrix changes.
I didn’t realise this was happening and at first assumed my images weren’t updated because I’d forgotten to push to git before making changes on my laptop but when I went to pull my laptop changes to my Desktop last night and then tried accessing my Craft website through MAMP I got this error :

Craft\MatrixBlockModel and its behaviors do not have a method or closure named "myBlockSummary".

"myBlockSummary" is a matrix thing I added last night on my laptop. My sass and html and image files are moving correctly with git which is why Craft is confused(?), looking for something on the database (myBlockSummary) which I suppose isn’t there. The website works on the laptop that I pulled it from.

How can I easily continue using git and going between computers but have the database be included also?

This information on using Craft with git has not helped me really:
https://craftcms.com/help/craft-storage-gitignore
“So unless you have a way to keep the databases in sync between servers, there’s not a whole lot of point to sharing these files.”
Are they saying this is not possible?

Thank you for any help.


texts: Uploading Lottie animation files with images

texts:
For anyone who doesn't know what Lottie is, it is a video player created by the AirBnB team that lets you play vector animation exported from Adobe After Effects. It exports as json-files that you can easily add to any web project. This is easy to upload in craft cms or include in a static website. However sometimes I have images included in the animation that needs to be linked correctly in the json-file.

I was just wondering if anyone else have encountered this problem and found a solution?


texts: Freeform - jquery lookup to fill in addresses?

texts:
Looking for a plugin/script to autocomplete addresses in a form.

I've got a couple of Freeform forms that ask for name, address, and a bunch of other data.

And, I'd like it so that when a user starts typing in the address, it shows an auto-complete box underneath, and when you select, it fills in fields for city, state, etc.

I'm looking at Geocomplete, but this seems like a thing that others (probably lots of others) have already done, and I'd rather not reinvent the wheel.

I'm on Craft 2.9, and the regular version of Freeform (not pro).


texts: Custom Token Authentication with Craft 3 Login Form

texts:
I am building token auth system in Craft 3.
https://docs.craftcms.com/v3/dev/examples/login-form.html
I used this Login Form.

Now I am going to create my own token and save it in user profile.

First problem is to link this Form Submit Action to my custom action.
I can not find the controller linked to this action.

How can I customize my login system? Where can I find the controller for the built-in login form logic?


texts: Why is this Twig code generating large numbers of DB queries?

texts:
I have a Twig include that generates a News Archive side-bar. It works great, but I've just noticed that on a particular project it's contributing in the region of 800 DB Queries when caching is off.

What have I missed about the mechanics of the group filter? Because I can see no other reason why this should generate more than one query?

{% cache globally %}
    {% set allEntries = craft.entries.section('newsItems').limit(null).all() %}

News Archive

            {% for year, entriesInYear in allEntries | group("postDate | date('Y')") %}

                    {{ year }}

                        {% for month, entriesInMonth in entriesInYear | group("postDate|date('m')") | reverse(true) %}

                                    {{ entriesInMonth[0].postDate|date('F') }}

                        {% endfor %}

            {% endfor %}

{% endcache %}


texts: Listing categories alphabetically & total post count

texts:
How do I list all categories in use alphabetically? And how to get the total post count from each category?

Cheers


texts: Change markup depending on category of an entry

texts:
I am trying to output a news section, where I want to display the news categories as classes of the article. That works fine. But I also want to change the markup for a certain category out of the group mainly for responsive layout issues as I use Bootstrap as framework. How would I do this?

Here is my code so far:

{% for entry in craft.entries.section('news').limit(5).find() %}
{% set categories = craft.categories.relatedTo(entry) %}

    {% if category.slug == 'media' %} {# ------- I MEAN THIS LINE, slug or ID would be perfect #}

{{ entry.title }}

        {% set info = entry.info|nl2br %}

{{ info|raw }}

        {{ entry.body }}

    {% else %}

{{ entry.title }}

        {% set info = entry.info|nl2br %}

{{ info|raw }}

        {{ entry.body }}

            {% for image in entry.images %}

            {% endfor %}

    {% endif %}
{% endfor %}


texts: Is it possible to limit the number of times a user can be added to the same field across different entries?

texts: I want to make it so that each user can only be assigned once to a specific field across all entries. For instance, let's say we have a bunch of teams. A user can only be on one team at a time. Once assigned to a team roster, they should not be available to assign to another team. Is this possible?


texts: Is there any easy way (via the admin panel) to get a direct link for an asset?

texts:
A client wants to be able to get URLs for assets (for, eg. pasting a direct link into an email). For images and PDFs, "View file" works nicely (the file opens in a new browser tab), but for other file types which the browser can't display, they download instead. Is there any way of accessing the full URL of an asset from within the admin panel?

(The best I've been able to suggest is that they reconstruct the URL from the folder structure of their assets, so, eg. "Files > Documents > File.xls" becomes /assets/files/Documents/File.xls, but it would be great if there was a less fiddly way of getting that URL)


texts: Displaying errors on frontend user forms

texts:
I'm trying to get some feedback for the user on registration when the username already exists but I don't know in which object the errors are.

I use the form they provide in the docs:
https://docs.craftcms.com/v3/dev/examples/user-registration-form.html

Same for the forgot password form if the user doesn't exists in the system, I'm not able the provide the right feedback with this form:
https://docs.craftcms.com/v3/dev/examples/forgot-password-form.html


texts: 404 error if folder in public_html has same name as folder in craft/templates

texts:
I am currently transfering a live website to Craft CMS. I am trying to keep all URLs of pages and images exactly the same as the live version, because of all the pages and images cached in Google. Current URL's are, for example:

http://www.website.com/projects/projectname-1/pictures/picture.jpg

Where projectname-1 and picture.jpg are variable.

In Craft CMS I made a structure called projects. The slug/uri of the entries are setup so that they are the same as the original URL (for example www.website.com/projects/projectname-1)

I made an Asset source with the file system path set as projects/ and asset url as /projects/. When creating an entry within the projects structure, I made it so that when you're adding the images (custom field), it created the subfolder like: projects/{slug}/. The filenames of the images I am uploading are the exact same name as the live version. This all together works, because I am recreating all the same URLs: nice! :)

Now, here comes the problem. I also made a Single for the projects (www.website.com/projects/) page. When I create an index.twig file in craft/templates/projects/index.twig, I get a 404 error when visiting the URL. This is because I also have a folder called projects in my public_html. So, my question is: how do I also show craft/templates/projects/index.twig on my projects Single, while also keeping the original URLs intact (thus at the same time having a /projects/ folder in my public_html).

Hope it makes sense, thanks,

ET


texts: How do I update the state of lightswitches reliably using checkboxes on a frontend user profile form?

texts:
I've got a frontend user profile form that is successfully setting the values of custom fields in the backend except for some lightswitch fields I've added to my user profiles.

I have the following code which displays a checkbox on the frontend profile form and sets checked="checked" if that switch is "on" in the backend:

<div class="checkbox">
  <label>
    <input type="checkbox" id="memberShowEmailLink" name="fields[memberShowEmailLink]" value="1" {% if currentUser.memberShowEmailLink %}checked="checked"{% endif %}>
    Show a link to contact me via email in the member directory?
  </label>
</div>

If the lightswitch is set to "off" and I check the box on the frontend form and submit the form, the change is saved and the lightswitch flips to "on" in the backend.

However, if the lightswitch is already "on" and thus the box is already checked, if I uncheck it on the frontend form and submit the form, the change is not saved and there's no change in the backend.

What am I missing?


texts: How do you import tags from EE (solspace tags) along with entries?

texts:
Has anyone successfully imported tags from EE (solspace tags) along with entries? I installed this plugin but it seems to be really old and Craft must have changed a lot since then since it reflects even a different Schema and many deprecated methods. I refactored to work with simple entry fields but importing tags along with that seems a little trickier.

I think I am good if I can just figure out how to save relations for entries. VERY new to craft as in 2 days but this all seems familiar since I'm a Laravel guy.

I can figure this stuff out by following the trails but if someone else has tackled this or can give me quick feedback on using the services and models that would so super fantastical.


texts: onBeforeSaveUser validation for existing user but not new user

texts:
I am trying to validate first name and last name on my user registration form. I have tested and the following works for existing users when updating their profile via the form. Both use the onBeforeSaveUser event.

Any ideas why this wouldn't validate for registering users?

public function init()
{
    craft()->on('users.onBeforeSaveUser', function(Event $event)
    {
        craft()->businessLogic_events->onBeforeSaveUser($event);
    });
}

public function onBeforeSaveUser(Event $event)
{
    $user = $event->params['user'];

    if (empty($user->firstName))
    {
        $user->addError('firstName', Craft::t('Name cannot be empty.'));
        $event->performAction = false;
    }

    if (empty($user->lastName))
    {
        $user->addError('lastName', Craft::t('Last Name cannot be empty.'));
        $event->performAction = false;
    }
}


texts:
I am trying to exclude the current entry in a "Recommended Reading" section which works at level 1 with the ID tag, but I also need it to do the same at level 2 (children).

 `{% for entry in craft.entries.section('Thunder').level(1).id('not '~entry.id).limit(3).order('RAND()') %}`

The level 1 entry is the Article and the level 2's are the Chapters. The recommended reading section displays other Articles and should therefor exclude the level(1) article also when viewing the Chapters.

Should I use craft.request.getSegment(2) to exclude the current entry, but how do you write that conditional statement?

Url structures are:

/site/article
/site/article/chapter

Section: Structure


texts:
I set a matrix block field for a blog's channel and when I try to create a new entry, It is empty

But if I change the matrix field with another field, it works.

Anyone have an idea? Thanks in advance :)


texts:
I have a client that has a need for adding users without knowing their e-mail beforehand. Their wish is that when the user login for the first time, they are prompted to enter their e-mail, which also needs to be verified as normally by sending a activate link.

Is this possible to do?

Perhaps something hooked into the users.onBeforeSaveUser event?


texts: Add entry author meta field in entries listing table in CP?

texts:
In CP Craft Admin in the entries table view I d like to display some authors meta info.
How could I do that in my plugin?
I know public function modifyEntryTableAttributes(&$attributes, $source) and public function getEntryTableAttributeHtml(EntryModel $entry, $attribute)and but I cannot make it work.


texts: I've tried to integrate the video.js plugin for Redactor. It allows me to insert a YouTube embed (as expected) but the iframe code is stripped out on save. Using the latest Craft 2.5 build. Anyone experienced the same? Solutions?


texts: How can I disable relative dates in elements index?

texts:
In control panel, specifically when displaying elements table under any section, postDate and expiryDate values are in relative format i.e. Today, Yesterday, Monday, Wednesday, ..etc.

How can I disable that and display them in dates only?


texts: Is it possible to limit the level at which entries can be selected from within an entries field?

texts:
I have an entires field which is using a structure as a source.
The structure has 3 levels and I would like to be able to limit it so the user can only select entries at the second level.

I've had a look through the docs and at the field settings but it doesn't seem to be doable. If anyone knows a work around or a plugin which can do this that would be great. I wonder if it is possible to create a plugin to extend this field to do this if not?


texts: Craft 3 admin panel only accessible when web/cpresources is exectuable for everyone

texts:
I’m trying to move a local Craft 3 site to a local server (hosted on 1&1).

The website itself runs fine, but for some reason I can only access the admin panel when the web/cpresources folder has permissions set to 777, which I obviously don’t want. (EDIT: It also seems to work with 755, but the folder probably shouldn't be executable by everone, right?)

All other folders where Craft needs write access are set to 744, as per the install instructions, and as long as web/cpresoures are 755, everything else seems to work fine.

Does anyone have an idea what can be the issue and a possible solution here?

Unfortunately I don’t know which user PHP runs under, but as a standard web hosting setup, I would guess it should be able to write to the file system without open access for everyone, and again everything else seems to be working like normal.

UPDATE:

It only

I managed to get the user by running this code:

$username = posix_getpwuid(posix_geteuid())['name'];
$echo $username;

The reported user is the same as my account, meaning php should run as the same user that owns the files.


texts: Problem with the LinkVault plugin not finding file above root

texts:
Anyone had problems with LinkVault?

I’m storing downloads above the web root and using LinkVault to generate links to them. This works locally but on the staging server I get a PHP notice for an undefined variable in LinkVault_DownloadController.php on line 26.

Basically it’s getting a 404 because it can’t find the file and that line is trying to log the error message but throwing the notice.

What I don’t understand is that it’s working fine locally and I’ve done exactly the same thing on another site with no issues at all. Same hosting set up too.


texts: Cannot get asset from custom user field, with no-admin account

texts:
I would like to get a file of custom user field, which is "asset", and provide a link to the file for the user.

However, the asset file cannot be gotten.
The length of the asset field is zero.
In addition, this issue happens only the currentUser is not admin.
With admin account, the asset is gotten without any trouble.

Of course, the user has a permission to view the asset volume.

The asset volume has public URLs.
On the other hand, the asset folder is out of web folder, but I do not realy think it is the cause because the asset file can be gotten with admin account.

And, my Craft is ver 3.1.33.


texts:
I must be missing something or not understanding something.

I'm trying to build a module for an install, and I'd like to run the initial migration. So the module initial install migration for the DB lives in /modules/moduleName/migrations/Install.php.

Nothing I run from the CLI seems to work:

./craft migrate/up

Only sees what is in the root /migrations/ folder; seems counter-intuitive to have a migrations folder in my module if I have to manually move them.

./craft migrate/up --plugin=everyVariationOfAPossibleHandleItMightFind

Doesn't work ever, as the module is installed and works, but it isn't a plugin so I guess it doesn't see it somehow (looking in the wrong place in the file system I would bet).

./craft migrate/up migrationPath=@app/modules/moduleName

Craft CLI doesn't seem carry that Yii CLI param, so I can't specify a path.

What am I missing? How do others handle custom module migrations in Craft 3?


texts: How to pragmatically set registered user status to pending and then manually send activation email

texts:
I have 2 front end registration forms. One for normal users and one for admins. In each form I have a hidden input with a group value like so:

<input type="hidden" name="group" value="ypo">

In craft I have allow public registration checked and verify user address unchecked

Then I have a module that does two things:
One, it assigns new registrations to the correct group based on the hidden field and that part works like a charm, but I'll still post it here just in case:

Event::on(
        Elements::class,
        Elements::EVENT_AFTER_SAVE_ELEMENT,
        function(ElementEvent $event){
          // Check it's a front end request
          if (Craft::$app->request->getIsSiteRequest()) {
            if($event->element instanceof \craft\elements\User){
              $user = $event->element;
              if($event->isNew) {
                  $formName = Craft::$app->getRequest()->post('group');
                  if($formName==='ypo')
                  {
                    Craft::$app->getUsers()->assignUserToGroups($event->element->id, [1]);
                    logMessage('Assigning Member - id: '.$event->element->id);
                  }
                  if($formName==='yp')
                  {
                    Craft::$app->getUsers()->assignUserToGroups($event->element->id, [2]);
                    logMessage('Assigning Website User - id: '.$event->element->id);
                    $users =  Craft::$app->getUsers();
                    if($users->sendActivationEmail($user)) {
                      logMessage('Activation Email Sent');
                    }
                  }
              }
            }
          }
        }
      );

Two, it blocks new users from being activated like that:

Event::on(
          Users::class,
          Users::EVENT_BEFORE_ACTIVATE_USER,
          function (UserEvent $event) {
              if (Craft::$app->request->getIsSiteRequest()) {
                // Only trigger when request comes from the specified form
                $formName = Craft::$app->getRequest()->post('group');
                if($formName==='ypo' || $formName==="yp") {
                  logMessage('Activation Withold');
                  $event->isValid = false;

                }
              }
          }
      );

I based this code on Brandon's answer to  [a very similar question][1] and it works, in a sense it sets the status to pending, but...

[1]: How can I set new user accounts to pending status in a Craft 3 module? but added the safeguard that the code will only be triggered when the accompanying hidden form fields are present.

The problem

The problem is that whenever I want to activate the account,by emailing the activation code (manually or by my script), I get an error:

Return value of craft\web\twig\variables\UserSession::getRememberedUsername() must be of the type string, null returned

EDIT: error was due to having 'autoLoginAfterAccountActivation' => true in settings. Switching that off got rid of the error, but the activation still doesn't work.

What's even more weird is when I use the activation code from the admin panel, I'm then redirected to set your new password page instead of activation.

My log doesn't show that my script has been triggered, so it shouldn't prevent activation from link or email. Any help would be appreciated.

I did a lot of testing, If I remove EVENT_BEFORE_ACTIVATE_USER code and register a user, and then put it back in and send email, activation works. This means that setting craft\events\UserEvent::$isValid to false is permanent and can no longer be activated. Any idea why?


texts: Is there a plugin like Compressor for Craft 3?

texts: Is there are similar plugin for Craft 3 like https://github.com/sathoro/Compressor?


texts: Craft Commerce - How To differentiate between Shipping and Billing Addresses?

texts:
Is there any method to differentiate between a shipping and billing address in Commerce once a customer has gone through a checkout? I ask because if they come back to their account and want to review their attached addresses and edit them, we want to be able to display them as a Shipping Address and a Billing Address. But from the docs, it appears you can only loop through all addresses with no way to really differentiate them beyond their ID.

This is a pretty common scenario in B2B stores where there may be different shipping addresses for different outlets but one billing address for the head office.


texts: Craft 3 - Twig search query for entry with custom EntriesField containing disabled entry

texts:
I have a search form with 1 simple input (q)
I also have 2 sections: SECTION-A & SECTION-B
The search is for entries within SECTION A.
The entry I'm searching for contains a custom entriesField from SECTION B which can contain a posible disabled entry because they have an expiryDate. But they still need to be searchable when typing something the disabled entry contains. I can't figure out what to do with my query.
This is what i have so far: (works perfectly with an enabled related entry from SECTION B)
{% set entries = craft.entries.section('SECTION-A').search(searchParam).orderBy('score').all() %}

what I am trying:
{% set entries = craft.entries.section('SECTION-A').search(searchParam ~ ' status: any').orderBy('score').all() %}

But this is not working, can anybody help me out here? :)
Screenshot clarification:

When searching october (expired entry from SECTION-B), it is NOT showing me results.
When searching november (entry from SECTION-B), I get the results I am expecting

some technical information:

PHP version  7.3.22
Database driver & version    MariaDB 10.3
Craft edition & version  Craft Pro 3.5.14


texts: Where exactly to update the composer.json to install an older version of Craft 3?

texts:
I'm trying to install a non-current version of Craft 3, and several pointers on using composer to do this say to "update the composer.json" line with the version you want.
Can someone please explain exactly where this file should be, and/or the steps to do this, as I cannot make head-nor-tail of this process.
Where can I download previous versions of Craft?
https://craftcms.com/knowledge-base/downloading-previous-commerce-versions


texts: Can I set the value of a Color Field to a hex value? Or only if the particular browser's color picker supports this? Maybe this is a feature request: please let us get and set color values in hex.


texts:
I want to be able to get the slug of my news section dynamically by searching for its handle.
Slugs tend to change during the development phase, but the handle doesn't. That's why I want to hard code the news handle in my template to refer to the news section from any other page.
How to do such a query?


texts: Get PDF file from Assets Folder - Element API

texts:
I have a PDF folder within assets and having trouble accessing the file path once chosen by the user.

To get something like an image from assets within a matrix I do something like this which works:

'image' => $block->image[0]->url,

I have tried similar code however it seems url is not available?

'downloadablePDF' => $block->downloadablePdf[0]

I need to return the URL so that I can pass the URL to a React Component to make the pdf downloadable.

Here is my full code to fetch data from a matrix block:

function articles($array) {
    $articles = [];
    foreach ($array as $block) {
        switch ($block->type->handle) {
            case 'article':
                $articles[] = [
                    'heading' => (string) $block->heading,
                    'subheading' => $block->subheading,
                    'text' => (string) $block->text,
                    'backgroundImage' => (isset($block->backgroundImage)) ? $block->backgroundImage[0]->url : '',
                    'downloadablePDF' => $block->downloadablePdf[0],
                    'videoUrl' => (isset($block->videoUrl)) ? $block->videoUrl : '',
                    'linkUrl' => (isset($block->linkUrl)) ? $block->linkUrl : '',
                    'size' => (isset($block->size)) ? $block->size->value : '',
                    'style' => (isset($block->style)) ? $block->style->value : '',
                    'verticalTextAlignment' => (isset($block->verticalTextAlignment)) ? $block->verticalTextAlignment->value : '',
                ];
            break;
        }
    }
    return $articles;
}


texts: I have a video Object with a duration property formatted in SCORM 2004 time format. Like so: PT51M55S. How do i convert this into a human readable time format like: 51:55? date() does not seem to work obviously.


texts: Update record definition after plugin is already installed

texts:
If you have a plugin installed with its own tables and you want to add some extra database fields to the table, what is the process for this?

Craft will create database tables using records on installation of the plugin, but what about after this? If I update the record definitions is there a way to trigger Craft to update the table or do I have to add the fields through MySQL?


texts: Problem with data hash only storing last entry in loop

texts:
1: I'm creating a data hash object and then looping through a collection of entries to store the results of various macros in it:

{% set data = {} %}
{% set people = craft.entries().section('people').all() %}

2: I'm setting a reference to each entry and then merging the content compiled into my data object:

{% for person in people %}
    {% set i = loop.index %}

    {# get and set key|values #}

     {% set data = data|merge({
        i: {
            "key": value,
            "otherKey":  otherValue
        }
    }) %}
{% endfor %}

3: And then I'm looping through my data object for output:

{% for row in data %}

        {{ row.key|raw }}
        {{ row.otherKey|raw }}

{% endfor %}

The structure of the output at stage 3 is fine, but it's only resulting in 1 row out of 45 people entries.

What am I doing wrong at 2 please?


texts:
When an entry is created and saved in a locale the corresponding entry is created for other locales using the original title. However, when the title of the locale which needs translating is edited the slug isn't auto generated from the new localised title and remains in the original language.

Of course, the slug can be manually edited but unfortunately the likelihood is that users won't bother, or forget, meaning that the urls for entries won't be localised.

What would be ideal is that on the first edit of the localised version that the slug is auto generated from the title as it is for the initial entry. Is this possible either via a plugin or could it be considered in a future version?


texts: Element API: Get Entries Related to Category with Query Parameter

texts:
I'm using the Element API Plugin to create an API, with which I want to get entries related to one category, but dynamically with the category set in the Url.
What I have so far in the config/element-api.php:
<?php

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

return [
  'endpoints' => [
    'api/projects.json' => function() {
      $projectCategory = \Craft::$app->request->getQueryParam('projectCategory');

      // dump for test purpose
      var_dump($projectCategory);

      return [
        'elementType' => Entry::class,
        'criteria' => [
          'section' => 'projects',
          'relatedTo' => "{$projectCategory}",
        ],
        'elementsPerPage' => 2,
        'transformer' => function(Entry $entry) {
          return [
            'title' => $entry->title,
            'url' => $entry->url,
            'jsonUrl' => UrlHelper::url("projects/{$entry->id}.json"),
            'thumbnail' => $entry->projectThumbnail,
            'description' => $entry->projectDescription,
            'credits' => $entry->projectCredits,
          ];
        },
      ];
    },
  ],
];

When I go to http://domain.test/api/projects.json?projectCategory=category, I get the right value dumped, but the relatedTo doesn't seem to work. I get zero entries, although there are some related to a specific category.
Am I doing something wrong here?


texts: How do you "pin" a flash error message in the CP?

texts:
It's possible to generate a "flash" error message at the top of the control panel like this:

craft()->userSession->setError('Your custom plugin error message.');

The message appears at the top of the control panel when the page loads, but then fades away after a few seconds. Is there any way to "pin" the message to the top of the page, so it stays indefinitely?


texts: Routing generic urls to sections or structures urls

texts: I have a structure setup with parents and children.  Can a route be setup in the CP to route a generic url to a specific parent or child of the structure.  For example I have a blog landing page that is a child of the structure.  Can a route be setup, so when a user enters at /blog it takes them to that landing page?


texts: Uploading animated GIF outputs only first frame

texts:
I've updated everything to the latest version and the result of uploading an animated GIF is just the first frame of the animated GIF.

Any ideas on why animated GIFs aren't working? Is there a way to disable image transforms for animated GIFs or GIFs in general?

PHP 5.4.45-0+deb7u1
ImageMagick 6.7.7-10
Craft Pro 2.4.2692

Thanks!


texts: Uploaded assets not saving in specified local folder

texts:
I have a local asset folder defined with name 'Local storage' file system path ../public/cms/images/, and URL /cms/images/.

I create an Assets field named 'Hero image', not restricted to a single folder, with source 'Local storage', and default upload location 'Local storage' with path heroes/{slug}/.

I'd expect uploads for Hero image to land in the /public/cms/images/heroes/{slug} folder. When I do upload an asset, this folder is created, yet the asset lands in the root /public/cms/images folder.

Why might this be?


texts: Smart Maps problems displaying static maps

texts:
I'm trying to output a static map from a smart map field in a matrix. I can output a dynamic map with no issues, but the static map code isn't working.

Here is my code:

{% set locations = entry.locationsAndNotes %}
{% set options = {
    width: 370,
    height: 208,
    zoom: 16,
} %}
{{ craft.smartMap.img(locations[0], options) }}

The url it outputs looks like this: https://maps.googleapis.com/maps/api/staticmap?visual_refresh=true&key=myKey&scale=2&center=-48.876667,-123.393333&size=370x208&maptype=roadmap&zoom=16
Pasted into a browser, i get an error that the API server rejected my request because it is missing the size parameter.

If I change all of the &amp to &, an image loads, but it's just a blank blue map.

It seems like this should work, since I can render a dynamic map, but I'm not sure if it's an issue with my code, or the plugin, or the api.


texts: Sending an e-mail to current user in FeedMe hook

texts:
I have made a custom module that allows a user to upload a CSV and import it using a FeedMe feed. This all works fine, however I want to send an e-mail to the user when the import has completed.

I have this so far, but realised it doesn't work because the event doesn't have access to the user session:

Event::on(Process::class, Process::EVENT_AFTER_PROCESS_FEED, function(FeedProcessEvent $event) {
    $email = Craft::$app->getUser()->getIdentity()->email;
    if ($event->feed->id === getenv('USER_FEED_ID')) {
        $message = new Message();
        $message->setTo($email);
        $message->setSubject("Import complete");
        $message->setHtmlBody('Data has been imported successfully');
        $message->send();
    }
});

I've been scratching my furry head but can't think of a solution, is there any way to do this?


texts:
I have a navigation like this:

{% set navi = craft.entries.id('2, 4, 5, 6' ).order('id asc') %}

    {% for entry in navi %}

{{ entry.naviTitel }}

    {% endfor %}

This results in something like:

Home
Projects
About
Contact

Now under Projects (Wich is a Single entry) are entry pages like this:

url/projects/project_entry_1
url/projects/project_entry_2

Now what I'm trying to achieve is that when viewing a project_entry, the nav link "Project" should have the class active which is not the case right now. Is this somehow possible with this navi markup or do I have to write something like this.

I taught about writing a conditional {% if url_segment 2 == project %} but that doesn't work because this would give all links the class active and since I have a multi-language installation segment_2 is not always the single slug.

What is the prettiest way to achieve this?

Thank you.


texts: Install MySQL stored procedure to database on plugin install in Craft 3

texts: I am trying to add a MySQL stored procedure to the database on plugin install in Craft 3.  I currently have an install migration calling a function from the safeUp method. In this function I am using Craft::$app->getDb()->createCommand(" DELIMITER $$ CREATE PROCEDURE ...")->execute(). However this does not seem to do the trick.


texts: Recently changed the URL format for a section. Now I have a red circle in the upper right and an error message of "resaving blog entries - failed". Trying again results in same error. Any ideas what could be wrong?


texts:
On a single entries page I have the following code:

    {% set params = {section: 'databytes', order: 'title'} %}
    {% set prevDatabyte = entry.getPrev(params) %}
    {% set nextDatabyte = entry.getNext(params) %}

    {% if prevDatabyte %}

    {% endif %}

    {% if nextDatabyte %}

    {% endif %}

I am wanting to somehow only paginate through entries that are tagged with the same tag maybe by passing that into the params object is that possible?


texts:
I have a user model that contains several Matrix fields, but for the sake of this question I'll just discuss one of those fields.

The field we'll discuss is a phoneMatrix.

The phoneMatrix data can come in from multiple sources. What I mean is, there is no one place where a user can add/update/delete phone numbers. There will be a user profile page, but other applications on the website will allow for phone numbers to be saved/added/deleted. Given this, it is not optimal for me to use the method:

craft()->users->saveUser($userModel)

The reason it is not optimal is because, for whatever unholy reason, Craft assumes that if matrix data does not exist after being set from POST that the missing data should be deleted. This assumption is not conducive to our process, yes we could pull all phone numbers for each save/update but that's unnecessary overhead.

If anyone has advice on alternative ways to save user data that avoids this problem it would be very much appreciated. I'll be looking into it on my own and if I find an answer I'll make sure to post it!

Thanks in advance for any help!


texts: Why won't the values of an editableTableField show up in my template?

texts:
I'm still trying to process my csv data as mentioned in a former question. But I'm struggling with another part of this right now.

I decided to implement a custom field type which should display the data from my csv in a table to make it further editable for editors. The problem is that I don't even get something shown in this table even without processing a csv file before.

I tried something really simple, at least I thought it was...

public function getInputHtml($name, $value)
{
    $id = 'test';
    $cols = array(
        'Sample' => array(
            'heading' => 'Heading',
            'type'    => 'singleline'
        )
    );

    return craft()->templates->render('csvImport/csvimport', array(
        'name'  => $name,
        'value' => $value,
        'id'    => $id,
        'cols'  => $cols,
    ));
}

This works until the point of saving the data. Craft stores everything into database as a string. No matter how many cols I use, it will always result in a string which looks like this:

"{"1":"Sample":"The entered string"}}"

This is what craft stores in the database, so at least the data is processed. But how the pencil do I get this stuff to show up in the table of my template?

If you have any other idea how I could solve my problem, please let me know!

UPDATE:

        {% for col in cols %}
            {{ col.heading ? col.heading : ' ' }}
        {% endfor %}
        {% if not static %}

        {% endif %}

    {% for rowId, row in rows %}

            {% for colId, col in cols %}
                {% set cellName = name~'['~rowId~']['~colId~']' %}
                {% set value = (row[colId] is defined ? row[colId] : null) %}
                {% set textual = (col.type in ['singleline','multiline','number']) %}

                    {%- if col.type == 'select' -%}
                        {% include "_includes/forms/select" with {
                            class:    'small',
                            name:     cellName,
                            options:  col.options,
                            value:    value,
                            disabled: static
                        } only %}
                    {%- elseif col.type == 'file' -%}
                        {% include "_includes/forms/file" with {
                            class:    'small',
                            name:     cellName,
                            value:    value
                        } only %}
                    {%- elseif col.type == 'checkbox' -%}
                        <input type="hidden" name="{{ cellName }}">
                        <input type="checkbox" name="{{ cellName }}" value="1"{% if value %} checked{% endif %}{% if static %} disabled{% endif %}>
                    {%- else -%}
                        <textarea name="{{ cellName }}" rows="1"{% if static %} disabled{% endif %}>{{ dump(value) }}</textarea>
                    {%- endif -%}

            {% endfor %}
            {% if not static %}

            {% endif %}

    {% endfor %}

I guess this is the relevant part for the ouput of my values.


texts: Add, remove, and append entries to an entries field via frontend form

texts:
I'm making a one-button form, to add an entry to an entries field.
Adding seems pretty straightforward, but it overwrites any previous entry that occupied the entries field. How would I append an entry to the entries field, or remove an entry?

<form method="post" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="entries/saveEntry">
  <input type="hidden" name="entryId" value="{{ entry.id }}">
  <input type="hidden" name="redirect" value="{{currentUrl}}">
  <input type="hidden" name="fields[tournamentTeams][]" value="{{team.id}}">

  <input type="submit" value="Add {{team.title}} to this Tournament">
</form>

My guess is, I will have to populate the entries field input value with the already-added entries to append the entry, and do the same kinda deal upon removing the entry- no idea how I would detect and remove the entry though!


texts: Categories field limit doesn't disable Add a Category button

texts:
I set the Branch Limit for a Category Field Type to 1, but after adding one category, the Add a Category button is still active.

Shouldn't it be disabled after reaching the limit?

Thanks!


texts: How is conflicting asset filename created

texts:
I upload files on the frontend using AJAX requests to actionUpload controller. When file is uploaded, I immediately display it using filename returned by controller.

In case if filename conflict, the duplicate file is created, with a name like something_200518_221543.jpg. How can I retrieve this duplicate filename, so I can display this file too? In control panel, this duplicate filename is somehow appended to the page, but I don't know how - there is no request that returns this new filename from backend.


texts: Automatically create users from http header

texts:
Bit of an awkward one.

The client wants a system where they send us a link e.g. mycraftsite.com?userid=abc123 and from there we need to populate the user table.

I am new to craft but I am assuming the correct way is to use a plugin, grab the header data and somehow insert it using a hook, but I don't see any available for before the site renders.

Can anyone help point me in the right direction?


texts: What's the best place to store and load static data for plugins?

texts:
I have static data that my plugin requires as an array (multidimensional with 100s of items), it doesn't need to change and it seems overkill to store in a database and not appropriate as just arrays in my code.

Options I have considered:

Json files - load them in
In the config file

Which is best and is there a more appropriate way to store access?


texts: Is there a way to remove or filter out duplicate entries?

texts:
I have imported some data for a client, and it turns out there are some duplicates in the csv-files.

Is there an easy way to remove or filter out duplicates, either in my entries-query or in my template?

My query looks like this now

{% set dealers = craft.entries({section:'dealers'}).order('dealerName') %}

Thanks!


texts: Is there a better way to make tables in Craft?

texts: I'm using the table function built into Redactor, and all my tables are coming out with the minimum width possible, without any padding between columns. How do I modify how Redactor builds its tables?


texts: Is Craft Suitable for Large Public Body website

texts:
I have used craft for a few medium sites sites and I love it.
Would Craft be capable of running a large public body website which would be updated with news regularly and have a wealth of information on the wide range of services provided - and likely to be a large number of documents needing accessed.
On a rough estimate there could be 7-8 structures and maybe 10 channels.
There will be a small eCommerce requirement on the site.

Will Craft handle this all ok?
Is there any limitations?

Don't want to be running into the problem of developing the site then at launch it and it not being able to cope.


texts: Pass URL parameter through General Config file

texts:
This may sound a little odd so let me explain what's going on.

In my current setup I have allowed new users to sign up. I want these users to follow this flow:

Fill up sign up form and submit
Gets redirected to page that warns them of activation email
User opens email, clicks on link and is forwarded to his/her profile page

So far I've been able to do this without any problems. However, I would like to be able to welcome the user when the account is activated without using a new template.

In this moment 'activateAccountSuccessPath' is set to the profile page, let's call it 'members/profile' I would like to pass a parameter so that I can detect if the account is being activated for the first time and therefore should display a message, e.g.: 'members/profile?activated=true'. As of now, this isn't possible because it looks for the template with that name, not recognizing that it has parameters.

I would like to use this same feature for other variables such as 'setPasswordSuccessPath', which would take you back to the login page, but displaying a message.

If it's impossible to pass arguments this way, how would you recommend going about it?


texts: Contact Form Required Fields Plugin – formEntry error

texts:
Has anyone experience with the ContactFormRequiredFields plugin? It works fine until the send button is pressed. It brings up an "Undefined variable: formEntry" error. When I look into the plugin I see that "formEntry" is connected to "formId". But what goes wrong?

        ...

        $formId = craft()->request->getPost('formId');
        $formId = craft()->security->validateData($formId);

        /**
         * Get the form entry using the ID
         */
        if ($formId)
        {
            $formEntry = craft()->entries->getEntryById($formId);
        }

        ...

Stack trace:

#0  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/etc/web/WebApp.php(693): CApplication->handleError(8, "Undefined variable: formEntry", "/var/www/vhosts/tonartmusikschule.at/httpdocs/craft/plugins/cont...",
#1  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/plugins/contactformrequiredfields/ContactFormRequiredFieldsPlugin.php(48): Craft\WebApp->handleError(8, "Undefined variable: formEntry", "/var/www/vhosts/tonartmusikschule.at/httpdocs/craft/plugins/cont...", 48, ...)
#2  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/framework/base/CComponent.php(567): Craft\ContactFormRequiredFieldsPlugin->Craft\{closure}(Craft\ContactFormEvent)
#3  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/plugins/contactform/services/ContactFormService.php(73): CComponent->raiseEvent("onbeforesend", Craft\ContactFormEvent)
#4  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/plugins/contactform/controllers/ContactFormController.php(139): Craft\ContactFormService->onBeforeSend(Craft\ContactFormEvent)
#5  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/framework/web/actions/CInlineAction.php(49): Craft\ContactFormController->actionSendMessage()
#6  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(array("p" => "anmeldung_index"))
#7  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/framework/web/CController.php(286): CController->runAction(CInlineAction)
#8  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(CInlineAction, array())
#9  /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/framework/web/CWebApplication.php(282): CController->run("sendMessage")
#10 /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/etc/web/WebApp.php(836): CWebApplication->runController("contactForm/sendMessage")
#11 /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/etc/web/WebApp.php(287): Craft\WebApp->_processActionRequest()
#12 /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#13 /var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/index.php(62): CApplication->run()
#14 /var/www/vhosts/tonartmusikschule.at/httpdocs/public/index.php(19): require_once("/var/www/vhosts/tonartmusikschule.at/httpdocs/craft/app/index.ph...")


texts: How can I loop through a Channel entries asset folder?

texts:
Basically, for every entry that I add to my 'Portfolio' channel, it creates a sub-folder inside assets/portfolio.

For example I have:

assets/portfolio/entry-one
assets/portfolio/entry-two

On my portfolio page, for each entry I want to display the first image from its asset folder and also get the url of every image in the folder.

Can anyone think of a solution that would allow me to do this? Can't figure out how to target each individual folder.  I know you can target folders by ID, but unless this can be somehow done dynamically in a loop it will not suit this situation.


texts:
I'm trying to get Preparse Field for Craft to work on some responsive images set up with Imager for Craft, but I'm not having much luck, as it's still only generating the cached images on page load and not when the client saves the image.

This is my image code in the twig template. Can someone explain how to setup the preparse plugin with it as the explanation on the plugin page is a bit too brief?

{% set image = category.countyHero.first() %}
{% set transformedImages = craft.imager.transformImage(image,
    [
            { width: 1920, ratio: 3/1, jpegQuality: 75 },
            { width: 1366, ratio: 3/1 },
            { width: 1024, ratio: 3/1.5 },
            { width: 750, ratio: 4/3, jpegQuality: 60 },
    ],
    {
            format: 'jpg',
            allowUpscale: false,
            mode: 'crop',
            jpegQuality: 80,
            position: image.focusPctX ~ '% ' ~ image.focusPctY ~ '%',
            interlace: true
    }
) %}
{% if image | length %}
<img class="img-responsive"
     src="{{ transformedImages[1].url }}"
     sizes="100vw"
     srcset="{{ craft.imager.srcset(transformedImages) }}"
     alt="{{ image.title }}">
{% endif %}