texts: Recommended way to organize product types and fields in Craft Commerce

texts:
I am setting up a Craft CMS site with Craft Commerce for a B2B-customer.

Here is a little excerpt of their product type hierarchy:

Textile

Sewing machines
Heavy Duty Machines
Furniture machines
Knitting machines
Scissors
Thread

Ergonomics

Chairs

Each product type have their own set of taxonomies that describe the product. For Sewing Machines, it could be:

Area of usage
Sewing machine type
Number of needles

For scissors it could be:

Scissor type
Left or right hand?

An example

Take the following screenshot from Gearbest.com:

I've outlined the taxonomies.

Questions

How should I organize the product hierarchy? (Using Categories?)
Considering that the taxonomies differ between product types, how should I assign the different taxonomies to products (System Support, Features, Application, Brand from screenshot)
Should each of the types I've described here become individual Product Types in Craft Commerce? (Heavy Duty Machines, Furniture machines, Chairs, Thread etc)


texts:
I am trying to make my image grid form out dynamically. I got it kinda working, But I need to figure out how to make my grid rows dynamic. I am kinda forcing it to start a new row at every 4th item right now, but dossent feel like the right way to do it.

This is my code:

 {% for entry in craft.entries.section('knapperForside').limit(50).find() %}

                    {{ entry.bilde }}

{{ entry.title }}

{{ entry.title }}

  {% endfor %}


texts: Storing a Matrix block data in a variable

texts:
Having an issue searching a Matrix field for a block with a certain value and storing the entire block in a variable. Right now it only seems to be storing the location value. The navigations field is a Super Table.

{## looping through matrix blocks works ##}
{% for block in siteNav.navigations %}

    {{ block.location }}

    {% for row in block.navLinks %}
        {{ row.label }}

    {% endfor %}
{% endfor %}

{## set variable via search matrix block only selects location field ##}
{% set utilityNav = siteNav.navigations.location('utility').limit(1) %}

{{ utilityNav.location }}

{% for row in utilityNav.navLinks %}
  {{ row.label }}

{% endfor %}


texts: Is it possible to use the MySQL LIKE directive in an ElementCriteriaModel?

texts:
In a plugin, I'd like to pull all Assets with filenames starting with a certain string (the $prefix variable, in the below examples).

It's possible to do this with a custom DbCommand:

$results = craft()->db->createCommand()
    ->select('assetfiles.*')
    ->from('assetfiles assetfiles')
    ->where(array(
        'like',
        'assetfiles.filename',
        $prefix.'%',
    ))
    ->queryAll();
$assets = AssetFileModel::populateModels($results);

However, I'd like to do this using an ElementCriteriaModel. The below doesn't work:

$assets = craft()->elements->getCriteria(ElementType::Asset, array(
    'filename' => 'LIKE "'.$prefix.'%"',
    'limit' => null,
))->find();

In the above example, is the syntax off, or is not possible to use LIKE in an ElementCriteriaModel parameter?


texts: Setting relative path to ElementAPI in PHP

texts:
I need a few small bits of data from Craft in a PHP file. It’s a really small task, so I don’t want to delve into writing plugins or anything hardcore.
It seemed to me the simplest way to approach it would be to use the ElementAPI plugin and then read the resulting JSON in the PHP (this is being tested using MAMP):
<?php

// ID of entry I want
$id = 563;

// Grab data from ElementAPI
$url = "http://localhost:8888/myApi/" . $id . ".json";
$data = file_get_contents($url);
$json = json_decode($data);

// output data
echo "Entry title: " . $json -> title;

?>

This works perfectly.
However, that hard-coded URL does not sit well with me.
I tried grabbing the directory using a few variations, eg:
$url =  __DIR__ . "/myApi/" . $id . ".json";

That gave me the correct path to the file, but the JSON isn’t generated — presumably because without the hard-coded address it’s not running the file through MAMP, so the PHP isn’t running.
I surely cannot manually update the URL every time I deploy a revision — that seems like a disaster in the making.
TIA for any solutions.


texts: How can I create a simple loop through entries in a category?

texts:
I have a category set up and have added entries to it. How do I loop through these entries, and output just the title of each entry?

Serious noob here but trying to learn, any help would be gratefully received.


texts: How to display the featured image on a Commerce product:

texts: How do I display the featured image on a Commerce product:


texts: Add a user to a userfield when there's a pending user on there

texts:
I have this code to save a new user onto a userfield on another user:

    $employees   = $currentUser->employees->ids();
    $employees[] = $employee->id;
    $currentUser->getContent()->setAttributes(['employees' => $employees]);
    if (!craft()->users->saveUser($currentUser))
    {
        Craft::dd($currentUser->getErrors());
    }

Which works fine, however if there's a pending user in the employees field it's not returned in the ids() array. How do I get all user ids from the employees field, not just active users?

Edit: got it:

    $employees   = $currentUser->employees->status('*')->ids();


texts: How do I create an external transformer class when using the ElementApi plugin?

texts:
I've been trying to clean up my elementapi.php file, and one very important step in making it more DRY is to have reusable transformer classes.

But I cannot seem to get it to work, the following gives me a blank page.

So far in my elementapi.php file I have the following.

'api/articles' => function() {
// I have also tried to place this line at the very top of the file.
require_once craft()->path->getConfigPath().'transformers/EntryInfoTransformer.php';

            'criteria' => [
                'section' => 'blog',
                'order' => 'postDate desc',
            ],

            'elementsPerPage' => 5,
            'elementType' => 'Entry',
            'transformer' => new EntryInfoTransformer(),
        },

and my EntryInfoTransformer.php file has

<?php

require craft()->path->getPluginsPath().'elementapi/vendor/autoload.php';

use League\Fractal\TransformerAbstract;
class EntryInfoTransformer extends TransformerAbstract{
    public function transform(EntryModel $entry) {
        return [
            'id' => $entry->id,
        ]
    },
}

I don't get any errors, nothing in either the php or craft logs, just a blank while page. This has been tested on php 5.5 & 5.6. Site runs normally otherwise.


texts:
I currently have a Craft 2 site deployment with a translations folder and a en_gb.php translations file.

I would be able to use expressions like this: {{"visualization"|t}}

However, this does not work in Craft 3. What is the new format for translation in Craft 3?


texts:
In my order PDF template I have an image that shows when I preview the template as a web page but not in the generated PDF. I’ve tried SVG, PNG and JPEG.

If I use a relative path I get the error Image not readable or empty. With an absolute path I get DOMPDF_ENABLE_REMOTE is set to FALSE.


texts: Environmental variable coming back as literal braces

texts:
I have my general config file set up as follows:

return array(
  'localhost' => array(
  'devMode' => true,
  'environmentVariables' => array(
    'baseUrl' => 'http://localhost:8888/path/to/site/'
  )
 );

Then, I have an asset source set up as follows:

File Base Path: assets/img/general/
URL: {baseUrl}assets/img/general/

The assets pulled within a template get this error:

GET http://localhost:8888/path/to/site/%7BbaseUrl%7Dassets/img/headers/image.jpg 404 (Not Found)

I've used this format with several other sites before, and haven't had a problem. Does anyone have any suggestions?


texts: Building a nav from the top level page of a structure

texts:
There are several questions like this already but none seem to cover my use case. I have a structure that looks something like this:

Landing Page 1
- Case Studies
-- Case Study 1
-- Case Study 2
-- Case Study 3
- Sub page
- Sub page
Landing Page 2
- Case Studies
-- Case Study 1
-- Case Study 2
-- Case Study 3
- Sub page
- Sub page

If I'm in any child of the 'Landing Pages' I want to create a nav (as per the docs) but I cant' seem to get all of the pages I need. I can easily get the top level 'landing page':

entry.getAncestors().level(1).first()

I can then get the descendants separately:

entry.getAncestors().level(1).first().getDescendants()

However, I want a single ElementCriteriaModel with everything from the 'landing page' down in it.

Is this possible?


texts: Like all other CMS's Craft Commerce doesn't have a Cash On Delivery payment method by default. How can we add or create a COD method ?


texts: How do asset and entry urls in rich text fields change with the environment?

texts:
If I have a rich text field containing a link to an asset and I create the link on my development server sample.craft.dev, the html in the rich text field contains this:

the file

If I then move the database to my staging server stage.sample.com, the html in the rich text field now magically contains the new url:

the file

How does that happen?

If the html in the rich text field on the development server instead contains this:

<select class="jumpMenu js_jumpMenu">
  <option value="">-- select brochure --</option>
  <option value="http://stage.sample.com/uploads/pdfs/file.pdf#asset:969:url">The File</option>
</select>

Then the url is not rewritten. Why is that?


texts:
I insert data into database table using query builder:

$command = Craft::$app->db->createCommand()->insert('test2', array());
$command->execute();

How can i retrieve id of newly inserted db row?


texts: Is it possible to use the assets modal on the front end?

texts:
Part 3 of a 3 part question:

I am creating a proof of concept for a client in Craft where the client's customers can manage projects from the frontend of a Craft install.

A missing piece to the puzzle for full management is being able to give the user access to the assets modal and asset relationship field so they can better manage the files that are associated with the entry. Ideally they would be able to edit a field with existing content with the ability to associate new files or remove them all together (while still preserving the file in the upload directory, for this use case).

Is it possible to access the asset modal and manage the relationship field from the front end?


texts: How to output first segment title/channel name of entry?

texts: For example, I have channel entry https://site.dev/news/2017/test and I would like to output "News" section name on entry page.


texts:
I am trying to list the months (January, Febuary etc) between two dates.
I have a start date: 5/4/2015 and an end date: 9/25/2015.

Using range I am able to return the month numbers, but just can't figure out the correct syntax to convert 5 into May.

Here's what I've got so far, maybe there is a better way all together?

TWIG

{% set startMonth = craft.plugin.getStartDate() %} // returns 5/4/2015
{% set endMonth = craft.plugin.getEndData() %} // returns 9/25/2015

{% for month in range(startMonth, endMonth, 1) %}
    {{ month }}  // returns 5 6 7 8 9
{% endfor %}

I've tried doing something like: {{ month|date('F') }} but that returns December for each result.

I'll eventually need days within this month range, but I am hoping from this I can figure that out.


texts:
I'm confused about the new .one() argument in craft 3

If I want to grab all entries I write:

{% for entry in craft.entries.section('thing').all() %}
  {{ entry.title }}
{% endfor %}

Alls is nice and well. 20 something entries are returned.

But I want to fetch only the latest entry so instead of .all() I use .one() (which was formerly .first())

But when I write:

{% for entry in craft.entries.section('thing').one() %}
  {{ entry.title }}
{% endfor %}

It returns the error:

  Impossible to access an attribute ("title") on a string variable
  ("3").

When I write:

{% for entry in craft.entries.section('portfolioEntry').limit(1).all() %}
  {{ entry.title }}
{% endfor %}

Then it works. But that's not the right way, is it?


texts: Extending options for different plugin types?

texts:
This may be more of a feature request but I was curious if this is on the roadmap.

I have seen a lot of plugins that are more of a “utility” than something users would interact with. For example look at Audit Log, Dump and other miscellaneous.

Currently the only real option that exists for plugins is hasCpSection. It would be really helpful as the plugin ecosystem continues to grow to have plugins that are a “utility” or “settings” with the option to show on the settings page in the Control Panel.

Naming aside as this is just a quick thought, I was thinking something along the lines of this:

public function isSettingsPlugin()
{
    return true;
}

public function getSettingsPluginCategory()
{
    return Craft::t(’Tools');
}

public function getSettingsIconPath()
{
    // return the path to the settings icon
}

Any thoughts on adding the ability to have plugins as a settings or utility?


texts: Activate correct locale upon front-end entry

texts:
Is there any way, upon creating new entries via front-end form, to not have all locale versions of those entries active?

I’d like to think I could just set something like
<input type="hidden" name="locale" value="en_us”>


texts:
I'm documenting Craft permissions for internal use but there are some permissions that I'm not clear on.

"Access the site when the system is off" What system?
"Publish live changes" How can you do that?


texts:
This question is related to: SuperTable Returning Unexpected Results w/ Template, which is still unresolved.
In essence, Im trying to return the results of a Supertable at two different points in my template.
{% set featuredContributorsGrouped = entry.contributors
    .search('terms')
    .all()
    |group('contribution[0]')
%}

Appears in my template first, but when I try and reuse entry.contributors.all, it seems like it is already filtered by terms. This happens even if I recast entry as another temporary variable.
I was able to get around this by saving the full results as its own temporary variable before filtering it, but perhaps I'm not understanding how Craft queries modify entry information. I would assume it would be non destructive?


texts: Can I choose a language for the translate filter?

texts:
So I've built a language switcher as per this answer.

I want the text for each link to be in the native language, for example I want the link to the English locale to say "Read this page in English" and the link to Spanish locale to say "Leer esta página en Español" etc.

However using the |t filter uses the locale that you're currently on, so if I'm on Spanish it says "Leer esta página en English".

Is there a way to pass in a parameter or something to say, for example, |t(Spanish).

Thanks!


texts:
I'm trying to bring back a list of entries from a section. Currently I have the following:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'airports';
$criteria->airportcode = 'BCN';
$airportPrefHotels = craft()->elements->findElements($criteria);

The airport section has a multiple entries field. I want to loop over them.

Is it possible?


texts: Craft 3: Can't backup database ("mysqldump: command not found")

texts:
I just tried to export the DB on the Database Backup page. Unfortunately, I got an error message saying "There was a problem backing up your database. Please check the Craft logs."

So I checked the logs, and found this...

  Could not create backup: The shell command "mysqldump --defaults-extra-file=/mysite/storage/runtime/temp/my.cnf... failed with exit code 127: sh: mysqldump: command not found...

(There's more to that error message, but I'm hoping that all the relevant parts are included here.)

What am I missing? It seems like I still need to install something else, is that correct?


texts: How to export Sprout Form submissions with a JSON API endpoint?

texts:
The goal is to have an endpoint that takes starting id and limit parameters and returns a filtered list of Sprout Form submissions as JSON without the JSON Feed v1 metadata bits.

I've tried to set up an endpoint with Element API, but haven't gotten that working yet. I suspect my elementType is off. I know that there are integration options available in Sprout Forms but from the documentation it looks like it's only pushing the submissions as they come in, not as requested. I've got the endpoint set up on a single PHP page with it's own db table now as a proof of concept.

Is the best way forward to:
a) Complete configuring the element API endpoint.
b) Build a native Sprout Forms data integration.
c) Use custom PHP to get the data and return the JSON.
d) Or something else?


texts: I do not have the /craft/storage/runtime/logs/ folder

texts:
I am trying to set up SMTP emails using Microsoft 365 and the settings are not working so I need to dig into the logs to find out why.

When I go to find the folder it is not there. Instead I have a /craft/storage/logs/ folder but this does not seem to contain the file containing email test logs - [exception.Craft\EmailTestException]

I have tried turning dev mode on to see if that changed the logs I was getting, and it does, but I am still not getting the logs I need.


texts: Dropdown form fields are not submitting properly

texts:
I am having issues with an entry form that updates current entries.
I have a field called "Driver Type" and its handle is "driverType". It is set as a drop-down field on the admin panel. When I submit the form with a driver type selected I will get the following error saying "Driver Type is invalid.".
I find this very odd because I also have a dropdown field called "Minimum Age Requirement" with the handle "minimumAgeRequirement" that updates correctly when I submit the form. The form will not submit when the"driver type" field is in there, but When i remove "driver type" everything else works perfectly fine.
I am identically rendering both fields and mapping them to their respective fields.
driver type

    Driver Type
    {% set drivers = craft.app.fields.getFieldByHandle('driverType') %}
    <select class="form-control" name="fields[driverType]" id="driverType">
      <option value="none" selected>Select a Driver Type</option>
       {% for option in drivers.options %}
      {% if option.label == entry.driverType.label %}
      <option value="{{option.value}}" selected>{{option.label}}</option>
      {% endif %}
      <option value="{{option.value}}">{{option.label}}</option>
      {% endfor %}
    </select>

Minimum Age Requirement

    Minimum Age Requirement
    {% set minimumAgeRequirement = craft.app.fields.getFieldByHandle('minimumAgeRequirement') %}
    <select class="form-control" name="fields[minimumAgeRequirement]" id="minimumAgeRequirement">
      <option value="none" selected>Select</option>
      {% for option in minimumAgeRequirement.options %}
      {% if option.label == entry.minimumAgeRequirement.label %}
      <option value="{{option.value}}" selected>{{option.label}}</option>
      {% endif %}
      <option value="{{option.value}}">{{option.label}}</option>
      {% endfor %}
    </select>

What I don't understand or at least have a hard time comprehending is why I am seeing the following error in the weblogs regarding the driver type field. Below is is the error message I see in the web log
2020-09-17 17:05:50 [-][1][-][info][craft\services\Elements::_saveElementInternal] Element not saved due to validation error: Array
(
    [driverType] => Array
        (
            [0] => Driver Type is invalid.
        )

)

If both fields are drop-down fields, why isn't "driver type" receiving the same error?
Any help would be greatly appreciated...


texts: Control Panel, Landscape / Portrait Images

texts:
How can i achieve that portrait images in Control Panel are shown as portrait images. Now they all are stretched to fit the width of the parent container. This behaviour is only in "Big View" of images.
I use newest Craft CMS 2.6.2791.


texts: What's best practice for creating an index page for Channels?

texts:
If I have a section called "news" with section type "channel" with entries having their own URLs, what is best practice for creating an index for when people site.com/news?

Do I just create an index file in 'template/news' or should I create a route?

EDIT: Did some more digging! Looks like some users have recommended using Structure to create parent level pages. Is this an ideal method?


texts: Use default Craft error/exception layout in Plugin

texts:
Is it possible for me to use the default Craft error-handling/exception-throwing/debug-showing template layout for my own plugin? Let's say something goes wrong and I want to show that to the user in the same style as any other "code related error" for my Plugin.

Could/how would I achieve this?


texts: create a fixed height and width for profile photos

texts:
Is it possible to do anything with Craft's getPhotoUrl() function to allow images to be processed in a similar way like assets?

For example for our profile photos I'd like them to be returned 45x45 cropped from centre.

Currently if a user were to upload a landscape photo they would see something like 45x25 because the height isn't being maintained.

Thoughts?


texts: Force redactor to only display HTML editor view

texts:
Is there a way to make a Rich Text field using Redactor, to only display and allow input in the HTML view?

The first step I tried was making a redactor config file that looks like this:

{
    "buttons": ["html"],
    "plugins": [],
    "toolbarFixed": false
}

But the default view is still the WYSIWYG view. I want the HTML button to be toggled by default...

Many thanks for any help!


texts: Display category entries based on Segment?

texts:
I'm really struggling to display entries of a category, based on the segment. In other words, I have 1 category template, so the category needs to be determined dynamically (*we still  do this by segment, right?? or is that not the best practice?)

I was trying something like this, but I can't seem to get it right:

{% for category in craft.categories.group('typeOfPack').find() %}
     {% set active = (
        craft.request.Segment(2) == category.slug
     ) %}

    {% for entry in entry.typeOfPack.search('active').find()  %}
        <h3>{{ entry.title }}</h3>
    {% endfor %}

{% endfor %}

Apologies if this offensively bad. As I try to get my head around Twig, I'm wondering if there are some high level errors, for instance:
1. Does the {% for entry... %} need to be inside the {%for category... %}? Do I even need to do the {% for category...%} stuff if I'm just needing entries, or is the ".search(...)" sufficient?

Thank you so much.

Big Mike


texts:
Having a strange issue - devMode is set to false, if I go to /404, I get the custom 404 page, which is great.

If I go to /something1234567890 (which is definitely not an entry's URL) I get the following exception:

yii\web\NotFoundHttpException: Template not found: something1234567890

I have tried adding debugging to my base templates but it looks like it is not getting as far as them.

Does anyone have an idea where I can start trying to debug this?

Stack trace:

2018-09-17 00:36:15 [xxx.xxx.xx.x][-][xxxxxxxxxxxxxxxxx][trace][yii\web\Application::handleRequest] Route requested: 'templates/render'
2018-09-17 00:36:15 [xxx.xxx.xx.x][-][xxxxxxxxxxxxxxxxx][trace][yii\base\Controller::runAction] Route to run: templates/render
2018-09-17 00:36:15 [xxx.xxx.xx.x][-][xxxxxxxxxxxxxxxxx][trace][yii\base\InlineAction::runWithParams] Running action: craft\controllers\TemplatesController::actionRender()
2018-09-17 00:36:15 [xxx.xxx.xx.x][-][xxxxxxxxxxxxxxxxx][trace][nystudio107\seomatic\{closure}] ErrorHandler::EVENT_BEFORE_HANDLE_EXCEPTION
2018-09-17 00:36:15 [xxx.xxx.xx.x][-][xxxxxxxxxxxxxxxxx][error][yii\web\HttpException:404] yii\web\NotFoundHttpException: Template not found: something1234567890 in /home/vagrant/code/craft-site/vendor/craftcms/cms/src/controllers/TemplatesController.php:70
2018-09-17 00:36:15 [xxx.xxx.xx.x][-][xxxxxxxxxxxxxxxxx][error][yii\web\HttpException:404] yii\web\NotFoundHttpException: Template not found: something1234567890 in /home/vagrant/code/craft-site/vendor/craftcms/cms/src/controllers/TemplatesController.php:70
Stack trace:
#0 [internal function]: craft\controllers\TemplatesController->actionRender('something123456...', Array)
#1 /home/vagrant/code/craft-site/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#2 /home/vagrant/code/craft-site/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#3 /home/vagrant/code/craft-site/vendor/craftcms/cms/src/web/Controller.php(103): yii\base\Controller->runAction('render', Array)
#4 /home/vagrant/code/craft-site/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('render', Array)
#5 /home/vagrant/code/craft-site/vendor/craftcms/cms/src/web/Application.php(282): yii\base\Module->runAction('templates/rende...', Array)
#6 /home/vagrant/code/craft-site/vendor/yiisoft/yii2/web/Application.php(103): craft\web\Application->runAction('templates/rende...', Array)
#7 /home/vagrant/code/craft-site/vendor/craftcms/cms/src/web/Application.php(271): yii\web\Application->handleRequest(Object(craft\web\Request))
#8 /home/vagrant/code/craft-site/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#9 /home/vagrant/code/craft-site/public/index.php(22): yii\base\Application->run()
#10 {ma    in}

Update 1

The devMode toggling works on another Craft 3 site I have, just not this particular one. Maybe it is a database issue?

Update 2

I have tried this codebase with a fresh database and still getting the same error, so it must be something to do with my codebase?


texts: How to hide {{ entry.title }} on a {structure} page but show it on a {structure}/{category-slug} page

texts:
Here's the breakdown:

» structure with two categories. Each category has +10 entries.

» Template is structure / index.html and _entryview.html

I'd like to show two links and a description of both categories on the /structure/ URL.

However...

On the /structure/index/ page, I'd like to show the entries for each category — all using the same index template.

So far I can pull the {category.title}s and the {entry.title} ... but it's the same on both pages (structure/ and structure/category)

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

  {% nav category in craft.categories
    .group('fellowsCat')
    .limit(11)
    %}

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

          {% children %}

      {% endifchildren %}

  {% endnav %}

{% set entries = craft.entries({
  section:  'fellows',
  relatedTo:  craft.categories('fellowsCat'),
})
%}

{# ___________________________
this is where things fall apart.
If I'm on /structure/ I don't want to see entries.
If I'm on /structure/category, I do.
_____________________________
#}

{% if craft.categories is not null %}

  {% for entry in entries %}

  {{ entry.title }}

  {% endfor %}

{% else %}
nothing to see
{% endif %}

I suspect there's something with the {% if craft.categories is not null %} line that would do the job, but I can't figure it out.


texts:
I can't help but think this is a silly/obvious question, but I'm trying to retrieve the current section handle so I can use it as a class.

Maybe I'm going about it wrong, but {{ handle }} does nothing.

Any ideas?


texts: Invalid Verification Code Customization?

texts:
When a user attempts to reset their password, they're emailed a link -- if they click on this link late, or click on it twice, they're shown the "Oops! Invalid verification code. Please login or reset your password."

Any chance this can be sent to a custom template, ala the loginPath or setPasswordPath configs?


texts: How to add a user to a Users field from front-end form?

texts:
Is it possible to update an entry’s Users field from the front-end? If so, how would you go about it?

The situation is this: training events are created and then posted for members to bid on for a limited number of spots. Logged in members review the available events and add their name (would use their ID) to each event of interest. Admins then manually chose a select few from all submissions.

I know I can do this by adding their IDs to a text field in the event section, and then using Split to create an array, but the Users field approach is much more elegant and offers more flexibility.


texts: Custom Commerce product type URL from custom field

texts:
I've run into a dead end when trying to create custom URL's for a product type in Commerce 2. I want to create the URL from a custom field -- a Commerce Product field to be exact. This product does not have variants.

I've referenced this question here, but the example did not work for me.

Here is what I've tried with no success: {relatedImage.first().id}, {relatedImage[0].id}, {object.relatedImage.first().id}.

When the Craft task manager tries to rerun these products, it just errors out (Failed). And I'm not sure where to find task manager error logs to see if I can get any information from them.


texts:
On a CP edit entry page there is a box for 'Notes about your changes'.
I have entered text in there and saved the entry, but it doesn't seem show up anywhere. How does it work?


texts: I'm wondering if there's any equivalent to the Yii "params" array I can set on Twig code template level for re-use throughout all my templates using Twig syntax?


texts: Anyone with a tricked out .htaccess file

texts:
I am looking at shaving www. and enforcing https on the entire site without a plugin.  All along removing the index.php.

Here is my .htaccess file, it works but is it optimized.  If you have any suggestions on how to condense or streamline would like to hear or see an example please. Thanks!

<IfModule mod_rewrite.c>

RewriteEngine On

# Remove WWW and SSL enforce
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

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

</IfModule>


texts:
I know that static text translations in still possible but where you put those translations has changed. According to the documentation the folder structure should look like this:

translations/
  en-US/
    app.php
     site.php

but what I can't figure out is where exactly do I put the translations folder. Does it go in the craftcms in vendor?


texts: How to find logged IP address from SproutForms sent email

texts:
I see in the documentation for Sprout Forms that IP address is recorded for sent emails. Is this the IP address of the person submitting the form or the IP address of the server sending the mail? Is there a way I can see the IP address of a user who submitted a form on my site with Sprout Forms?

https://sprout.barrelstrengthdesign.com/docs/email/sent-emails.html#tracking-info


texts: Is it possible to change a user's password in the front-end?

texts: Is it currently possible to change a user's password in for example the profile edit form? I'm currently using the forgot password approach for this.


texts:
I am querying data using the code below. In the database, there are duplicate entries for 'title', how can I get distinct values?

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'institutions';
$query = craft()->elements->buildElementsQuery($criteria);
//$query->setDistinct('title');
$query->order('title asc');

$queryResults = $query->queryAll();
$institutions = EntryModel::populateModels($queryResults);

return $institutions;


texts: How to display submission data on a thank you page with sprout forms?

texts:
How can the thank you page display submitted values? I'd like to give the users the submission id to reference.
I've tried adding a hidden redirect field with a shortcode GET parameter but haven't got the syntax right.


texts: Does a programmer have to creates meta tags? I'm the end user (not a programmer)

texts:
I didn't create our website but it's been set up for me and I just use the CMS that was created for me.

Now, I'm being alerted by all kinds of website graders that I need meta tags created. I know how to do alt image tags, and the SEO section of my craft CMS has a section for SEO TITLE, SEO DESCRIPTION, and SEO KEYWORD but no where does it give me a place for meta tags...and if it did, I wouldn't know how to create one.

Do I have to have the programmer who set up my site do it?


texts: What is the best to find a developer to create a Craft plugin?

texts: I have the Craft Commerce based webshop and need a developer to create plugin for Klarna Checkout (https://knowledge.klarna.com).


texts:
Wonder if you can help? Got a booking form on a multi-locale site and I need to include the user's country in the form. I'm using Craft's LocaleData class to output locale-specific locales (e.g. Angleterre for England)...

<select name="country" required>
{% for country in craft.i18n.getLocaleData().getAllTerritories() %}
    <option>{{ country }}</option>
{% endfor %}</select>

Works great except it outputs stuff I don't need like "World", "Oceana", "Ascension Island" etc... Is there any way to control the output, like maybe show countries only and not regions?


texts: I have made a new "section" called Blog. In the dashboard I now have a quick post panel but I can only input a title and nothing else? How can I add the ability to have a body etc?


texts: Craft CMS 3 - Always load "en" translation file

texts:
I have 2 sites (fr and en), fr is default.

In index.php, I have define('CRAFT_SITE', 'fr') and define('CRAFT_SITE', 'en')

In templates, I'm using {{ 'Texte FR'|t }} tag.

In /craft/translations/en/site.php, I have my translation : 'Texte FR' => 'Text EN'

When I test the English version, it's OK.

When I test the French version, English translations are displayed.

If I remove translations folder, of course, it's OK.

If I add 'fr' folder in translations, Englishis  still displayed.

Is there a way to trace the choice of the translation file by Craft?

I can't find why ...

Thank for help. :)


texts: How to set dynamic criteria for endpoint with the Element API plugin?

texts:
How can I set the criteria for an endpoint based on the current category view?

My elementapi.php looks like this where I can pass the slug of a category url to force a return of entries from the slug name.

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->slug = "albania";
$category = $criteria->first();

return [
                'endpoints' => [
                    'directory.json' => [
                        'elementType' => 'Entry',
                        'criteria' => [
                                'section' => 'directory',
                                'limit' => null,
                            ],
                        'paginate' => false,
                        'transformer' => function(EntryModel $entry) {
                            return [
                                'title' => $entry->title,
                                'mapinfo' => $entry->mapaddress,
                                'url' => $entry->slug
                            ];
                        },
                    ],
                    'directory-category.json' => [
                        'elementType' => 'Entry',
                        'criteria' => [
                            'section' => 'directory',
                            'relatedTo' => ['targetElement' => $category],
                            'limit' => null,
                        ],
                        'paginate' => false,
                        'transformer' => function(EntryModel $entry) {
                            return [
                                'title' => $entry->title,
                                'mapinfo' => $entry->mapaddress,
                                'url' => $entry->slug
                            ];
                        },
                    ],
                    'seafarers-directory/<entryId:\d+>.json' => function($entryId) {
                        return [
                            'elementType' => 'Entry',
                            'criteria' => ['id' => $entryId],
                            'first' => true,
                            'transformer' => function(EntryModel $entry) {
                                return [
                                    'title' => $entry->title,
                                    'url' => $entry->url,
                                    'body' => $entry->body,
                                    'mapinfo' => $entry->mapaddress
                                ];
                            },
                        ];
                    },
                ]
            ];

I tried setting the criteria category slug name with

craft()->urlManager->getMatchedElement();

but it always returned nothing.

Can a dynamic category be set for the criteria from the existing url like the dynamic entry is?


texts: Craft 3 Admin not loading cpresources files over HTTPS

texts:
I have a Craft 3 install on my client's Windows machine running Apache, PHP and MySQL.

We purchased an SSL certificate but the main Admin login page (on SSL) keeps loading cpresources assets over HTTP which cause all of these CSS and JS assets to be blocked by the browser.  However, loading these assets over https in a browser works fine.

The Site URL is indeed set to https.  I've tried to force change the URL in config/general.php using the siteUrl and baseCpUrl parameters.  I've also tried clearing Craft's cache and removed the www/storage/* and web/cpresources/* content but nothing works.

I don't have a https redirect in .htaccess as I believe the force redirect was set up when the SSL was installed (I don't have how this step was done).

Does anyone know how to solve this?  The admin page is totally broken and unusable at the moment.

While the server setup is different, this issue might be related to the below.  However I wasn't able to solve my problem based on it.
Craft Admin assets do not load over https (Apache & Cloudflare)


texts: How can I change variant price in Craft Commerce 2 form

texts:
I want to add range field that will change price based on its value.
How can I send updated price to the cart? Is there something easy like:

{% set product = craft.products.one() %}
{% set variant = product.defaultVariant %}

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/update-cart">
    {{ redirectInput('shop/cart') }}
    {{ csrfInput() }}
    <input type="hidden" name="price" value="HERE NEW PRICE">
    <input type="hidden" name="purchasableId" value="{{ variant.id }}">
    <input type="submit" value="Add to cart">
</form>


texts: Order entries by multiple matrix date field

texts:
I have a section with trainings. In each training entry there's a matrix field where we add a new block with a training date, location, etc. So each training has multiple matrix blocks.
When I run an entry query and get all the matrix date fields inside of them, I can output it like this:

Training 1

October 1, 2020
October 5, 2020

Training 2

October 5, 2020
October 10, 2020

Training 3

October 7, 2020
October 10, 2020

Now I would like to group and order the trainings by date like this:

October 1, 2020

Training 1

October 5, 2020

Training 1
Training 2

October 7, 2020

Training 3

October 10, 2020

Training 2
Training 3

I'm close but can't get the dates sorted the right way. The template currently outputs:

October 1, 2020

Training 1

October 5, 2020

Training 1
Training 2

October 10, 2020

Training 2
Training 3

October 7, 2020

Training 3

The code I have right now:
{# Query entries that have training dates #}
{% set allEntries = craft.entries
.section('trainings')
.trainingDates(':notempty:')
.all() %}

{# Merge all training dates in an array #}
{% set startDates = [] %}
{% for entry in allEntries %}
    {% for training in entry.trainingDates.all() %}
        {% if training.startDate | date('d mm Y') not in startDates %}
            {% set startDates = startDates | push(training.startDate | date('d mm Y')) %}
        {% endif %}
    {% endfor %}
{% endfor %}

{# Show all trainings grouped by date #}

    {% for startDate in startDates %}

{{ startDate }}

                {% for entry in allEntries %}
                    {% for date in entry.trainingDates.all() %}
                        {% if date.startDate | date('d mm Y') == startDate %}

{{ entry.title }}

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

    {% endfor %}

Any idea on how to sort the array by date? And this can probably done much easier. If you have any tips, I would love to hear from you! :-)


texts:
I know Commerce allows you to just authorize and pay later but the 'pay later' scenario requires re-entering the credit card details. We have a flow that requires the admin to be able to charge a user later without having the credit card details. As such, we would use Stripe's API to create a customer to save the token for future use, as follows:

User places order, providing credit card info to Stripe.
Authorize with Stripe and create a customer in Stripe so as to save the token for later use (ie. do not charge the card right away).
Allow the admin to go into the Craft CP at a later point and charge the customer's card (by making use of the token saved at Stripe). Do this via a status change perhaps?

We're a little lost conceptually how to proceed with this with Craft Commerce. Do we need to write our own custom gateway to do this?

We considered using the built-in Stripe gateway and setting it to "Credit Card Payment Type: Authorize Only" but that means we get the "Make Payment" button on the Order Detail screen and it also isn't doing anything to create the customer on the Stripe end with a saved token.


texts: Front end assets uploading, does not appear to be a an image error

texts:
I have a front end form for entries. All other fields are working fine however my assets keep throwing errors.

My assets location is set to 'Images/{slug}' in the CP. Server info tells my Imagemagick is installed, on both local and staging environments.

However, when I submit an entry form with a file chosen for the assets field I get an error
'The file XXX does not appear to be an image.'
The odd thing is that the image does actually get uploaded and it's in the expected assets location, but the entry does not get created.

I should add that I can view it within the file directory, but the asset is not indexed into the Assets CP view.

Any ideas?


texts:
I'm working for the first time with Craft Commerce and trying to create product types. So far so good, now I have three product types: "Inspiration", "Gift" and "New". I need the URL of these three product types and don't know how to create it... actually the URL is shop/products with all products.

I need shop/inspiration with the inspiration products, shop/gift with the gift products and shop/new with the new products.

With {{ productType.name }} I can show all my product types, but how can I show the URL of product types?

{% for productType in craft.commerce.productTypes %}
  {{ productType.name }}

    {% for product in craft.commerce.products.type(productType.handle).find() %}
      {{ product.url }}

    {% endfor %}
{% endfor %}

Or do I need to create these product types as categories?

Hope you guys can help me!


texts: How to get a list item  using a plain text field every time I hit enter

texts:
I'm trying to get a list from a simple plain text field which will accept line breaks. I need to find a way to wrap an li tag around the content on that line. So everytime I hit enter, it wraps
Whatever is on that line

So going from this:

Into this:

Thanks!


texts: After upgrading Craft CMS, is there a receipt to print out?

texts:
The in-app process of upgrading a Craft licence is smooth, but leaves no paper trail (not even a confirmation email).
All I've found is a date of registration in the admin panel sidebar, without even stating the Craft licence type (client or pro).

Is there away to obtain a somewhat formal proof of purchase, like a receipt, that I can pass along to a client?


texts:
I'm getting this strange error when I'm trying to upload an .jpg in the assets.

Env: Localhost
Craft version 3.1.8

MAMP:
- PHP(7.2.7)
- MySQL: 5.7.21

Upload failed. The error message was: "SQLSTATE[23000]: Integrity constant violation:


texts:
Here's what I'm getting:

Error: An error occurred

Output: Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for craftcms/cms 3.0.18 -> satisfiable by craftcms/cms[3.0.18].
    - craftcms/cms 3.0.18 requires enshrined/svg-sanitize ~0.9.0 -> satisfiable by enshrined/svg-sanitize[0.9.0] but these conflict with your requirements or minimum-stability.
  Problem 2
    - craftcms/cms 3.0.18 requires enshrined/svg-sanitize ~0.9.0 -> satisfiable by enshrined/svg-sanitize[0.9.0] but these conflict with your requirements or minimum-stability.
    - pierrestoffe/craft-language-redirector 1.0.2 requires craftcms/cms ^3.0.0-RC1 -> satisfiable by craftcms/cms[3.0.18].
    - Installation request for pierrestoffe/craft-language-redirector 1.0.2 -> satisfiable by pierrestoffe/craft-language-redirector[1.0.2].

Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.

I've attempted:

removing vendors directory
removing composer.lock file
updating via CLI
changing craftcms to 3.0.18 and running install

Anything else I can try?


texts:
I'm currently working on integration some caching behaviour using {% cache %} tags. This works mostly just fine, but I have some issues when I work with related entries.

For example I have a list of categories with an indicator to show many entries they are assigned to.

New (3)
Used (2)
Broken (3)

If I change an entry and add a category, the cache refreshes and shows the correct amount. But if I remove a category from an entry I get the wrong number until I refresh the cache manually.

Is this the expected behaviour? Or do I miss something here?

Here is my code example:

{% cache unless not craft.config.cache %}
{% set categorySlug = productSection ~ 'Categories' %}

{% for category in craft.categories.group(categorySlug) %}
  {% set entryCount = craft.entries.relatedTo(category).total() %}
  {% if entryCount > 0 %}

      {{ category.title }} ( {{ entryCount }} )

  {% endif %}
{% endfor %}

{% endcache %}


texts: I created a section for appointment record (channel type). Each appointment record has different fields, i.e. customer name, phone#, address, etc... I would like to set a unique appointment_record_id (Numeric, i.e. 234) for each record.  Is there any way to create it?


texts: How to modify entry with a users field in the front-end?

texts:
Is it possible to modify an field of an entry within the front-end? Something like this with an action URL:
add user to userfield of current entry


texts: "Field Limit is too big for your chosen Column Type" error on already existing fields when updating matrix

texts:
I'm getting the following error when I'm trying to update a matrix:

"Field Limit is too big for your chosen Column Type.""

I'm trying to add a new block type but this error keeps getting up on fields that already exist in other block types.
The problem seems to related to the plain text field type. I've read somewhere about the field limit exceeding the mysql varchar length but 80 or 100 shouldn't be a problem, no?

Does anyone have an idea what might be the problem?

I'm running on:

PHP version 7.2.15
OS version  Linux 4.19.76-linuxkit
Database driver & version   MySQL 5.7.26
Image driver & version  Imagick 3.4.3 (ImageMagick 6.9.7-4)
Craft edition & version Craft Pro 3.4.19
Yii version 2.0.35
Twig version 2.12.5
Guzzle version  6.5.3
Imagine version 1.2.3-dev


texts: I just want to run a couple of conditionals depending on a visitor's IP address. How would I do that?


texts: Craft on a cPanel hosting with CentOS and CloudLinux – I/O faults?

texts:
I'm running Craft on our shared hosting with PHP 7.2. No SSD. Performance is fine, but working in the backend, I often get hickups of several seconds (!), where nothing happens, everything stalls.

Here's what cPanels resources diagram tells us:

So ... something with I/O and I/O Faults.

Could this be solved without changing the hosting?


texts:
I've been given a site and asked to prevent visitors from seeing the news archive beyond page 6.

The navigation has already been done, but if the user manually enters example.com/news/p7 they'll see it.

Here’s my template code:

{% set entries = craft.entries.section('news').limit(3) %}
{% paginate entries as entries %}
    {% for entry in entries %}
        {% include '_elements/_news-entry' %}
    {% endfor %}
    {% include '_elements/_pagination' %}
{% endpaginate %}

The _elements/_pagination include:

{% for page, url in paginate.getPrevUrls(5) %}
    {{ page }}
{% endfor %}

{{ paginate.currentPage }}

{% for page, url in paginate.getNextUrls(5) %}
    {{ page }}
{% endfor %}

I tried adding the following to /craft/config/routes.php, but it doesn't appear to have any effect.

'news/p[^1-6]' => '404',


texts: Do temporary files stored in craft/storage/runtime/temp get automatically deleted?

texts:
This is somewhat related to the question at Where should a plugin create temporary files

I have a plugin that needs to store temporary files. Do I need to worry about cleaning up the craft/storage/runtime/temp after I'm done with them, or do they get deleted automatically on some kind of recurring basis?


texts: Parse variables into twig email template from custom module

texts:
I'm trying to send an email from my module and am trying to pass some vars into my module template that I can render using twig. Please note that this is a module template not a front end template.

$first = "john";
$last = "doe";
$mailTo = "john@example.co.uk";
$mailer = Craft::$app->getMailer();
$mailer->htmlLayout = false;
$mailer->textLayout = false;
$mailer->setViewPath('@modules/businessmodule/templates/emails');
$mailer->compose('failed_payment.twig', ['first' => $first, 'last' => $last])
        ->setTo($mailTo)
        ->setSubject('Failed Payment')
        ->setTextBody('Text fallback')
        ->send();

But I cannot access the vars in my twig template like {{ first }}.

i.e

<p>
    Hi, sorry it didn't work out {{ first }} {{ last }}
</p>

Am i missing some parse method somewhere?


texts:
I tried setting up a URL format that takes the hierarchy of a structure into account, but deals with the magic __home__ slug transparently.

So I did this:

{parent.uri == '__home__' ? '' : parent.uri}/{slug}

Which works, but I wanted to tighten it up using the twig ternary ?:, like this:

{parent.uri != '__home__' ?: ''}/{slug}

But that doesn't work at all, seems to choke on the ?: part. Is that a bug, or just a short-coming of the URL format system (not being actual twig)?


texts: What are the replacements for the order events onBeforeAddToCart and onBeforeGatewayRequestSend in Commerce 2

texts:
I'm looking for replacements for the events onBeforeAddToCart and onBeforeGatewayRequestSend.

I used onBeforeAddToCart to prevent the user from adding an article from different article groups to the cart.

onBeforeGatewayRequestSend is used to check a mandatory field and to increment our own order/invoice numbers (the md5-style numbers are not convenient for German business).

I need to set $event->performAction = false and $transaction->message = "Please agree with our terms and conditions" if the mandatory field is not checked, like I did in Commerce 1.


texts: List authors on front end by total number of entries

texts:
I need to output a list of channel authors. There are about 40 authors but I want the 8 authors with the most entries. Not sure how to achieve this.

What I have so far:

    {# get all the itbuzz entries #}
    {% set allEntries = craft.entries.section('itbuzz').all() %}
    {# get all the authors #}
    {% set authors = craft.users.group('itBuzzAuthor').limit(8).all() %}

      {% for author in authors %}

          {{ author.firstName }}
{{ author.lastName }}

      {% endfor %}

All this does is output the first 8 authors, it's not finding the 8 with the most entries.


texts: How to directly get value of text field in a given section of type structure?

texts:
I am trying to get a value of a text field that is in a Section which is a structure and has multiple entry types. I don't want to use a loop. I tried this and some other variations but does not give me the correct value.

{% set value = craft.entries.section('mySectionHandle').type('entryTypeHandle').myTextFieldHandle.first() %}

What is the correct syntax? Thanks.


texts:
I've used this tool to generate a module: https://pluginfactory.io/

So in my constructor, I have

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

In my init() function I have this

 Event::on(
            Cp::class,
            Cp::EVENT_REGISTER_CP_NAV_ITEMS,
            function(RegisterCpNavItemsEvent $event) {
                $event->navItems[] = [
                    'url' => 'leads',
                    'label' => 'Leads Management'
                ];
            }
        );

When I click the link on the control panel, I will get a Template Not Found error.

My template folder is located at modules/leadsmodule/src/templates

Inside templates I have a file called leads.twig.

I did die() on the $baseDir that it's being set to in the constructor and got the path: modules\leadsmodule\src\templates

I need my control panel item to load a specific template.

What am I doing wrong?

Edit: the control panel URI for my item looks like /admin/leads

Here is my config/app.php

'*' => [
        'modules'   => [
            'leads-module' => [
                'class' => \modules\leadsmodule\LeadsModule::class,
            ],
        ],
        'bootstrap' => ['leads-module'],
    ],

I've tried every combination to load the template I can think of.

In side my modules/leadmodule/src/templates I've placed the following

admin/leads-module/leads.twig

admin/leadsmodule/leads.twig

/admin/leads.twig

/leads-module/admin/leads.twig

/leads-module/leads.twig

/leadsmodule/admin/leads.twig

/leadsmodule/leads.twig

/leads.twig

Still get a 404 template not found: leads when accesses /admin/leads from the control panel


texts: I am still new to craft commerce and I have 5 sales, some are flat and others are percent. When i loop through my products, I am trying to get the type of the sale for the current product. How do i get that?


texts: Calling an event from a third party plugin in my plugin

texts:
Trying to work out if I’m doing something wrong with catching an event from another plugin in my plugin.

I’m trying to use amforms “onSaveSubmission” event, so, in my plugin’s init()
function i have

craft()->on('amForms.onSaveSubmission', function(Event $event) {
    var_dump($event);
});

But, when I submit a form successfully, this event is triggering an error:

Internal Server Error

Property "Craft\AmFormsService.onSaveSubmission" is not defined.

The onSaveSubmission event is in /plugins/amforms/services/AmForms_SubmissionsService.php


texts:
What could cause Craft to not define the request object?

I have a local site that recently stopped loading (front-end and back-end)

The error is happening in WebApp.php (line 630) when $this->request->getBrowserLanguages() method runs.  The script fails because $this->request is not defined.

Other Craft installations work just fine.  This site works just fine on a dev and live server with the same code. Any ideas on what I bumped?


texts: Can't redirect cpTrigger and api routes/urls - oauth in craftcms

texts:
I have OAuth 2.0 installed in my Craft project. I built an event that every URL is redirected to example.com/oauth and needs authorization if not logged in.
Everything works except these two routes:

/api -> defined in routes.php for graphql frontend schema
/admin and /admin/login -> defined as cpTrigger in general.php

Is there any way to also trigger these two routes for my event?
Thanks in advance!


texts: How do I implement Google+ comments on a Craft site?

texts: How can I implement Google+ comments into Craft CMS?


texts: Updating the postDate field from a plugin?

texts:
I think I'm almost there with this one but obviously missing something as the postDate is not updating. I have the following in an onSaveEntry event. It's saying it's successful but the postDate does not change. Ideally I want this to update whether the entry is enabled or not.

public function onSaveEntry(Event $event)
{
    $entry = $event->params['entry'];
    // set postDate from assignedDate
    if($user->admin) {
        if($entry->assignedDate && $entry->assignedTimeslot) {
            $timeslot = $entry->assignedDate.' '.$entry->assignedTimeslot.'.000000';
            $params = $entry->postDate = $timeslot;
            $success = craft()->elements->saveElement($entry, $params);
        }
    }
    return $event;
}


texts: Showing entries in CP only for specific category

texts:
I need to sort structure section entries belonging to specific category (entries have category field).

With default structure list displayed in CP, i see all entries for this structure type section thrown in together. This makes sorting cumbersome because if i want to sort inside specific categpry, all other entries from other categories are in the way.

So, can i display entries only related to specific category in CP?


texts: How can I strip or replace a non-breaking space with Twig?

texts:
Using Twig, is it possible to strip out or replace a non-breaking space (&nbsp;)?

I've got a string variable price (returned from the currency filter) that prints like this:

Nkr&nbsp;100,00

What I'd like, is to strip the Nkr&nbsp; part, so the string looks like this:

100,00

However, {{ price|replace('Nkr&nbsp;', '') }} does nothing, as the replace filter doesn't appear to actually match the non-breaking space.

{{ price|replace({'Nkr' : ''}) }} strips out the Nkr part, but leaves the &nbsp;; and I'm unable to remove it.

Here's what I tried already (after stripping the Nkr part):

{{ price|replace({'&nbsp;' : ''}) }}
{{ price|raw|replace({'&nbsp;' : ''}) }}
{{ price|striptags }}
{{ price|raw|striptags }}
{{ price|trim }}
{{ price|raw|trim }}
{{ price|replace({ '\u00a0' : '' }) }}
{{- price -}}
{% spaceless %}{{ price }}{% endspaceless %}


texts: How do I show errors for a new front end entry form?

texts:
I'm using a front end form so logged-in users can create a new entry ("post") or edit an existing entry. Here's the controller for figuring out whether it's a new or existing entry:

{# Get the entry being edited from the url parameter #}
{% set entry_id = craft.app.request.getParam('id') %}
{% if entry_id %}
  {% set post = craft.entries({
    id: entry_id,
    status: null
  }).one() %}
{% else %}
  {% set post = null %}
{% endif %}

For the form fields, I'm using Twig partials and with { 'entry' : post }.

This works great for editing a post, and I can create a new post as long as I enter the info that Craft expects. However, there are some required fields, and I want to show error messages when those fields are missing, rather than the post silently failing to be created.

Per the entry form documentation, I'm including the suggested macro and this chunk of code with my required headline field:

{% if entry is defined %}
  {{ errorList(entry.getErrors('headline')) }}
{% endif %}

Desired behavior:
if I try to save a new entry that's missing a headline, I should get the error message for that field.

Actual behavior:
This gives me a runtime error: Impossible to invoke a method ("getErrors") on a null variable.

I've tried setting post = {} for an empty object, but Twig seems to see that as an array and can't invoke getErrors on that either.

How should I go about addressing this?


texts: Passing params to Freeform’s `render` tag

texts:
Can you pass params to Freeform’s render tag ?

E.g. {{ entry.form.render({ entry: entry }) }} ?

Trying to access entry data inside formatting templates...but I get Variable "entry" does not exist error.


texts:
Is it possible for me to create an image transformation that generates a cirle cropped thumbnail?

Just like this:


texts: Get entry url from primary site (using seomatic)

texts:
We're adding a multi-site config to a website.

All sections are being copied over to the new sites from the primary site.

So for example, we now have these two pages:

mysite.com/services/some-service

mysite-ca.com/services/some-serivice

The mysite-ca.com should have a canonical url of mysite.com/services/some-service

I'm using seomatic and I'd like to insert the correct dynamic canonical url in the Content Seo Settings.

Is there a way to get an entry.url from another site?


texts:
How do I print the field ID of a category field in place of its title?

{% for entry in craft.entries.section('posts').relatedTo(category) %}
    some html...
    {% for category in entry.market.level(2).find() %}
        {{ category.title }}
    {% endfor %}
{% endfor %}

I want to print the field ID of category.title instead.

Reason = I am using the printed output as a class to filter against.  Some of the category titles contain more than one word and I do not want to add a hyphen to each instance.   So, using the field ID in place of category.title  would solve this problem.


texts:
I am trying to send data to my plug-in controller using jquery $.post() method.
here is my form:

<form method="post" action="" accept-charset="UTF-8" id="testForm">
  {{ csrfInput() }}
  <input type="hidden" name="action" value="test/test">
  <button type="submit">Test</button>
</form>

and this is my js code:

<script type="text/javascript">
   window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
   window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>
<script>
$("#testForm").submit(function (e) {
    e.preventDefault();
    var data = [];
    data["test"] = "test";
    data[csrfTokenName] = csrfTokenValue;
    $.post('/', data, function(response) {
        console.log(response);
    });
});
</script>

The console keeps logging "400 Bad Request".
What am I doing wrong ?


texts:
I'm using a Rich Text field for captions beneath images, so that I can add bold, italic and links. But I'd like the output HTML to be a single line; ie, no block-level tags like <p>, or line breaks. At the moment Redactor automatically adds <p> tags, around a single line of text.

I've tried setting both paragraphize and replaceDivs to false in my Redactor config JSON, as suggested in this answer but that seems to have no effect for me:

{
    buttons: ['bold', 'italic', 'link'],
    minHeight: 50,
    paragraphize: false,
    replaceDivs: false
}


texts: Problem uploading JPG in MAMP Pro 4.2 (9213)

texts:
I use MAMP Pro for a few years in combination with Craft CMS, but since the new upgrade to version 4 I cannot upload JPGs anymore. Dit anybody had the same issue and how to fix this?

In the PHP7.0.20.ini there's a line says:

MAMP_Imagick_MAMPextension=imagick.so

And these are the settings for resource limits:

max_execution_time = 240
max_input_time = 240
memory_limit = 1024M
upload_max_filesize = 32M

But it's different from earlier versions, so it looks like ImageMagick is loaded?

Thanks in advance.

Cheers, Martijn


texts: Solspace Freeform: loop over all form errors

texts:
I can only find the following method in the documentation (https://solspace.com/craft/freeform/docs/form/#templates)

form.hasErrors

Is there an array available with all the error messages combined? I'm looking for a way to iterate over all form errors.


texts: How do I output all field values from a Category on the current entry?

texts:
I'm building my first site with Craft, so this is a bit newbie question.

I've build a category with a some fields.
How can I output all fields form the selected category on the current entry?

Thank you very much.


texts: How can I list all sub-field handles of a Matrix parent field?

texts:
If I want to get a list of all fields that I've defined on the site, I can do this:

craft()->fields->getAllFields()

But how do I get a list of all sub-fields defined within a Matrix field?

I have access to the MatrixBlockModel, if that helps.


texts: How do I pass dynamic year and month to the .after() and .before() functions?

texts:
I've a URL /news/archive/2014/12

A route parses that as going to an archive template and captures a year and month variable. I then want to select all the entries from that month, and I can't work out how. Here's what works for just the year:

{% set entriesInPeriod = craft.entries.section('news').limit(null).after(year).before(year+1) %}

And the docs say the after and before functions need things specified in the format:

YYYY
YYYY-MM

I can't get that passed in because I don't know how Craft is interpolating the contents of the parenthasise; if I do

{% set entriesInPeriod = craft.entries.section('news').limit(null).after(year-month).before(year-month+1) %}

I'm not getting any results.

UPDATE: Answer below (use ~ to concat strings) doesn't work correctly because in reality months 'loop' after 12. What gets put in the query when starting in December evaluates to 'month after 12 and before 13', which is garbage.

Is there a way to get something like:

{% set entriesInPeriod = craft.entries.section('news').limit(null).postDate(year~'-'~month) %}

This doesn't work, but I can find no documentation on how postDate should be formatted in this use case.


texts: If we wanted to use FeedMe to import changes from a staging server to production, what would be the best plugin (etc.) to use for content feed that Production would use to import items from staging?


texts:
I have a custom plugin that uses a custom field leveraging the elementSelect fieldtype to select an asset (which is then processed on submission via a custom service). However, when I select an asset via my field, I get the following JS error in console:

Uncaught Error: Syntax error, unrecognized expression: [data-id="["1286"]"]:first

The integer above relates to the selected asset.

Has anyone come across this issue before?
It was working previously so not sure if a Craft update has broken it.

The plugin field template:

{% import "_includes/forms" as forms %}
{{ forms.elementSelectField({
        elementType: elementType,
        sourceElementId: value,
        value: value,
        elements: elements,
        sources: volumes,
        label: 'Your asset',
        limit: 1,
        id: name,
        name: name })
}}

Cole


texts: How to use createFromString() in Craft 3

texts:
In Craft 2 I've used createFromString() as following:

DateTime::createFromString($pubDate, craft()->timezone)

But if I use this function in craft cms 3 then I'm getting the following error:

Call to undefined method DateTime::createFromString()

Is there any alternative way to use the createFromString() in Craft 3?


texts: Sorting multi-dimensional grouped arrays

texts:
My problem is that I don't know/understand how to sort complex arrays.

I have a multi dimensional array of users from an external API. So it's not an array that I fetch from the Craft database. Let's call this array the "Main Array".

The Main Array contains multiple users, every user has multiple fields such as firstname, lastname, department, and so on. So every user in the Main Array is actually another array that we shall call a User Array. So the Main Array consists of multiple User arrays which consists of multiple fields.

First I group the Main array by the department field of a user (using the Twig group filter). So far so good, that way I can list all my users in department blocks.

But within those blocks, I want them to be alphabetically sorted by their lastname. So I need a way to let Craft know to sort my User Arrays by the lastname field of a user within the Main Array.

Seems logical and simple, but I can't figure out how. I tried SuperSort, but the standard asort function won't work. I than tried superSort('SortAs', '{lastnameField}') but that didn't work either.


texts:
When I upload an image to assets, it just shows the progress bar loading, but it won’t upload my image into assets. Originally, this had worked before, but for some reason it suddenly just stopped working. I’m using Media Temple for my production. I checked my error log and it says:

  Got error 'PHP message: PHP Warning:  File upload error - unable to
  create a temporary file in Unknown on line 0

I’ve checked my files permissions and changed /tmp to 777 and I’ve also changed my assets folder to 777 too. I even checked my disk space for the /tmp folder and it still have 25GB left so it’s not out of disk space.


texts:
I really love working with Craft, especially around how easy and user friendly it is. However, I do work with React/Vue and usually I setup a node server/app that will do some routing, render views and so on...

Would it be a good idea to have a setup like this:

Frontend: React / Vue
Backend: node app that has all my public routes setup, rendering views, server side render React/Vue etc
Backend no 2: Craft CMS with Element API setup

Example:

User requests /contact/person-1
The request will be matched in my node app as a valid route
Node app will make request to the API that has been setup for Craft, fetches the relevant info about Person 1, returns the result to node
Node app renders the view with the data that was fetched

Is this O.K. or completely nuts? Will it be ineffective or is it a good way to structure it like this when I'm in need for a nice CMS like Craft... ?

Please help me out on finding the best approach!


texts:
I'm working on a plugin where I set a variable from my template. The plugin also provides a Twig filter
that makes use of that variable.

{% do craft.myPlugin.setVar('example') %}

{# Filter appends 'example' to the entry title #}
{{ entry.title|myFilter }}

One thing I'd like to do is to make it possible to set the variable anywhere in my template,
but still provide it to the Twig filter everywhere it is used (within that template).

{{ entry.title|myFilter }}
{% do craft.myPlugin.setVar('example') %}
{{ entry.body|myFilter }}

Yes, this probably is a very very stupid question and this cannot be done.
But maybe there's a chance I'm overlooking something and you can influence the parse order or do some magic to make this possible? Any answers welcome :)


texts:
Getting a strange error when trying to check if a field is null when importing via FeedMe

Getting unknown property: craft\feedme\events\FieldEvent::fieldValue

use yii\base\Event;
use craft\feedme\events\FieldEvent;
use craft\feedme\events\ElementEvent;
use craft\helpers\ElementHelper;
use craft\elements\Entry;

Event::on(Fields::class, Fields::EVENT_AFTER_PARSE_FIELD, function(FieldEvent $event) {
    switch($event->feed['name']){
    case 'offers':
    if ($event->fieldHandle === 'merchants' && $event->fieldValue == null) {
    $event->isValid=false;
    }
    break;
}
});


texts: Faster MySQL query when joining data from a non-Craft table to a Craft table

texts:
I’m looking for a way to make a database query faster. The table parts has over 6 million rows. Each part row is associated with the manufacturers table (a couple hundred rows) by ID. When searching for results matching a query in a specific column (i.e.: partNumber or materialDescription) I have efficient queries that return results quickly.

The problem I’m having is when I’m doing an ALL search where the result can be in the parts table’s partNumber column or materialDescription column or the manufacturer’s title (which can only be determined by the manufacturerID from the part’s row which gets the manufacturerCode from the manufacturers table which can then get the manufacturer’s actual name by finding the entry in Craft’s content table field_manufacturerCode column. The results time is well past 20 seconds. Is there any way to make this database query more efficient assuming we can’t add the actual manufacturer’s name to the manufacturers table because the API we are getting the data from doesn’t include the manufacturer’s name?

SELECT p.id, p.manufacturerId, m.code as manufacturerCode, p.materialNumber, p.partNumber, p.materialDescription, c.title as manufacturerTitle
FROM `craft__parts` AS p
JOIN `craft__manufacturers` AS m ON p.manufacturerId = m.id
JOIN `craft_content` AS c ON m.code = c.field_manufacturerCode
WHERE p.partNumber like '%polymer%'
OR p.materialDescription like '%polymer%'
OR c.title like '%polymer%'
ORDER BY manufacturerTitle asc


texts: Field removed from entry layout is still displaying

texts:
So I'm setting my meta author tag this way:

<meta name="author" content="{% if seoAuthor is defined %}{{seoAuthor}}{% else %}{{globalSeo.seoAuthor}}{% endif %}">

seoAuthor is a field that only appears in some entrie's layout (blog posts). At first the field was on every entry, but I changed it later.

The problem is that the data on the entries that no longer have that field in their layout is still displaying.

So is it possible to only show fields that are currently in the layout of the entry ?


texts: Is .relatedTo().total() returning all source elements if none are found?

texts:
I'm using categories and relating them to entries.

If using .relatedTo().total() I'm seeing the total number of ALL entries if none of the entries are related to a particular category.

If using .relatedTo().find()|length then zero is returned as expected.

I'm trying to output a link list of all categories with their total related entries IF they have any entries.

Here is the code I'm using (with a testing snippet to show how |length is working.

{% set cats = craft.categories.group('topic') %}
{% for cat in cats %}
  {% set total = typeEntries.relatedTo({targetElement:cat}).total() %}
  {% if total %}

{{ cat.title }} ({{ total }})

    testing length: {{ typeEntries.relatedTo({targetElement:cat}).find()|length }}
  {% endif %}
{% endfor %}


texts: Is there an option to edit title-parameter for Links in Redactor?

texts: How can i edit Link-Title in Redactor Richtext-Editor? Didn't found any config options or plugins for that. Can't believe this is not possible yet.


texts: On entry save/update, centered text returns to left in rich text field

texts: How am I to center text with in the rich text field type? It centers while I'm editing, then returns to left align on save (and on output). I feel like I'm missing something obvious here...


texts: How do you manage your Craft 'starting point'?

texts:
We build a lot of Craft site's these days, and now we ave a lot of experience we find we are always having to re-do the same few dozen things at the start of every project, such as setting up a Matrix field called 'Mixed Content' with a bunch of entry types in it, and the same for 'SEO' fields. These are always identical, but they take half an hour or so to set up, every time.

The templates aren't an issue, we have those stored somewhere and can just copy them in, but getting the database stuff done is becoming a chore and it's time that's adding up. How do you handle this?


texts: Craft 3: Error "variable now does not exist"

texts:
I upgraded a Craft 2 project to Craft 3 and am working on updating some template quirks. One I am having trouble with involves the following element query:

{% set scriptsAboutToExpire = craft.entries({
    section: 'scripts',
    order: 'expirationDate asc',
    expirationDate: [ 'and', '>=' ~ now, '<=' ~ now|date_modify('+2 weeks') ]
}) %}

This worked great in Craft 2. It grabs all script entries whose expirationDate field is two weeks away from today's date.

However now after upgrading to Craft 3 I am getting the following error when viewing that template:

PHP Recoverable Error – yii\base\ErrorException
Object of class DateTime could not be converted to string

with a highlight on this line:

(isset($context["now"]) || array_key_exists("now", $context) ? $context["now"] : (function () { throw new Twig_Error_Runtime('Variable "now" does not exist.', 10, $this->source); })())), 2 => ("<=" . twig_date_modify_filter($this->env, (isset($context["now"]) || array_key_exists("now", $context) ? $context["now"] : (function () { throw new Twig_Error_Runtime('Variable "now" does not exist.', 10, $this->source); })()), "+2 weeks"))))), "method");

I tried updating all .localeDate() filters to |date('short') but that had no effect.


texts:
So I made an account with MultiSafePay:

Added my website where i need to get payments from.
Filled in the API key and Locale
Enabled it for customers (me)
Changed the Gateway of MultiSafepay from XmlGateway to RestGateway.
(Because XMLGateway is deprecated)

How would I add it to the checkout process in Craft Commerce?

Now I only get to see the credit card fields if MultiSafePay is selected in the dropdown, but I enabled all the payment options at MultiSafePay.

Could somebody explain to me and others how to implement it correctly?


texts:
Is it possible to start a matrix loop from a particular block ID?

I am trying to set a new block called "New Page" so that an author can split an article into multiple pages.

Currently it's able to detect a page break and exit out of the block field loop. I have also identified the next block's ID.

{% set nextBlockAfterPageBreak = contentBlock.getNext().id %}

Now what I'd like to be able to do is to get all blocks from nextBlockAfterPageBreak.

So for example,

{% for contentBlock in matrixField where firstBlock = 237 %}

Does anybody know if this is possible?


texts: Duplicate Entry Types into a new section

texts:
Is there a way to duplicate Entry Types into a new section?  I have a section with many entry types with their fields and handles all named nicely...  I need to create a Section using exactly the same Entry Type setup?

Many thanks

Martin


texts: I get error on live site after Preparse-field update

texts:
After I've turned devMode on live site to see what's going on a fatal error appeared: Using $this when not in object context in /var/www/vhosts/site.com/craft/plugins/preparsefield/PreparseFieldPlugin.php on line 112

The weird thing is, that with same settings on local machine it runs as expected.


texts: How to query EntryQuery for multiple sections with varying types

texts:
I think the best way to pose this question is by giving an example:
Given a variable $query of type craft\elements\db\EntryQuery, I'd like to get entries from 2 different sections: "people" and "news". Of the entries from the "people" section, I only want ones with entry type "Employees". How would I set this up so that the "type" filter only applies to 1 section? If I were querying them individually, they would look like this:
$query->section('people')->type('Employees');
$query->section('insights');

How can I do this in 1 query? Thanks!


texts:
I am trying to set up a search form in my website. Followed this tutorial on builtwithcraft documentation website.

So in my top navigation bar I include this code

<form class="navbar-form navbar-right" role="search" action="{{ url('/oeuvres/_results') }}">

        <input type="search" class="form-control" name="q" placeholder="Recherche">

            <button type="button" class="btn btn-default" value="Go"> </button>

</form>

And then the result page:

{% extends "_layout" %}

{% block main %}
    {% include "includes/_topNav" %}

Résultats

                {% set query = craft.request.getParam('q') %}
                {% set entries = craft.entries.search(query).section('oeuvres') %}

                {% if entries|length %}

{{ entries|length }} Votre recherche:

                        {% for entry in entries %}

{{ entry.title }}

                        {% endfor %}

                {% else %}

Votre recherche “{{ query }}” n'a donné aucun résultat.

                {% endif %}

    {% include "includes/_javaScript" %}
{% endblock %}

I have no idea what is wrong, it seems that the "q" param is passing through the result page (the address line is for example: http://www.example.com/oeuvres/_results?q=routes
But the page is totally blank. Meaning nothing gets generated between the body tags. (not even the template tags...

I can't find what I am missing here.


texts: Can I disable logging 404 errors in my craft.log file?

texts:
I want to get a better understanding of some issues in production surrounding timeouts but as its a high traffic site the craft logs get replaced about every 15 minutes due to the amount of 404's that are requested.

Most are stuff like missing apple-touch-icons or old images from our last version of the site that are now gone. Is there any way to tell craft either to not log those 404s so that craft.log becomes a little more useful?


texts:
I want to create an event that triggers before the site loads to I grab the variables passed in the http header and send them to a plugin I have made.

I will have a url like http://www.foo.com?username=abc123

I want it immediately trigger a controller method located at: http://www.foo.com/actions/myPlugin/myMethod

Im just not sure how to connect the dots.


texts: Falling back to Parent Category if no asset exists

texts:
I'm trying to make it so that if an entry image does not exist, then fall back to the category image that the entry belongs to. Right now this isn't working and is receiving an error.

{% set feature = entry.brandFeature.one() %}
{% set featureUrl = feature ? feature.url : entry.category.one().categoryImage.getUrl() %}
<div class="jumbotron category-jumbotron" style="background-image:url({{ featureUrl }})">

This is the error that craft is returning:

  Calling unknown method: craft\elements\db\AssetQuery::getUrl()


texts: Redactor pagebreak plugin and linking to pages

texts:
I am trying to split entry into multiple pages.

In accordance with the docs, I am using this code on single-entry template:

{{ entry.body.getPage(1) }}

{% if entry.body.getTotalPages() > 1 %}
  Continue reading…
{% endif %}

However {{ entry.url }} is always pointing to the same page that I'm on (base entry URL) without any pagination number, so I never get to second page.
I have checked that {{entry.body.getTotalPages()}} returns 2, so the pagebreak plugin is working.

What am I missing here?

Answer:

Here's the working code that I got with Brad Bell's help:

{% set currentPage = 1 %}
{% if craft.request.getParam('page') is not empty %}
    {% set currentPage = craft.request.getParam('page') %}
{% endif %}

{{ entry.body.getPage(currentPage) }}

{% if entry.body.getTotalPages() > 1 %}
    {% set totalPages = entry.body.getTotalPages() %}

    {% for i in 1..totalPages %}
    go to page: {{ i }}
    {% endfor %}
{% endif %}


texts:
I'm not entirely well versed in how Redis works, but I have an idea that it probably makes the most sense to have the 3 craft sites I have running on the same server, have 3 different redis databases assigned to each?

Is there a way to do so, like in general.php or db.php

As in

"site-one.com" => {
    'database' => 0,
},

"site-two.com" => {
    'database => 1,
}


texts: Return entry where matrix field is not empty

texts:
I am trying to get a random entry which has the quote matrix field populated.

I've tried this:

{% set entry = craft.entries.section('entries').quote(':notempty:').order('RAND()').limit(1) %}

That isn't working. What do I need to do?


texts:
I'm trying to upload a 40MB video through the assets tab in the admin panel, but I get an error saying "The file "x.mp4" could not be uploaded, because it exceeds the maximum upload size of 8.0 MB."
In my php.ini file it looks like I've got it set to 265MB and i'm not sure where else to check. Here's what my php.ini file looks like:

allow_url_fopen = Off
allow_url_include = Off
display_errors = Off
enable_dl = Off
file_uploads = On
max_execution_time = 30
max_input_time = 60
max_input_vars = 1000
memory_limit = 128M
session.gc_maxlifetime = 1440
session.save_path = "/var/cpanel/php/sessions/ea-php71"
upload_max_filesize = 256M


texts: How can I create list of a group’s fields for a select field’s options in my Field Settings?

texts: I’m trying to create a plugin that relies on the values of a Matrix field in the same entry. Knowing that a single entry type could have more than 1 Matrix field, I think I need a way to select which Matrix field to pull from in my field settings. Any thoughts?


texts: How would one go about migrating fields?

texts:
Is there any "simple" way of migrating fields and layouts from one setup to another?

Example;
Two identical installations/setups have diverged, where some information on certain fields have changed (like descriptive texts and so forth), perhaps there's a SuperTable or Craft Neo field with added blocks, or even a matrix field where there's been blocks added on the one setup, that need to update exactly on the other setup. Perhaps there's been some additions to a structure's field layout. Perhaps something has been removed.

I realize this could possibly be done with some sort of plugin/migration.

The purpose of my question is basically to figure out a) if there's a simple and straight-forward way of doing so programmatically/automated, or b) if there are any plans on, or capability of setting up fields similarly to ACF for WordPress in the theme's function.php—where it can be done programmatically.

A real world usage would be;
You build a set of templates (a theme, essentially), and when you update the templates (theme) and you want to apply those updates to a separate install/setup, what is the most efficient and "simple" way of doing so in Craft?

I've looked into the architect plugin, which is great for clean installs, but alas my limited php, or rather sql, knowledge makes it hard to expand into querying for field names rather than ID's. Of course there's the caveat that if you change a field's name, you probably need the ID, but if we forget that rabbit hole for a bit, is anyone sitting on any smart and simple tips for this type of approach?

Anyone had any success with FeedMe or the CraftImport plugins?


texts: How to darken an image using the Imager plugin

texts:
I'd like to 'darken' an image using the Imager plugin. How would I go about doing this?

I'll explain the exact effect I'm after in Photoshop terms: I have an image on one layer, then I create a new layer above it and fill it with black. I then change the opacity of the black layer to 40%. This is the end result that I'm trying to achieve with the Imager plugin (ImageMagick is available too).

I realise I could add a div with a black background over the images and change the opacity of this div, but I think it would be nicer if I could do this with the Imager plugin instead if this is possible.

This is the closest I've managed to get so far, but it doesn't quite match what I'm seeing in Photoshop:

{% set image = block.image.first() %}
{% set transformedImage = craft.imager.transformImage(image, {
  width: 1500,
  height: 700,
  effects: {
    vignette: ['none', 'black', 3],
    modulate: [100, 80, 100],
    gamma: 0.7 }
}) %}

Thanks in advance for any help with this.


texts: Issue with validator getNameReplacementInFolder

texts:
I have issue with the following code:

public function getNameReplacementInFolder(string $originalFilename, int $folderId): string
{
    $folder = $this->getFolderById($folderId);

    if (!$folder) {
        throw new InvalidArgumentException('Invalid folder ID: '.$folderId);
    }

    $volume = $folder->getVolume();
    $fileList = $volume->getFileList((string)$folder->path, false);

The problem if I am using an external filesystem the getFileList is a very heavy API call for the external filesystem. It would be much easier to check the filename in the Asset database, than to check it on the filesystem.

Is there any way to avoid this call? Also if the flysystem driver is poorly written it could stuck in case of huge files or folders.

I badly need solution for disable this call - we can take care the indivudual file nameing, or to tweak it or change it for the database call

Thank you for your help


texts: best approach to call entries from two different sections

texts:
I have set up two sections for two different kinds of events. On one page I want to differentiate between them on the other page I want to list them all. How do I organise that best on the back end and how do I call it best in the template?

big events
small events
overview for all events


texts:
is it possible to replicate the order of related entries in the front end as they appear in the admin entries panel? (see images below)

Right now, in the front end it only sorts the order in which the entries where originally entered (sorted by entry date & time).

If not is there any other possibility to do so?
Thanks


texts: How to hide the assets section of the control panel to specific user groups?

texts:
I need to hide the assets section of the control panel to a given user group.
Changing the group permissions to prevent them from viewing all asset volumes also prevents them from uploading assets in entries, which is not what I want.
I want them to be able to upload new assets but prevent them from snooping around in the asset library.
Is there a way to achieve this?


texts: How to apply a discount on cart weight ?

texts:
I'd like to create a discount that is applied based on the weight of a cart.

I'm working with bottles & boxes of wine, so a bottle of wine has a weight of 1kg & a box of wine can have a weight of 6kg (6 bottles) or 12kg (12 bottles).

I need the discount to only apply when a customer from a certain customer group purchases 12 or more bottles of wine, but can't work with quantity because a quantity of 1 could be 1 bottle of wine or 1 box of wine (which could contain 6 or 12 bottles), hence my desire to apply the discount by weight of the entire cart instead.

I think the best way to do this would be to set up a rule for the customer group, apply it to all products & set a minimum of 1 to ensure that the rule always runs & then add logic in a plugin that fires on some or other discount event that then checks the weight and applies or doesn't apply the discount.

Something like:

craft()->on('commerce_discounts.onBeforeMatchLineItem',
  function($event){
    if( cartWeight >= 12){
       return;
    }else{
       $event->performAction = false;
    }
 });

But I'm having trouble figuring out which event to use & how to put all the pieces together to achieve my desired result.

Any pointers in the right direction would be greatly appreciated.


texts: Failed Stale Template Cache Delete Error...Analyzed...But No Answer

texts:
For some of the extremely static content on my site, I use caching to prevent multiple db queries during every single load. I also have multiple locale on my site with custom cache key names. The actual execution of cache is running perfectly at the moment on all the locales.

However, when I make changes to any entry which has cache enabled, I get stale template delete failed error. When I take look at the actual MySQL table, I see that the requisite cache row is deleted from the table upon making changes to an entry. So I don't quite understand why this error shows up.

Here is a typical cache directive I used in my templates

 {% cache globally using key  "www-features" for 24 hours %}

When I look at the runtime logs, I see following error which I am assuming it to be associated with this problem

  2018/11/03 19:10:42 [error] [application] Encountered an error running task 17 (DeleteStaleTemplateCaches), step 13 of 29: An exception was thrown:
  CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'dateCreated' in order clause is ambiguous.
  The SQL statement executed was:
  SELECT elements.id, entries.sectionId, entries.typeId, entries.authorId, entries.postDate, entries.expiryDate
  FROM craft_elements elements
  JOIN craft_elements_i18n elements_i18n ON elements_i18n.elementId = elements.id
  JOIN craft_content content ON content.elementId = elements.id
  JOIN craft_entries entries ON entries.id = elements.id
  JOIN craft_sections sections ON sections.id = entries.sectionId
  LEFT JOIN craft_structures structures ON structures.id = sections.structureId
  LEFT JOIN craft_structureelements structureelements ON (structureelements.structureId = structures.id) AND (structureelements.elementId = entries.id)
  WHERE ((((elements_i18n.locale = :locale) AND (content.locale = :locale)) AND (elements.archived = 0)) AND (elements_i18n.enabled = 1)) AND (sections.handle IN ('policies'))
  GROUP BY elements.id
  ORDER BY dateCreated. Bound with :locale='en_us'

Looks like you have dateCreated field in multiple tables used in the join and the statement is not explicitly defining the identity of the table ???

Can anyone help me to fix this?


texts: Pass aspect ratio as variable into imager

texts:
I use imager to transform images and I want to pass the image ratio as a variable:

{% set customRatio = 1/1 %}

{% set image = craft.assets().one() %}
{% set transformedImage = craft.imager.transformImage(image,
    { width: 1000, ratio: customRatio })
 %}

This does not work. There is something wrong with how it is passed along. If I pass it as a string: {% set customRatio = '1/1' %}. It doesn't work either. (No errors in both cases).

But when I write it directely into the imager markup like this:

{% set image = craft.assets().one() %}
{% set transformedImage = craft.imager.transformImage(image,
    { width: 1000, ratio: 1/1 })
 %}

Then it works. But why?


texts: Is it possible to exclude entry from search index?

texts: I have some pages that I want to exclude from search results. How can I do this?


texts: Input Tags Template for my Custom FieldType

texts:
I created a custom FieldType that gathers data from 2 different Models. I was able to successfully display it as a Drop Down. My problem now is that there are tooo many records on my array and I would like to have a search instead similar to what craft already has implemented on the Tags Field.

My current template is:

    {%- set class = [
    'select',
    (class is defined ? class : null)
    ]|filter|join(' ') %}

    {% set selectedValue = (value is defined ? value : null)  %}

    <div class="{{ class }}">
        <select {%- if name is defined %} name="{{ name }}"{% endif %}>
    {% if value is not null %}
    {% set selectedValue = value.id %}
    {% endif %}
    {% else %}
    <option value="0" > </option>
    {% endif %}

    {% for test in tests %}
    {% set optionValue = test.id %}
    <option value="{{test.id}}" {% if optionValue == selectedValue %} selected{% endif %}>Test - {{ test.name }}: {{ test.price }}</option>
            {% endfor %}
        </select>
    </div>

Any way I can make it similar to the craft/app/templates/_components/fieldtypes/Tags/input.html


texts: Possible to share assets, templates and plugins across two domains but not all content?

texts:
I've seen many similar questions (Multiple databases, single codebase) but now a little confused on the best approach. This is our first Craft CMS site so still learning the possibilities.

We have domainone.com and domaintwo.com which will be almost identical in design and functionality but the copy throughout will be slightly different as each website is for the same brand but different locations (same country).

In a perfect scenario, both websites will share the same assets, CSS/JS, templates and plugins as they require the same functionality, however, they'll have their own login areas to manage their own content.

Approx. half of the content will be the same i.e. new and used vehicles, but they'll have different pages such as 'about us', 'meet the team' and so on.

Would the best option be to just copy over the plugins, templates etc to a fresh installation and separate the two completely or is there a way to achieve this 'perfect scenario'?


texts:
I'm considering using Craft for a new site. One requirement will be allowing members to upload and manage images. With Craft, can I set a size requirement for member uploaded images? So for example, if I only wanted to allow 400x400 image size to be uploaded, could I lock it down so that any image smaller or larger will just give an error?

If that's not possible, is there a way to resize/crop a large image down to the correct size?


texts: How to show a product from a field entry

texts:
I'm trying to bring in recommended products for adding to a bigger purchase. I set up a simple matrix but can't seem to figure out how to pull product information. This is what I have so far, it throws no errors, but it also gives nothing.

{% for block in product.recommendProduct %}
    {% set i = i + 1 %}

           {% set image = block.chooseProduct.mainProductImage.first() %}

{{ block.chooseProduct.title }}

{% endfor %}


texts: What is the best way to make text that has html translatable?

texts:
I have a block of text I'd like to make translatable. Within that block of text there is a link.

The following works:

{{ "Lorem ipsum. Aenean commodo ligula eget dolor."|t({
    url: "#"
})|raw }}

But doesn't feel like the best way to do it as the translation file now requires HTML:

craft/translations/en_us.php

<?php

return array(
    "Lorem ipsum. Aenean commodo ligula eget dolor." => "Lorem ipsum. Aenean commodo ligula eget dolor."
);

Are there any other ways to do this that lead to a better separation of translatable text and HTML that relates to how the translator can interact with that text?