texts: Output first matching matrix block model if condition is true

texts:
I've run into situation, where I have to loop only once, if condition has met the requirements. The condition is controlled by matrix block field ligthswitch which is the field in finish.

Matrix structure:

Actually, I've ended up doing this:

{% for block in entry.productSettings.type('finish') %}
   {% if block.inStock %}
      {{ block.amazonUri }}
   {% endif %}
{% endfor %}

which outputs cluster of characters: 123456.
Bear in mind, that total count of characters is count of loops. Desire output is 1.


texts:
A website I built frequently throws up the following code instead of the homepage:

<?php

// Path to your craft/ folder
$craftPath = '../craft';

// Do not edit below this line
$path = rtrim($craftPath, '/').'/app/index.php';

if (!is_file($path))
{
    if (function_exists('http_response_code'))
    {
        http_response_code(503);
    }

    exit('Could not find your craft/ folder. Please ensure that $craftPath is set correctly in '.__FILE__);
}

require_once $path;

I have followed the Craft CMS install guide to the letter. Here's the output from php.ini:

engine = On
zend.ze1_compatibility_mode = Off
short_open_tag = On
asp_tags = Off
precision    =  12
y2k_compliance = On
output_buffering = Off
zlib.output_compression = Off
implicit_flush = Off
serialize_precision = 100
safe_mode = Off
disable_functions =
realpath_cache_size=256k
expose_php = Off
max_execution_time = 600     ; Maximum execution time of each script, in seconds
max_input_time = 6000   ; Maximum amount of time each script may spend parsing request data
memory_limit = 768M      ; Maximum amount of memory a script may consume (128MB)
error_reporting  =  E_ALL & ~E_NOTICE
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/sites/t/domain.com/public_html/error_log
log_errors_max_len = 1024
report_memleaks = On
track_errors = Off
variables_order = "EGPCS"
register_globals = Off
register_argc_argv = On
auto_globals_jit = On
upload_max_filesize = 100M
post_max_size = 100M
magic_quotes_runtime = Off
magic_quotes_gpc = Off
magic_quotes_sybase = Off
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
extension_dir = "/usr/newage/lib/php/extensions/no-debug-non-zts-20151012"
enable_dl = Off
file_uploads = On
upload_tmp_dir = /tmp
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
date.timezone = Europe/London
mysql.allow_persistent = On
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
mysql.connect_timeout = 60
mysqli.max_links = -1
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = On
[Session]
session.save_handler = files
session.save_path = /tmp
session.use_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 0
session.gc_divisor     = 100
session.gc_maxlifetime = 14400
session.bug_compat_42 = 1
session.bug_compat_warn = 1
session.referer_check =
session.entropy_length = 0
session.entropy_file =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0

#zend_extension="/usr/newage/lib/php/extensions/no-debug-non-zts-20151012/ioncube_loader_lin_5.6.so"
#zend_extension_ts="/usr/newage/lib/php/extensions/no-debug-non-zts-20151012/ioncube_loader_lin_5.6_ts.so"
#zend_extension=/usr/newage/lib/php/extensions/no-debug-non-zts-20151012/ZendGuardLoader.so
always_populate_raw_post_data=-1

The error log set in php.ini is showing up empty.

Via the Craft CPanel, I'm seeing the following recurring errors from the logs tab:

Here's the Server info via the Craft CPanel:

My host has told me that ImageMagick isn't available on the PHP version I'm running (7.1).

For iconv extension, the info bubble is reading:

  You have a buggy version of iconv installed. (See PHP bug #48147 and
  iconv bug #13541

My host has recently fixed load issues on one of their hosting clusters, which I initially thought might be causing the problems, but I'm still getting 503 errors.

This may be unrelated, but the site also jumps from having normal permalinks, like so:

https://www.domain.com/pretty-page-url

To messy permalinks, like this:

https://www.domain.com/index.php/pretty-page-url


texts: How can I import existing users with passwords stored in a different format than Craft's hash format?

texts:
Se need to import a large user table to a Craft installation. Unfortunately, the passwords in the imported data are SHA1 encrypted (and salted).

What is the best way to enable the login of the users?

We thought that we add an extra column to the table which defined if the hash is standard or SHA1.

If a user logs in where the password is SHA1, then we check if it's the correct password and change it to the standard hash.

This would be the most comfortable way for the existing users.

Question: Is this a possible solution, especially is it possible to hook up into the login process to create the logic for the check.

Or would you recommend other solutions?


texts: Does Craft/Twig help with cache-busting js/css?

texts: Usually, I would use PHP to append the filetime of a file provide cache-busting. Does Craft or Twig do anything that can help with this?


texts: Craft Nitro PHP extension ext-zip * is missing

texts:
I'm not particularly tech minded so MAMP has served me well for a good while.  However I more recently decided to give Craft Nitro a try.  I got everything (Multipass and Nitro) set up really easy.  I then went to create a project and got the error PHP extension ext-zip * is missing.  I've seen this before and worked around it guided by This post.
All good...  craft installed.   However, now i'm confused?  Why did I need to install an older version of PHP on my host machine (OSX) when Nitro is supposedly a self contained 'box' with everything needed for a Craft install?


texts: How are changes to the dashboard scoped?

texts:
I'm working on a Craft project with another developer. We're connected to the same shared database but my dashboard is different than his (I customized mine).

This made us wonder how the custom dashboards are scoped. Are they based on user? Or are they based on a user group and "super admins" have their own individual scope?


texts:
I have made a simple plugin (with pluginfactory.io) that has been working perfectly so far. But after taking it to our live test-site it is causing the /admin/settings page to stop working, throwing the error that the plugin's settings template cannot be found.

  [error] [exception.Craft\TemplateLoaderException] Craft\TemplateLoaderException: Unable to find the template “pluginname/pluginName_Settings” in "settings/_index" at line 8. in /craft/app/etc/templating/twigextensions/TemplateLoader.php:123

I have dumped the production DB and imported it locally, I have checked that the files exists both in git and on the server, but I still only get this error on the server, everything is working fine locally.

Any ideas what could be causing this?

public function getSettingsHtml() {
    return craft()->templates->render('pluginname/pluginName', array(
        'settings' => $this->getSettings()
    ));
}


texts:
Versions:
 - Craft CMS (3.1.21)
 - Craft Commerce (2.1.2)
 - Stripe for Craft Commerce (1.2.0)

Problem:
- My website offers user's ability to subscribe to several subscriptions at the same time. Currently, I have created products that represent each subscription so they may be added to the cart. These products are purchased like a regular 'purchasable' element.

My plugin listens to the event EVENT_AFTER_COMPLETE_ORDER and finds all subscriptions that were in the completed order.
I could create each subscription individually using Craft's createSubscription() method found in craft\commerce\services, but doing so causes multiple invoices to be sent out to customers and each invoice created is also charged a fee by Stripe.

My Goal is to create one subscription that contains several subscriptions inside of it (https://stripe.com/docs/billing/subscriptions/multiplan). This would only generate one invoice.

I am able to use the Stripe API to do this successfully but at the cost of bypassing Craft. Is there a way to do this through Craft so it knows about all subscriptions that have been created?


texts: Entries not being searched in the control panel

texts:
I have a 'person' channel that does away with the title field and instead uses custom fields like so {lastName}, {firstName}.

However, I've noticed that when I'm looking at the entries listing in the control panel and I search for 'Hamilton' as an example (I have 3 entries where the surname is Hamilton) - only 1 of the entries returns.

I even tried adding myself as an entry to the channel but searching for Grant or even Steven - I get no returns.

Can't figure out why this would be?


texts: Defining TwigExtension globals in Craft 3

texts:
A long time ago I asked how I could utilise the getGlobal method in Craft 2.x.

I'd like to know how best to do this in Craft 3?


texts: Can two sites use the same channel, but have unique entries?

texts:
I have a multi-site application where my primary site is my company's main website, and the additional sites are small "microsites" for some of our projects.

I want to share channels between my sites. For example, I have a "testimonials" channel with a basic quote & cite fields in the entry type.

I want to make this channel available to all my sites, but I want each site's testimonials to be unique, since they're about different projects. I also don't have the same number of testimonials for each site.

I made the channel available to each site, then created the testimonial entries within each site's tab. I thought this would keep each site's testimonial entry list separate, but it instead made one big list.

Is there a way that I can do this through filtering or site groups? I don't want to have to create a unique channel for each site that has the exact same functionality.

Edit: I've found that I can fudge this by using the "Enable for this site" lightswitch on each entry, but I don't trust my content editors to properly use this function, and I don't want them to have to see all the disabled entries from other sites in the entry list.


texts: Order of {% set %} tags changing output unexpectedly

texts:
I have a content builder matrix that I'm looping through to build my page. That code works with no problems.
{% set content = entry.pageBuilder.all() %}
{% for block in content %}
    {% include "blocks/_" ~ block.type ignore missing %}
{% endfor %}

Above that block, in the same template, I'm trying to create a text blurb from one particular field type within that matrix. When I try to define what field to pull the blurb from, suddenly the above code only outputs the content of the blurb field. This is the code that breaks my template:
{% set blurb = entry.pageBuilder.type('copy,faq').limit(1).all() %}

But, if I move it below the "set content..." chunk, it works as expected.
It seems like these should be two completely unrelated chunks of code, and I don't understand why the "set blurb..." code is interfering with the other code when placed above it. Am I missing something?


texts: How can I check on the value of a template variable?

texts: If I'm used to PHP's var_dump() and print_r() to check the value of a variable, how can I evolve to inspect things in Craft where Twig's dump isn't available?


texts: Craft Installation Next Button Not doing anything

texts:
I am in the first step of the installation. I entered my email, username and password and clicked on the next button, but it is not doing anything.

It makes a post request to:
/var/www/html/test_craft/craft/app/index.php

And a Get request to:
http://localhost/public/index.php?p=admin/resources/images/spinner_submit.gif&d=1465331044

Looks like the get request is not returning anything because in firebug, the response is a spinning wheel.


texts:
Is there a way to fetch the content generated by the Element API via a plugin.

For example, if we have created an ingredients/<slug:{slug}>.json endpoint, can the data for a specific page (eg ingredients/lemon.json) be queried at the code level without having to fetch it via curl or similar?

Cheers,

Cole


texts: Charge/Stripe and "Missing required param: exp_month."

texts:
I'm working on getting charge to take donations and have set up my Expiration date field the same as in the demos.

    Expiration Date
    <input type="text" class="form-control" data-stripe="exp"  id="cardExpiry" placeholder="mm / yy" required>

However on form submission (in test mode) I see this error.

  Missing required param: exp_month.

Not sure how to resolve this. Please advise


texts:
Is there a way to partially match text in a URL segment? I would like to conditionally show code if the text "vascular" is in Segment 3.

If my URL is: https://website.com/segment1/segment2/10009-vascular-access

This is what I've tried so far...

{% if craft.request.getSegment(3) == 'vascular' %}

{% if craft.request.getSegment(3).contains("vascular") %}


texts:
This is probably a newby question, but, I am just trying to add a basic email send test and my twig page does not like the dollar signs.  Is EmailModel built-in to craft or is there a plugin I need?

I am just trying to add this code to a basically empty twig page:

$email = new EmailModel();
$email->subject = "Thanks!";
$email->htmlBody = "
Congratulations!
htmlBody .= "
Hello World
";
$email->fromEmail = "email@domain.com";

thanks for the help...

Chip


texts:
For some reason when we're bootstrapping Craft CMS it's VERY slow to bootstrap (500ms) worth of slowness. This is utilizing HTTP2 and PHP7 so we're expecting it to be much faster than this.

I'm assuming this is just some setting we're missing and/or our Craft installation is doing too much for one app.

I changed the _layout.html to this:

<!DOCTYPE html>

    <title>TESTING</title>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />

TESTING IN THE BODY

Not much going on there. However, this is still taking 500-600ms to bootstrap. This is my general.php file --

<?php

require __Dir__ . '/../../vendor/autoload.php';
require_once __Dir__ . '/../plugins/global/config/Environment.php';

//error reporting
if (Craft\Environment::isProduction()) {
    //log all errors except for notices, strict php guidelines, etc
    error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_DEPRECATED);
    ini_set('display_errors', 0);
} else if (Craft\SayEnvironment::isDemo()) {
    error_reporting(E_ALL & ~E_STRICT & ~E_WARNING);
    ini_set('display_errors', 0); //don't display errors to console in demo
}

return array(

//////////////////////////
///  Default Settings  ///
//////////////////////////
'*' => array(
    'useCompressedJs' => false,
    'appId' => 'myappid',
    'validationKey' => 'asdfasfdasdfasdfasfasd',
    'timezone' => 'America/Chicago',
    'omitScriptNameInUrls' => true,
    'generateTransformsBeforePageLoad' => true,
    'maxUploadFileSize' => 33554432,
    'phpMaxMemoryLimit' => '512M',
    'slugWordSeparator' => '-',
    'enableCsrfProtection' => true,
    'devMode' => false
),

////////////////////////
//  Local Overrides  ///
////////////////////////
'localhost' => array(
    'cacheMethod' => 'file',
    'overridePhpSessionLocation' => false,
    'environmentVariables' => array(
        'siteUrl' => 'https://localhost/'
    )
)

);

Realistically all I'm asking Craft to do right now is bootstrap itself and load this _layout.html file. Any ideas why this implementation might be slow? We have 15-20 large plugins but we're not really doing anything with them in this instance?


texts: Live Preview in different languages on different top level domains

texts:
Our website offers three different languages. Each language has it own top level domain (example: domain.de, domain.it, domain.fr). Everything works like it should, except the Live Preview function. We have already tryed the things described here: https://craftcms.com/support/cross-domain-live-preview and a few other tweeks we found in stackoverflow. Every solution we found, only works with subdomains.

As i understand, it's not possible because the browser does not allow cookies accross domains (Cross-Domain Policy).

Does anyone have experience with handling various languages and top level domains in Craft CMS? How can we handle this requirement?


texts:
I'm  trying to get the _POST data for my form in a plugin, and for whatever reason am unable to get the selected option from a select tag:

 <form class="parseResults" action="actions/MyPlugin/myFunctionAjax" method="post" name="submitResults">
    <select name="submission">
        <option value="view">View</option>
        <option value="submit">Submit</option>
    </select>
    <textarea rows="9" cols="80" name="content"></textarea>
    <input type="submit" value="Submit" name="submit">
</form>

And then in my plugin, I can get the textarea form content like:

    $formContent = craft()->request->getPost('content');

But when I try to get the selected option from the #submission select, nothing returns

    $submissionType = craft()->request->getPost('submission');

What am I missing or doing wrong in order to get the selected option?


texts:
Basically I want to add certain parameters to my 'craft.entries' based on whether a variable is set:

{# Get a start date value from the URL (my use case) #}
{% set start_date = craft.request.getSegment(3) %} {# e.g. '2015-12-10' #}

{% if start_date != "" %}

  {# Create .after() param #}
    {% set startDateQuery = ".after(" ~ start_date ~ ")" %}

{% else %}

    {# If there is no start date then set the param as "" so nothing happens #}
    {% set startDateQuery = "" %}

{% endif %}

{% set entries = craft.entries.section('events') ~ startDateQuery %}

{% paginate entries as pageInfo, pageEntries %}
  ... Do stuff

I've tried this other ways as well, but this one seemed the most appropriate. Either way, it's not working and I was wondering if anyone might know why - or have a suggestion of a better method?

Cheers!


texts:
this is my first Craft CMS & Commerce build and I need some help with searching products by a tag field.

I have a tag field ("designTag") for each product and I would like to have a search bar that will only query the tag field for a specific product type ("designMedia") and return those products with matching or similar tag titles and also account for pagination. I can't seem to get it to work. Any help would be appreciated.

SEARCH FORM CODE:

<form action="{{ url('design/keywords') }}">
    Search By Keywords

        <input type="search" name="q" class="form-control input-lg" placeholder="Enter Keyword...">
        <button class="btn" type="submit"></button>

</form>

RESULTS CODE:

{% set tagTitle = craft.request.getParam('q') %}
{% set tag = craft.tags.title(tagTitle) %}
{% set product = craft.commerce.products.search(query).order('score') %}

{% if product|length %}

{% paginate craft.commerce.products.type('designMedia').limit(48) as mediaProducts %}

{% for product in mediaProducts %}

{% endfor %}
{% else %}

No Results

{% endif %}

/*pagination code */
{% endpaginate %}


texts: How can I set live preview's minimum interval?

texts:
New Relic reporting seems to show a strong correlation between the previewEntry method's transactions and a couple of recent apdex-based alerts (the periods indicated by the pink background):

(The third period of previewing shown near the end of the chart is my failed attempt to trigger an alert; perhaps my test entry was less intensive than the client's.)

To cut down on the number of previews generated, how can I set a minimum interval between preview update POSTs, such as five seconds?

Update: we think it likely that the alert from New Relic was not actually a problem in terms of performance, and that it's simply a case of all/most of the requests during those periods taking longer than usual. It's a relatively quiet site, and so the live preview POST requests can easily represent 100% of requests. So I'm not so worried about this now, but it might still be nice to be able to set a minimum interval between live updates when the live update feature has been activated.


texts: How to check how many characters there are in my string?

texts:
Lets say I have a simple string:

{% set string = "Simple String" %}

How to get number of characters of my string?


texts: Displaying An Entry's Image on Edit Page

texts: Currently, these Entries display just the title. Has anyone found a way to display entries as a thumbnail (from it's image field)? I'm starting to look at plugins, but haven't seen anything that would help yet.


texts: How to apply sales to custom order adjustment?

texts:
Is it possible to apply a discount voucher to custom order adjustments? EG i want 5% off everything. I have two order adjustments, one is rush delivery and the other is an engraving fee.

At the moment i can only seem to apply it to the delivery and products in the order.


texts:
Is there a twig filter to encode special characters like umlauts:
{{ entry.title | filter }}

  Datensätze & Karten

Which then should result in:

  datensaetze-karten

Basically what 'convertFilenamesToAscii' => true, does but as a filter.

I want to use this as a anchorlink later on so umlauts are not the best to have in anchor links.


texts:
Does anyone have any recommendation on how to reformat the Commerce checkout workflow to be on one page? More specifically, how to pass the address/customer info before the payment info without having to redirect to another page? I've tried combining them into one form without success.

Thanks!


texts:
I have started using imgix on some non-Craft sites, and it’s bloody awesome. It’s a bit similar to Craft in the way you apply transforms to a master image, and those transforms are done on-demand and then cached for future use. Only with imgix the transforms are done in the cloud and stored on their global CDN. Now I was thinking if it might be possible to write a Craft plugin to use imgix instead of the internal image handling code.

Any tips/pointers on how to go about this would be most appreciated!


texts: How to skip the first few entries in a "load more" scenario with Element API?

texts:
I have a website that uses a "load more" button. The process for this button can be found here:
http://craftsnippets.com/articles/infinite-scrolling-and-lazy-loading-with-craft-cms
I made it pretty much verbatim (structure-wise with Element API) to that article, but I want to skip the first 6 entries because they are featured elsewhere on the site. So I tried to add .offset('6') to the for loop, and that did skip the first 6 entries. But when the "load more" button is clicked it would display the second 6 entries again (duplicates) then when you click the button again it properly continues down the list of entries.
So, how can I skip the first 6 entries in this scenario without having duplicates?


texts: in a for loop, how do i only display entries of a certain category?

texts:
I see a few answers that look, hopefully, way more complicated than I'm looking for. I simply want to loop through entries with a normal for loop like:

{% for entry in craft.entries.section('News').limit(1).all() %}
loop through entries of a specific category only here
{% endfor %}

Is there no way just to throw on something like .category('BreakingNews') onto that chain?


texts: Dynamic URL generated by a custom field dropdown value

texts:
I have a special case where the URL needs to be defined from within the entry itself. I have a dropdown that I want to populate with the URLs as values.
Can the dropdown value be used to generate the URL? I can not use custom site URLs because the customer/user needs to see the URL themselves from within the entry.
The entry is a channel.
So let's say the dropdown has a label called "Monkey". Then I want the URL to be /monkey/article-slug.


texts: Webhooks: Filter Entry by type (or Section)

texts:
Using the Webhooks Plug-in, I'm looking to specify a "scope" (or filter) for content type (or section) when using the saveEntry event.

Example:  Fire a webhook only when a new entry of specific type (say recipe ) is saved... not any/all new entries.

My config for my webhook is:

Sender Class = craft\elements\Entry

Event Name = afterSave

Filter = Element is new: ON

Filter options provided allow to filter out new entries, but not entry type.

My solution for now is to try and filter the incoming JSON on my endpoint and only trigger when I see the right Entry Type (untested yet), but would be nice to not send JSON on every single new entry to my webhook if I don't have to.


texts: Supporting LongBlob / LongBinary in Craft record ColumnType

texts:
Why is LongText supported but not LongBlob for Craft records? Is it because of the reliance on Yii? Is there some way I can circumvent that and hard-code that change to the DB, (i.e. changing a field from blob to longblob), without having to change any core Craft code?

Currently my field looks like that:

'data_blob' =>   array(AttributeType::String, 'column' => ColumnType::Binary),

I'd like to be able to have LongBinary (or longblob in mysql) as I'm reaching the max length for blob and my data is getting truncated.


texts: Craft Locales and translatable image field

texts:
I´m working in a multi country website ( resolved with locales ) with products, and each product will show information for each country and the product image could change from one country to another, but the picture will usually be the same. Because the image can change for each locale, i check it like a Translatable field, but i realize that the client will have to fill the image field with the same image for each of the 4 languages, resulting in extra work to enter each product... so my question is:

Is there a way to assign the image in the default locale, and the others locales taking this image as default, except that you specify an image for that language specifically?

Thanks!
Sebastian


texts: Login Page Logo and Site Icon gives 404 in Craft 3

texts: I have update the craft version from 3.0.2 to 3.0.3.1, after that Login Page Logo and Site Icon gives 404 path error. I have checked file permissions also but it is not creating link in cpresources folder while it is showing url in frontend. In local its working fine.


texts:
Sometimes the links are in-page, sometimes they point outside. I want to be able to create an array menuitems that is passed to an include and which then generates a per-section index menu on the page.

I currently have the approach below, but I'm a little annoyed that I have to loop through projects twice because of Twig's scope. Any better ideas?

template projects.html

{% extends "_layout" %}
{% set title = 'Projects' %}
{% set projects = craft.entries.section('projects').find() %}
{% block submenu %}
    {% set menuitems = [] %}
    {% for project in projects %} {# first loop #}
        {% set menuitems = menuitems|merge([project.title]) %}
    {% endfor %}
    {% include '_includes/_submenu' %}
{% endblock %}
{% block content %}
    {% for project in projects %} {# second, unnecessary loop #}

{{ project.title }}

    {% endfor %}
{% endblock %}

template _includes/_submenu.html

    {% for item in menuitems %}

{{ item }}

    {% endfor %}


texts: In the footer at the bottom of my page, www.soldierswish.org, there are two links for 501c3 and Form 990. Is there no way to edit these from the GUI? How do I edit these links?


texts: Route to entry in Arabic not working but category route is OK

texts:
I have successfully managed to route Arabic categories to a custom template. The Arabic URLs appear RTL which is strange (and correct?), but I cannot get the Arabic single entry to pick up the template. The image below is an example of the category route working for French and Spanish but not for a single entry in Arabic. This is on Craft 2.

Does anyone know why this wouldn't work?


texts: ElementCriteriaModel andWhere() with different comparison operators?

texts:
I'm trying to do an andWhere() "OR" group for a special criteria value so basically when building an element criteria I want to just set `$criteria->upcomingOnly to true, and then have the following code run. The problem is that the greater than or equal to is being added to the value and its doing an equals comparison on it which obviously is going to return nothing. Anyone have any idea what I need to change to get desired result?

if($criteria->upcomingOnly) {
    $today = new DateTime('now');
    $query->andWhere(['or',
        ['events.eventStart' => '>= ' . $today->format('Y-m-d')],
        ['events.eventEnd' => '>= ' . $today->format('Y-m-d')]
    ]);
}

Basically the resulting query is

WHERE ((elements_i18n.locale = :locale) AND (elements.archived = 0)) AND ((`events`.`eventStart`=:pzek8XoNML) OR (`events`.`eventEnd`=:pZQmaPhwE8))
GROUP BY `elements`.`id`
ORDER BY `eventStart` ASC LIMIT 50. Bound with :locale='en_us', :pzek8XoNML='>= 2017-10-06', :pZQmaPhwE8='>= 2017-10-06'

And I would like to get something like this:

WHERE ((elements_i18n.locale = :locale) AND (elements.archived = 0)) AND ((`events`.`eventStart`>=:pzek8XoNML) OR (`events`.`eventEnd`>=:pZQmaPhwE8))
GROUP BY `elements`.`id`
ORDER BY `eventStart` ASC LIMIT 50. Bound with :locale='en_us', :pzek8XoNML='2017-10-06', :pZQmaPhwE8='2017-10-06'


texts: Empty cart should remove coupon discounts in commerce

texts: Is there anyway to remove all the discounts if cart becomes empty?


texts:
I have a simple caching setup on this site. I have a layout template that extends it has this:

{% block content %}
    {% cache %}

my content

    {% endcache %}
{% endblock %}

And i have 'enableTemplateCaching' => true set to on for the production site in my config.

Since upgrading Craft from quite a old version to the latest as of a few weeks ago, the cache seems to have gone a bit haywire.

If i clear the cache and then load the pages, all seems well, but then if i edit a template for example, elements on some pages don't output.

One example is a map block, if i edit the latitude for the js in that block and then save that template, it doesn't output the js from that block which btw uses {% includeJs myJs %}. Other template elements seem to be missing also in other places.

This all worked before, but doesn't now, no idea why!


texts: Unable to access login page or my website

texts:
I have been unable to access my website or log into my CMS. I have checked with the server and everything is OK there but all I am getting is a blank page.

I updated craft manually following the instructions given.

I also have a staging site which I use for sharing with my client and this all works fine.

Is there anything I need to be checking? What will have stopped the website from working? I would really appreciate any help you can give with this.

Thanks in advance.


texts: I want to display an entry's tag next its title in a list of entries, and on the entry's detail page. For example, for a blog. How do I do that?


texts: Is there any plugin that allows admin user to edit localization files from backend interface?


texts: Does Craft save dates in the locale format?

texts:
I have a website with multiple locales (English, Dutch, French, German and Spanish). I'm saving dates on a front-end form through Ajax, but it seems that Craft saves the dates in the locales' format, eg. in English, the 1st February 2018 would be 02/01/2018 and in Dutch it would be 01/02/2018.

I'd think Craft would save all dates in the same format, disregarding any locale. I read somewhere that craft saves all dates in UTC format.

When I'm in the locale EN and I pass the date 01/02/2018, expecting 2nd January 2018 to be saved, it saves OK.
However, if I'm in NL, DE or FR and I pass the same date, it is saved as 1st February 2018 as these languages switch the day and month around.

I always pass MM/DD/YYYY to the date field whatever locale.
I'm using the dateFns library for formatting and the date it formats is correct. I use VueJS v-calendar as a datepicker which also shows everything correct.

But when it's saved to Craft it suddenly switched day and month in the back-end!

Any help or explanation, please? Seems like strange behavior choices.


texts: {% Exit 404 %} doesn't work right with routes

texts:
The {% exit 404 %} doesn't work right on routed templates.

It's fine on pages that aren't affected by routes. Mysite.com/asdfasdf shows me the proper 404 page.

I've got some routes configured like this:

URL: projects/type/*
Template: _projects/category.twig

URL: projects/*
Template: _projects/entry.twig

In the top of entry.twig, I've got code that says:

{% set entrySlug = craft.app.request.getSegment(2) %}
{% set entry = craft.entries.slug(entrySlug).one() %}

{% if entry is not defined or entry is null %}
    {% exit 404 %}
{% endif %}

{# regular page template below here #}

mysite.com/projects/WorkingProject - this works right.
mysite.com/projects/BrokenProjectLink - gives me a 500 error.

When I turn on dev mode, the Yii debugger gives me a 404 ( HTTP 404 – Not Found – yii\web\NotFoundHttpException ), which is the right thing. But turning devmode off, I don't get the 404 page, I get my 500 Internal Server Error page instead.

Again, 404s for pages that don't have any routing work fine. It's just things that are getting routed, and using the {% exit 404 %} code.

This all worked in v3.3.20 and earlier, but it doesn't seem to work the same in Craft 3.4.0.2.


texts:
How would I get the global variables associated to other sites?

For example, in an instance where I have three websites under the group languages for the English, Spanish, and French versions. I have specified companyInformation globals that contain: phone, address, and logo.

From a template I would like:
- Loop through all sites under the group languages
- Get companyInformation global values for each of the sites

Thanks in advance


texts: Direct access call for a twig template from a twig template gives 404

texts:
I'm trying to call for a Twig template _template from a Twig template, particularly from within AngularJS <script type="text/javascript"></scirpt> tags. A console log says, that the file was not found on the server with status of 404. Using {% include '' %} or {% embed '' %}interferes with AngularJS somehow. Does any way around exists to access that Twig template, without breaching the security?

Troubleshooting part of js:

$mdDialog.show({
  templateUrl: '_template',
})


texts: How to get an Entry in structure and all of its children and it's children's children with Element APi?

texts:
How do I get all of an entry's children using the Element API?

I want to return something like:

data: [
    title: 'Root Entry'
    uri: 'root-entry'
    children: [
        {
            title: 'Level 2 Entry'
            uri: 'level-2-entry-1'
            children: [
                {
                    title: 'Level 3 Entry'
                    uri: 'level-3-entry'
                    children: [...]
                },
            ]
        },
        {
            title: 'Level 2 Entry'
            uri: 'level-2-entry-2'
            children: [...]
        },
        {
            title: 'Level 2 Entry'
            uri: 'level-2-entry-3'
            children: [...]
        },
    ]
]

I would want to get all entries up to the depth level of 4. Some entries wont have children past level 3 and some wont have any past level 2. I have tried doing a for loop traversal but cannot figure out why $entry->children returns everything but children entries.


texts: I have a venue search tool which has two categories - event type and event size. How do I create an entries loop that returns entries that have both categories assigned?


texts: Prevent redirecting to the control panel from a URI of "/login" when logged in

texts:
I have a top level page that needs the URL of "/login/". It has nothing to do with an actual Craft login.

If I have a logged-in session, that url redirects me to the dashboard (via UsersController->actionLogin).

If I'm logged out, the page renders fine.

I thought setting craft.config.loginPath to something other than "login" would fix it, but it didn't seem to have an effect.


texts: What's the differences between the Mailer and the Message classes?

texts:
In the Craft 3 Class Reference (https://docs.craftcms.com/api/v3), there are two classes under craft\mail:

Mailer
Message

I found that I was able to send an email using this:

<?php

use craft\mail\Message;

$message = new Message();
$message->setTo('john@doe.com');
$message->setSubject("Hello world.");
$message->setHtmlBody("Hello world.");
$message->send();

But I found in some examples, like this one, that the email could be send using Craft::$app->mailer->send($message) instead of $message->send().

What's the difference between the Mailer and the Message classes? When should I use one instead of the other?


texts:
I'm fairly new to using macros and haven't found anything online regarding this — sorry if this is a possible duplicate post.

I've created a macro with 7 possible parameters but on different templates I want to add to the default classes.

{% macro button(label, link, width , classes, colours, textclasses, alignment) %}

{{ label }}

{% endmacro %}

Is there a way of doing this without having to set a variable with all the defaults in it and tacking on new classes? For example:

{% set buttonClasses = "absolute w5-ns l-50 tc pa2 pa3-ns ph3 br2 z-max link white f6 flex mt--18 mt--25-ns underline-hover tracked-more" %}
  {% if buttonPosition == 'above' %}
    {% set buttonClasses = buttonClasses ~ " top-0" %}
  {% endif %}
{{ macros.button(block.ctaText, block.ctaLink.one().url, "", buttonClasses) }}

Any help would be appreciated!

— Thanks


texts: How can I check if a plugin is installed and enabled, in Craft 3?

texts:
In a question I asked a few years ago, it was very simple to perform a check on wether a plugin was installed or not.

As of Craft 3, the same methods don't seem to work. The likes of this always returns true:

{{ craft.myPlugin is defined ? 'Installed' : 'Not Installed' }}

Is there another way to determine if a specific plugin is installed and enabled?


texts:
I have a template, /calendar, which outputs a list of all entries from the events channel. If a user clicks a link for "July 2015", I want the same template to load showing only the events for July 2015. I can fetch the entries for a given month with something like this.

{% set setMonth = '2015-07' %}

{% set firstDay, lastDay
   =
   setMonth ~ '-01',
   setMonth ~ '-' ~ setMonth|date('t')
%}
{% set after, before
   =
   firstDay|date_modify('-1 day')|date('Y-m'),
   lastDay|date_modify('+1 day')|date('Y-m')
%}

{% set events = craft.entries.section('events').after(after).before(before)
%}

I want to pass the date that will be assigned to setMonth in the URL using something like /calendar/2015-07, but I currently get a 404 error.

How can I pass the date in the URL without throwing a 404?

To make it even more complex, this template can also be filtered by category, so there would also be times the URL would look something like /calendar/catslug/2015-07. In this case, the template should display only the July events from the catslug category.

Assuming I can conquer the aforementioned 404 problem, will Craft still recognize /calendar/catslug/2015-07 as a category-triggering URL, or will the addition of the date segment break that functionality?

I suspect this isn't as difficult as I'm making it, so any assistance is appreciated.

Thanks in advance.


texts: (content) Propagation + website in multiple languages

texts:
Currently we're developing a craft multi-site that has 3 languages (nl, fr, en). It's an upgrade (new style, removing junk, ..) from another cms so the content has to be inputted manually.

We've used a NEO block with different options for the layouting the content.
Now because 80% of the content is the same for the 3 languages, the propagation method for this block was set to "Save blocks to all sites the owner element is saved in".

Almost all of the content has been added, except for the last 20% which differs in some blocks not existing in certain languages.

Now we wanted to change the propagation method, but this deletes all the blocks in the others languages when we save an entry.

Is there a way to change the method without overwriting our data?

Thanks in advance!


texts: Listing all entries in one section related to entries written by currentUser in another section

texts:
The setup:

Section A (entries I want to list)

Section B

entries field (related to 1 entry from SectionA)

My goal is to list all entries from Section A, that are related to an entry in Section B  authored by the currentUser.

Right now what I'm doing is looping through all entries in Section B authored by the current user and querying/displaying the entry related to it, but it's way too inefficient and eats up a lot of database queries. Was hoping there's a more efficient way of doing this.

Not sure whether or not there's a way to achieve this sort of relation via a complex relatedTo or if I need to go another route.

Can provide additional information/clarification if anything is unclear.

Thanks


texts: Correct Multisite MultiLanguage Approach

texts:
I am having a website with 4 languages and has two main sections B2B and B2C.

So the final URLs will look like this:

@web/b2b/de
@web/b2b/
@web/de (b2c uses no indication in the link - is default)
@web/
@web/tc

Some articles might be at b2b, some at b2c and some might be at both.

My approach to this is to have two site groups

B2B
B2C

and then for each of these categories is to have the site in it's 4 different languages.

Is this approach correct?


texts: Displaying related image assets from another section with twig

texts:
I have a site that shows upcoming football matches in a table, and I would like to include the clubs' logos next to each club name.

I have the following sections and entry types, both generated using an API and feedme to create entries

Teams section (includes fields for teamIDs and logos)
Matches section (includes fields for home team & home team ID, away team & away team ID, match time and location, but does not include logos)

The team ids and home/away team IDs match.

To display logos, I imagine the process should go something like this:

for each hometeam and awayteam in each row of the match table, identify the team ID
Use the ID to find the related teams in the teams section,
output the asset (logo) related teams logo in the match table.

This feels like a relatedTo / reverse relations problem, where i can say - in twig - something like:

{% if homeTeamId or awayTeamId in the fixtures section is the same as a Teamid field in the Team Section, then output that related teams's logo. %}

Can anyone suggest the most efficient way to structure this in Twig?


texts:
How can I request the url for a channel index page from another page. I got this message asked on twitter towards craft, but they misunderstood my question.

The came back to me using craft.request.getSegment(x), but this will only work if I would like the index page of a channel when I'm on the entry page of this channel.

But how would I get the url for the "news" channel index page, when I'm in the "projects" channel section (either the index or an entry) of the site?

News is an entry-field of projects btw, so that we can show news related to a project on the site.


texts: Force donation purchasable to replace donation of the same amount in cart

texts:
I'm using Craft Commerce Lite and the donation purchasable. I don't want users to ever be able to add more than one donation to the cart. Using the Lite edition stops users from being able to add donations with different amounts since those would need two line items. In the docs for Adding the Donation to the Cart

Customers can add more than one donation to the cart, but the line item will be replaced if the optionSignature remains the same, just like it does for any purchasables added to the cart. (For example, two donations added for the same amount will be consolidated into one line item with a quantity of 2.)
Once the donation is in the cart, the donation amount can also be updated using the standard line item option update form. You would normally hide the qty field, because while it continues to work it’s most common for customers to donate a single amount.

How do I disable this consolidation feature?
Adding <input type="hidden" name="options[random]" value="{{ random()|hash }}"> works, but that displays in the CP so it's not clean.
I also tried showing a commerce/cart/update-cart form on the donation page that redirects to the payment page (there's no user viewable cart on this site) when the cart isn't empty, it works, but it seems like this shouldn’t be necessary. It also can show the user incorrect data if they enter an invalid donation amount, switch to a valid amount, go to the payment page, and then hit the back button. The invalid update cart form will be shown.
What's the simplest way to streamline all of this this?


texts: How to loop through entries by importance?

texts:
I have a channel of entries I'd like to loop through by order of importance on a scale of 1-5 with 5 being the most important and appearing first.

I tried to achieve this using a radio button field called importance and if else statements like:

{# List most important entries first #}
{% if entry.importance == "5" %}

            {% if entry.logo | length %}
                {% for asset in entry.logo %}

                {% endfor %}
            {% endif %}

{{ entry.companyName }}

{{ entry.description }}

    {% elseif entry.importance == "4" %}

                {% if entry.logo | length %}
                    {% for asset in entry.logo %}

                    {% endfor %}
                {% endif %}

{{ entry.companyName }}

{{ entry.description }}

        etc...

But this isn't very DRY and this lists the entries but they are still ordered by date. Is it possible to use .order with a field to achieve this?


texts: Use dropdown field to add a class to the body tag

texts:
I have a website where I want to be able to use different background colors on different project pages.
The way I want to achieve this is by having a dropdown field in Craft to select from a set of values on each project page. I will then use that to set a class on the body tag so that I can style that accordingly with css.
I have created a dropdown field with the handle backgroundColor.
I have added the these options as values:

default
yellow
green
blue
purple

and here is the code in the template
{% if entry.backgroundColor.default %}
  {% set bodyClass = "page-project" %}
{% elseif entry.backgroundColor.yellow %}
  {% set bodyClass = "page-project bg-yellow" %}
{% elseif entry.backgroundColor.green %}
  {% set bodyClass = "page-project bg-green" %}
{% elseif entry.backgroundColor.blue %}
  {% set bodyClass = "page-project bg-blue" %}
{% elseif entry.backgroundColor.purple %}
  {% set bodyClass = "page-project bg-purple" %}
{% endif %}

This gives me and error saying that the property does not exist.
Does anyone know what the problem might be, or if there is a better way to do this.
Thanks!


texts: First Craft website: how to organize different content

texts:
I am new to Craft and read a lot of arctilces and most of the docs. Most parts are quite easy. Now I plan how to organize all the different parts and pages.

Below is a simple outline. Not every page, but to get the ieda.

Home                            (Single)
- News                          (Section; structure: news)
  - Posts                       (news entry with category post?)
  - Press                       (news entry with category press?)
  - Media                       …
  - Events                      …
- About                         (Section; structure: pages)
  - About us                    (pages entry with defult entry type)
  - History                     (pages entry with defult entry type)
  - Team                        (pages entry with defult entry type)
- People
  - Locations                   (Section; channel: location)
  - Page-A, Page-B, etc…        (? other entry types)
- Members                       (Section; structure: pages)
  - Info                        (pages entry with defult entry type)
  - Jobs                        (?)
  - Listing                     (pages entry with defult entry type)
  - Register/Login              (?)
  - (PROTECTED MEMBERS AREA)    (?)
    - Auth-Group-I
      - Page A, Page B, …
    - Auth-Group-II
      - Page-A, Page-B, …

First:
There are 4 different "sections" (in terms of the content and audience). Would it be possible/a good idea to put alle those into one Craft section, titled pages?
And on those pages, where I need other content, like locations (store locator), I pull data from a dedicated section titled locations. Or on another I query the job listings.
That way I can group most pages, create the hierachy and spearate the content in logical groups/sections.

Second:
Otherwise, would it be better to give each website section its own Craft section.

Third:
What about those "special pages" like my register/login form, the job lsiting page, etc. Do they become a Single?

Fourth:
What is more appropriate for my different news pages: using categories or entry types?


texts: Using ElementType as field type for plugin in what way do I provide my own data to the modal?

texts: I have been looking at the BaseElementFieldType.php file to try and understand how to use it for my own field type. How do I provide that field type with my own array of data to use? I believe it has to do with the sources,criteria, or elements but it is unclear to me.


texts:
Sorry if this question is starting off too abstract. I'm porting a calendar plugin from Textpattern and WordPress into Craft.  Basic workflow for the output has been (in twig terms):

{% set start = "now"|date("Y-m-d") %}
{{ craft.Calendar37.calendar_full(start)|raw }}

and the plugin php does all the work of querying the db and producing the calendar.

What I'm up against is getting the db query right. It seems pretty abstract to get all the fields related to an entry--in particular working out the query to get the category from a category field in the entry. Probably I can work that out, but here's my question:

Would it be possible or better to do more of the work with Twig, and less in php?  I.e. once the php db query knows the entries and i could put that into (I suppose) a model, then can Twig figure out the rest using (I haven't tried this, just working it out in my mind):

{% set start = "now"|date("Y-m-d") %}
{% craft.Calendar37.initialize(start) %}  {# just does the DB query #}

  ...

    {% set event_instances = craft.Calendar37.getInstances(date) %}
    {% for instance in event_instances %}
       {% set entry = craft.entries.id(instance.entryId) %}

             {{ instance.time }} - {{ craft.entries.id(instance.entryId).title }}

    {% endfor %}

I wonder about efficiency.  One big, but precise query in php is probably better than going back from twig for every event on each day of the month as shown in the second part here.  This is the query so far; it doesn't find the category, or slug, or several other things yet:

$events = $query
    ->select('*') //c37.event_id, dateYmd, timestr, alt_text, css_class, entries.id as event_id, title as event_title, slug')
    ->from('calendar37 c37')
    ->join('entries entries', 'c37.event_id = entries.id')
    ->join('content content', 'entries.id = content.elementId')
    ->join('elements_i18n elements_i18n', 'entries.id = elements_i18n.elementId')
    ->where("c37.dateYmd >= $fromDateYmd")
    ->andWhere("c37.dateYmd <= $toDateYmd")
    //->andWhere('STATUS = published, pending, etc')
    ->order('dateYmd ASC, timestr ASC')
    ->queryAll();

Thanks for any advice!


texts: How to manage multiple categories and entry url formats

texts:
I have a setup in Craft 2 like below:

Section: products
Url format: flowers/{productCategory.last.uri}/{slug}

Categories:
cat1 = Bouquets
cat2 = Valentines days
Url format: flowers/{slug}

The problem headache arises when I want to get the entry URL within a category template. It always gets the last category of the entry due to the URL format. So once valentines day is added as a second category then a normal bouquet entry URL goes from this:

/flowers/bouquets/entry-slug

to

/flowers/valentines-day/entry-slug

I solved this partly by making my bouquet URL out of the URL path:

            {% for entry in entries %}
                {% set prodUrl = 'flowers/'~ seg2~ '/'~entry.slug %}
                 <a href="{{ baseUrl }}{{ prodUrl }}" >

However, the entry template now doesn't have the entry model.

How do other people solve this multiple categories for the same content type issue?


texts: Get entries whose title has a keyword or related to a category's title

texts:
I am trying to get entries that either their title has the keyword or their category field title. I am getting them from my plugin, not twig.
I tried like this:

$keywordCategory= Category::find()->title($keyword)->all();
$entries = Entry::find()->title($keyword)->relatedTo($keywordCategory)->all();

but it must be in the title and the category field. Is there a way to check using where and orWhere?


texts:
I would like to set a .htpasswd on a folder within my templates directory. Here is what I did:

..create the .htpasswd file and place in directory above my public folder
..create a .htaccess file that points to the .htpassword file, and place it in the folder I want to protect, which is in my templates directory.

When I enter a url to access the page, it displays the page fine, but does not trigger the .htpasswd. If I move the folder to my root directory, everything works fine.

Why does this not work as a Craft template?


texts:
Is it possible to render the search time after a query (out-of-the-box)?

eg: 2 results(.0271 seconds)

There are a number of plugins available but I would like to find out what's possible within Craft's core.


texts:
is there any built-in way to encode malicious file name characters when getting an asset URL through assetHandle.getUrl('transformationName')?

My system contains files with names such as /assets/images/foo/_transformationName/105 Flippy Dolphin 31 (F60).jpg and escaping the whole string escapes also slashes.

I can assemble a valid URL from asset.directory and asset.filename, but that cuts off access to image transformations.

I do realize I could create a twig extension or explode the string using regular expressions, do my thing and join it back, but I have a feeling this might use some approach more aimed at fixing the cause, not the consequence. The .getUrl() method might be able to return a web-safe value somehow maybe?


texts:
So I've created a boilerplate for my web development company using Craft. However, I'm encountering so much inconsistency across different machines.

I recently set up a new website at my public domain. I set up the webserver, and did a Git pull from the boilerplate Bitbucket I've got going.

After the pull, I did a composer install and installed Craft.

At this point the website is working, but I can't login. The Craft setup never prompted me to create a new user/password. Not sure why.

Regardless of this issue, I have to import my DB from my local box to the web server. So after doing so, I can now login. Great right? Not quite.

After I login, I can't access any Settings in the backend and get a error about my license key. I've since fiddled around with my License Key settings on Craft's website, but I still can't access the Settings panels.

I'm sure there's a process to deploying a site to production, but so far I can't find any consistency. Any advice is greatly appreciated.

Screenshot below.


texts: How does Craft regard a Lightswitch field when it's set to Required in the Fields layout?

texts:
If I set a Lightswitch field as required, does that require it to be On? Is that valid at all?

(Context: I'm using a Lightswitch in User fields to capture "I agree to the Terms & Conditions...", and building a front-end user registration form.)

Thanks!


texts: Different Single as homepage for other languages

texts:
How can I give another localization its own "Single" as homepage. My main language has its own very unique homepage but for the other languages I need all the fields and HTML/CSS of my about us page. I want to do this without adding all the fields to some other tab in my homepage.

Is there any possible way to make this happen. I tried already to set the homepage for the main language open. Created a new Single for the other language but I dont have the option to set it as homepage for the current language.


texts: Craft 3 memcached session storage in load balanced environment

texts:
I'm getting the good old session expired popup every minute in the admin panel which is odd given that memcached should be properly configured:
php.ini
session.auto_start = 0
session.save_handler=memcached
session.save_path="mymemcachedhost:11211"

config/app.php
return [
    'modules' => [
        'my-module' => \modules\Module::class,
    ],
    'components' => [
        'session' => [
            'class' => yii\web\CacheSession::class,
            'as session' => craft\behaviors\SessionBehavior::class
        ],
       'cache' => [
           'class' => yii\caching\MemCache::class,
           'useMemcached' => true,
           'defaultDuration' => 86400,
           'servers' => [
               [
                   'host' => 'mymemcachedhost',
                   'persistent' => true,
                   'port' => 11211,
                   'retryInterval' => 15,
                   'status' => true,
                   'timeout' => 15,
                   'weight' => 1,
               ],
           ]
        ]
    ]
];

/admin/utilities/php-info (craft admin panel)
session.save_handler    user
session.save_path   mymemcachedhost:11211

I think the problem might lay with session.save_handler showing up as user in the craft admin panel for the php.ini but if I look at <?php phpinfo(); ?> on either host behind the loadbalancer I see session.save_handler showing up correctly as memcached.
I've verified with telnet and nc that the memcached host responds correctly at the given host:port combo. Any ideas?
EDIT
The same problem persists when using redis as a session store:
redis attempt config/app.php
<?php
return [
    'components' => [
        'redis' => [
            'class' => yii\redis\Connection::class,
            'port' => 6379,
            'hostname' => 'elasticachehostname'
        ],
        'cache' => [
            'class' => yii\redis\Cache::class,
            'defaultDuration' => 86400,
            'keyPrefix' => 'pm_key',
        ],
        'session' => [
            'class' => yii\redis\Session::class,
            'as session' => craft\behaviors\SessionBehavior::class,
        ],
    ]
];

"yiisoft/yii2-redis": "2.0", has been added to composer
With this config I cannot even sign into the admin panel as I get this error in the craft logs (about a dozen times right after another):
2019-11-27 14:43:50 [-][5615][-][error][yii\web\Session::open] session_start(): Failed to read session data: user (path: tcp://elasticachehostname:6379)
Redis is working in php though as I can run this php file no problem (with properly incrementing numbers:
<?php

 ini_set('session.save_handler', 'redis');
 ini_set('session.save_path', 'tcp://elasticachehostname:6379');

session_name('FOOBAR');
session_start();

if (!array_key_exists('visit', $_SESSION)) {
    $_SESSION['visit'] = 0;
}
$_SESSION['visit']++;

echo nl2br(
    'You have been here ' . $_SESSION['visit'] . ' times.'
);

This would indicate that there is definitely an issue on the craft/yii side of things. I don't know why it cannot connect to it.
I also confirmed it's not a Amazon issue,  I installed redis locally on the host and get the same error message (except of course tcp://localhost...)


texts: Saving a SuperTable field within a Matrix Field

texts:
I am trying to save a SuperTable field that sits within a Matrix field.

I have followed the docs as far as I can but for some reason the SuperTable data is not getting saved.

My steps are as follows:

Get the SuperTable field id:

$matrixBlocks = Craft::$app->getFields()->getFieldByHandle('eventPerformances')->getBlockTypeFields();
$ticketBlockId = $matrixBlocks[2]['id'];

Check that the field has content and loop over it to get the array of data:

if ($event['schedules'][0]['performances'][0]['tickets']) {

    $ticketsMatrix = array();
    $i = 1;

    foreach ($event['schedules'][0]['performances'] as $performance)

    {
        foreach ($performance['tickets'] as $ticket) {
            $ticketsMatrix['new'.$i] = array(
                'type' => $ticketBlockId,
                'enabled' => true,
                'fields' => array(
                    'ticketType' => $ticket['type'],
                    'minPrice' => $ticket['min_price'],
                    'maxPrice' => $ticket['max_price'],
                    'currency' => $ticket['currency'],
                ),
            );
            $i++;
        }
    }
} else {

    $ticketsMatrix = '';
}

Pass this array through when saving the parent Matrix field

$performancesMatrix = array();
$performances = $event['schedules'][0]['performances'];

$i = 1;

foreach ($performances as $performance) {

    $performancesMatrix['new'.$i] = array(
        'type' => 'performance',
        'enabled' => true,
        'fields' => array(
            'performanceDate' => date_create($performance['ts']),
            'duration' => $performance['duration'] / 60,
            'tickets' => $ticketsMatrix
        ),
    );
    $i++;
}

The performanceDate and duration fields get saved as expected but the $ticketsMatrix data is not saving in the nested SuperTable field.

Any assistance would be appreciated!


texts:
This question is identical to Resaving blog entries keeps failing except that I'm not finding any [error] or [warning] in my log entries.

I have changed my entry URL format for the section named Events from

{mainCategory.last().uri}/{slug}

to

{mainCategory.last().uri}/_entry

as described here: Is it possible to view 'Expired' entrys on the front end? and when I hit save on the section page, then it immediately gives the failed task: Resaving Events entries. Any thoughts?

UPDATE

OK, I did find this error:
2016/12/18 02:26:41 [error] [application] Encountered an error running task 422 (ResaveElements), step 2 of 197: Encountered the following validation errors when trying to save entry element "Transforming Work" with the ID "19":
 - URI "fort-collins/weekly/buddhist-meditation-classes/_entry" has already been taken.

I'm not sure quite what it means. There's only one entry named Transforming Work.


texts: Compose URL POST parameters to filter entries by category?

texts:
How do you update an URL with new params?

I'm working on a search / filter entries page. I have multiple menu lists with categories in it. Like this:

Size:
Small
Medium
Large

Color:
Blue
Red
White
Yellow

So if the URL is product?size=m and I click on a link "Size → Large" then the URL needs to update to product?size=m,l. Click again on "Large" the l value of the sizes parameter needs to delete.

If I then click on "Color → Red" the URL must be product?size=m,l&color=red.


texts: UnexpectedValueException after loading plugin

texts:
I'm attempting my first Craft plugin and trying to update https://github.com/matthewattanasio/Craft-Url-Decoder-Twig-Extension for Craft 3 and followed the instructions in the docs for loading plugins which seemed to work in that the plugin appeared in the control panel, but I also got the following error:

  [UnexpectedValueException]
    Package cakephp/core's source key should be specified as {"type": ..., "url": ..., "reference": ...},
    {"type":"git","url":"https://github.com/cakephp/core.git","reference":null} given.

and now when I try to run any more composer commands I get the same error so I'm unable to do

composer remove package/name
composer require package/name

because I've made some changes to file names and need to update it.

The plugin is still showing in the CP but showing old information and when I try to install it, I get a server error.


texts: HighRes image crop tool (not Aviary plugin)

texts:
Is there an alternative to the Aviary plugin (https://github.com/fruitstudios/AviaryImageEditor)?

I only need to be able to offer the client a visual interface for cropping (in 1 aspect ratio only).
While Aviary works great, it's limited at the moment to low res images and I really need high res images as I use them full screen.

Does anyone know an alternative?


texts:
I’m currently using react as a font end SPA with craft cms as the backend. I’m trying to create user accounts where a user use can sign up and favourite content on the site, using the Like for craft cms plugin - https://github.com/dukt/like

So far the user is able to sign up, login and logout. However I’m having issues with accessing the renewed CSRF token when then the user logs in. I am accessing the CSRF token as per the documentation - https://craftcms.com/support/csrf-protection#updating-your-javascript. So these are currently the steps of the CSRF token login process.

1) User lands on website and the CSRF token is created e.g.
pRO1LyYLzxulTZ6ttv17kZ4gBQzTYHeQEpwZI8nL

2) User logs in (updated CSRF token is generated, don’t have access to it unless I refresh the page).

3) User likes an entry (400 error ’The CSRF token could not be verified.’).

4) Refresh the page
CSRF Token = pRO1LyYLzxulTZ6ttv17kZ4gBQzTYHeQEpwZI8nL\x7C42101f4b43f2bc331d376d055c77c8f7146d30e4

5) User can now like an entry.

I’ve tried to get the updated CSRF token from the cookie, but I can’t access it via document.cookie for security because they are tagged httponly.

Is there a way to get the updated value of the CSRF token? Possibly after the login action?

Thanks for any help!


texts: Adding description and other information to channels

texts:
This might be a little difficult to explain thoroughly and correctly, bear with me. :)

The Problem

The news website I'm working on has different categories based on topics, location, and "genres" (news, editorial, press release, etc). In addition, we also have other channels that work independently from the primary articles.

I am having a difficult time finding the best approach to provide information such as heading, description, a cover image, etc — for these different channels in a way that is organized, makes sense and can be easily edited from the CP.

Example

The Main channel could have an image and a description which states that the articles in this section are written by the members of the company.
A channel managed by a writer from the community could also have its own cover image and description stating that this channel contains chronicles and critics by him and other authors.
A channel managed by a collaborator/correspondent could focus on a specific topic, such as technology; the image and description of the channel would explain this.
Another channel could provide news related to the company alone.
Another channel could be from the developers in the team.
etc...

Note how these secondary channels are different from the main content. These should not be mixed together and are often accessed by different users.

So... Has anyone dealt with this problem? How have you solved it? I have a few ideas in mind but I'd like to see what other practices are out there.


texts: Can I simply update from 2.6.2779 -> 2.6.2958, shared hosting

texts:
Do I need to go through and install all the previous updates before installing 2.6.2958 (current 2.6.2779) OR can I simply use the instructions on this page https://craftcms.com/docs/updating and install version 2.6.2958.

Any recommendations would be appreciated since I have never used Craft before and/or done any installations/updates.

Thanks in advance.


texts:
Very similar (almost exact) to this question: Poor performance on midsized site / Queries without index?

CPU keeps getting pegged to 100% for MySQL, which makes the admin interface very slow (the site is cached using fastCGI, so generally the site still performs well regardless).

The troublesome query:

FROM (SELECT `elements`.`id` AS `elementsId`, `entries`.`sectionId`, `entries`.`typeId`, `entries`.`authorId`, `entries`.`postDate`, `entries`.`expiryDate`
FROM `elements` `elements`
JOIN `elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id
JOIN `content` `content` ON content.elementId = elements.id
LEFT JOIN `relations` `sources1` ON (sources1.targetId = elements.id)
LEFT JOIN `relations` `targets1` ON (targets1.sourceId = elements.id)
JOIN `entries` `entries` ON entries.id = elements.id
JOIN `sections` `sections` ON sections.id = entries.sectionId
LEFT JOIN `structures` `structures` ON structures.id = sections.structureId
LEFT JOIN `structureelements` `structureelements` ON (structureelements.structureId = structures.id) AND (structureelements.elementId = entries.id)
WHERE (((((elements_i18n.locale = 'en_us') AND (content.locale = 'en_us')) AND (elements.archived = 0)) AND ((elements.enabled = 1) AND (elements_i18n.enabled = 1) AND (entries.postDate <= '2017-12-29 15:41:28') AND ((entries.expiryDate is null) OR (entries.expiryDate > '2017-12-29 15:41:28')))) AND (elements_i18n.enabled = 1)) AND ((sources1.sourceId='52') OR (targets1.targetId='52'))
GROUP BY `elements`.`id`) derivedElementsTable

What are CPU has looked like:

I'm not sure where I should start hunting this down. This appears to only happen for the en_us locale, I haven't recorded another locale showing this. This is on a staging site on Digital Ocean, so it's getting zero traffic. It's also being managed by Forge on PHP 7.1.

Could I get any advice for hunting down the php that might be leading to this? It's not happening as a result of any clear action.


texts:
Has anyone tried using the Craft reCAPTCHA plugin from Matt West? The issue I am experiencing is that if a Contact Form is submitted without ticking the reCAPTCHA widget, the form does not submit - that's good! - but there is no error message posted on the form page to remind the user to 'prove they are human'

Thanks for any suggestions!


texts: Import Large Number of records - 300,000

texts:
Is there a best way to import a large number of records - About 315000 to be precise. The company provides a service which is only available to specific addresses.
So I had set up a section to contain the addresses where the service is available. With fields - Address1, Address2, Postcode, Town
Just got the data to import and discovered that there is 315000 records - I got the data in csv format. Tried with Import and FeedMe Plugins but run into memory issues straight away. CSV file is nearly 15MB and when converted to XML for feedme it is 52MB

So what are my options for importing?

Could I ramp up the resources on a Digital Ocean Server for the time that the import is required?

Or should I try another method to try this lookup service on the website?


texts:
When creating a new volume (same process as the other 3 volume I currently have and which are fine, I'm running into the following error).

Any help would be appreciated.


texts: Save a selected category for a user (using a plugin)

texts:
I have some categories, and with the use of a category field a user can select these from within his / her profile.

Which is shown in the image:

In my Twig template I can get the user selections out using the following code.

{% set property_prefs = craft.categories({
    relatedTo: { sourceElement: currentUser, field: "propertyPreference" },
    limit:     null
}) %}

But what I want to know is how can I programmatically save a user selection using the API from within my plugin.

Also, which table are these stored in?


texts: Updating Craft cause broken git and merge conflict

texts:
I've got a local db and install of Craft as well as a remote. I'm pushing to bitbucket from my local Mamp environment then pulling from bitbucket to my server via ssh.

I recently updated Craft by clicking the prompt inside the dashboard. When I did this, it editing nearly every file in /craft/app leaving a ton of modified files registered in git.

I should have had craft/app in my .gitignore file but I didn't. Now when I try to pull I'm getting this error:

error: Your local changes to 'craft/app/Info.php' would be overwritten by merge.  Aborting.
Please, commit your changes or stash them before you can merge.

How can I force my remote build to ignore everything in craft/app so I can get back to pushing/pulling.


texts:
I added a field called "phonenumber" to the user profile fields which I want to use for login purposes, too.

Usually Craft allows an authentication by username or email-address. Is there a way to add another field for authentication, e.g. the custom field phonenumber? The goal is to expand Craft to accept logins via username and email-address as well as the phonenumber.


texts: Are values in Asset fields held globally for a particular Asset?

texts:
I have a few fields assigned to an Asset Source, which allow the user to alter the appearance of the image (large, small, portrait, landscape) etc. on the front end.

I'm not sure if this is a bug or intended behaviour, but when I enter a field value as an editor to a particular instance of an Asset, if that Asset then appears elsewhere in a different entry, it appears to inherit the field values of the Asset where it was used previously.

I need to be able to have an image in one entry set to, for example, 'large', but also have that same image appear on another entry but set to 'small'.

Assuming this is intended behaviour, how can I get around this?


texts: Locales with independent language and country

texts:
How might we use Craft to manage our locales, keeping our language and country logic independent? The desired scenario:

No duplicate language entries: Spanish in Spain would be the same as Spanish in Mexico or Portugal or China.
Content sections should be shown or hidden based on country.

We are running Craft headless with React, so this question is more about how to most efficiently manage our data in Craft and whether or not Craft can (or should) handle the locale routing.

Perhaps we would be better off putting the show/hide logic and locale routing in React.


texts: Using Craft environment variable for Asset source subfolder

texts: I have an environment variable "bucketUrl" that I would like to use as the subfolder path in my S3 bucket. However, Craft is not parsing the variable. When I upload an image, I see in my S3 bucket that a new subfolder "{bucketUrl}" was created with the uploaded image inside it. Why is Craft not parsing the environment variable? Craft is parsing my site url variable I am using elsewhere in the Craft admin, so I'm not sure why Craft is not parsing the bucket url variable.


texts: Is there a setting to get Craft to save user photos to S3 like a regular asset source?


texts:
I have a matrix field with an entries field which ties into another matrix field. Is this possible? Here's what I have so far...

{% for block in entry.contentMatrix %}

  {# Tabs Block Type #}
  {% if block.type == "tabs" %}
    {% set entries = craft.entries.relatedTo(block.tabEntry) %}

    {% for entry in entries %}
      {# Matrix Content #}
      {% for block in entry.tabsMatrix.type('videoChannel, videoPlayer, copy') %}
        {{ block.title }}
      {% endfor %}
    {% endfor %}
  {% endif %}

{% endfor %}

This does not produce an error, just nothing.


texts:
I have a link on a website that i'd like to set a class of active on, based on different segments.
{% macro is_acitve(segment) %}
    {% if craft.app.request.getSegment(2) == segment %}active{% endif %}
{% endmacro %}

Link Title

It's not working. How would I go about this ?


texts: Setting User field type from a front end form

texts:
I am moving a site from EE to Craft and trying to figure out the best Craft approach to something I did with lots of php and url parameters in EE.

The overview: the site is a Family Counseling Clinic.  As part of their program, they have parents register as users on their site.  The parents create a profile for each of their children and then, for each child, they fill out a number of questionnaires.

The basic issue is how to set up these relationships, given that I am using front end forms.

Since the parent is a registered user and is creating the child profile(s) (as a channel entry), the relationship can be based on entry.authorId(theParent).  No problem there.

The relationship between child and forms is where I am looking for a Crafty solution.  One obvious approach is to use Structure for the child profiles and have the questionnaires as a "child entries".  The other possibility that occurs to me is to use an Entries field in a Questionnaire channel that is tied to Child channel entries.

In both cases the question is whether it is possible to do either one of those using a front end form, which would either require setting the parent entry for the Structure solution or the Entry field for the other.

Hope this is clear, and thanks for any suggestions!


texts:
I've got a custom controller in my plugin that checks whether or not the request is ajax or not, using craft()->request->isAjaxRequest()

In the event that it is, I just want it to return a partial. First though, I'm trying to just get it to return a string but seem to be having issues getting something as simple as that to work (I'm pretty new to PHP). The code I have on the condition of it being an ajax request is:

$path = craft()->path->getSiteTemplatesPath();
craft()->path->setTemplatesPath($path);
$temp = craft()->templates->render('notifications/_test');
echo $temp;

I'm logging the response in javascript but keep getting a 404. If I try to open the link (custom controller url) in a new tab (so not and ajax request) it correctly executes the non ajax condition.

The GET request looks like this: $.get($(this).attr('href'), function(data)...
where the href is the controller action url.

Does anything look amiss? Am I perhaps missing a step to allow for this to work? I've tried $allowAnonymous on the controller to no avail.


texts:
I'm suddenly having issues with multiple Craft builds on my local dev environment.

Basically, everything else is working fine but when I edit a field the page breaks. It appears to only be displaying the form with any html, head or body tags. I installed a fresh copy and the issue also occurs on that build. I'm thinking it could be an issue with my version of MAMP or perhaps it's a known issue. Any ideas?


texts: EVENT_BEFORE_SAVE_ELEMENT Saving element loop in task/queue

texts:
I'm calling EVENT_BEFORE_SAVE_ELEMENT to trigger a task that then updates the entry, but it's causing a loop?

The event is triggered when a specific entry type is saved:

Event::on(
  Elements::class,
  Elements::EVENT_BEFORE_SAVE_ELEMENT,
  function(Event $event) {
    $entry = $event->sender;
    if ($event->element instanceof \craft\elements\Entry) {
      $entry = $event->element;
      if (ElementHelper::isDraftOrRevision($entry)) {
        return;
      }
      if(($entry->sectionId == 18) && ($entry->typeId == 26)) {
        $signpostURL = $entry->getFieldValue('signpostUrl');
        if(($signpostURL) && ($signpostURL !== '')) {
          Craft::$app->queue->push(new BrowshotTask([
            'description' => 'Grabbing screenshot for '.$signpostURL,
            'url' => $signpostURL,
            'entryId' => $entry->id
          ]));
        }
      }
    }
  }
);

BrowshotTask then performs some API calls to a third-party service, gets a screenshot, saves an asset and saves the asset in the asset field of the entry.

But this triggers the event again and causes a loop:

$entry->setFieldValue('browsershotUrl', [$assetId]);
if(Craft::$app->elements->saveElement($entry)) {

Sometimes BrowshotTask can take 20 seconds due to the third-party service.. so I thought putting it in a task would be a great idea, but now it's causing me so many problems :(


texts: The plugin docs are a good reference but can be a bit daunting when piecing things together, any good plugins from the community that are well commented/built etc. ? Especially in regard to elements.


texts:
How Craft reacts to missing images is one of the very few places where I find Craft less than ideal.

TL:DR;

Is there a way to make missing images not become a fatal error?
How do you find elements that are referencing the missing image?

Long version:

There are a number of ways images can be missing, for example:

Our workflow involves developing locally, then putting up to staging for clients to add content. Sometimes we need to then do more local development, local and stage both share the same database... but not images.

An image is simply corrupt, due to transfer or disk failure (it happens)
A filesystem is reverted to a previous state but the database is not
A live server dies and a project is restored to a new machine from SVN/GIT, but the assets are not in version control and therefore not available
Getting hold of the images on local isn't possible temporarily because you're working on a restricted internet connection; like on a plane.

Any of these result in instances of 'blahblah.jpg could not be found' in Dev mode or Internal Server Error in production. Sometimes those images actually get lost; they just don't exist any more; but they're in the database. So...

How do you find what element is referencing these lost files? Besides manually trawling through entries, related entries, etc? Crafts error gives no useful information about that, and rebuilding asset indexes doesn't seem to make Craft aware that the image isn't available anymore.

And...

Is there an option to just ignore these types of error - it's not helpful in production to have a whole page 'internal server error' just because a single image referenced on the page is missing from the file system for whatever reason. A missing image is not a throw-the-baby-out-with-the-bathwater problem.


texts:
I'm building my first Craft site and need to set a variable if a field has an image and then use that variable elsewhere in the template.

The field is part of a matrix and will repeat.

What I have so far is:

{# extra image #}
{% set asset = block.extraImage.first() %}
{# set variable empty so it's avialble outside of conditional #}
{% set float = "" %}

{% if asset %}

    {% set float = yes %}
{% endif %}

 more code here

The above code doesn't give me any template errors. But it also doesn't output the class as expected.

The full template code can be viewed here.


texts: Creating a multi-dimensional Photo Gallery on Craft CMS

texts:
I'm currently working with a client who has several hundred photos in a gallery. The gallery consists of albums within albums. The link to their current gallery is here: http://www.fmquizzing.net/gallery2/main.php

I'm working on an entire site update and would like to update their photo gallery to integrate directly with Craft if possible. They currently have the photos in folders on their server pulled in dynamically with a PHP script.

Is there a good way to go about creating a gallery like this with Craft, or is it going to be just as good to attempt updating the styles and script on what they already have going? Trying to think both about short term and long term development and maintainability costs.


texts: Prevent EVENT_BEFORE_VALIDATE in specific case

texts:
I have a registration form and its custom validation in PHP plugin code.

However, the validation works when user set a new password.
I supposed that $event->isNew is good to detect if it is a new user registration or not, but the element does not work.
Craft says it is unknown property.

Could you tell me how to detect the kinds of submission?

// Registration Form
$request = Craft::$app->getRequest();
Event::on(
    User::class,
    Element::EVENT_BEFORE_VALIDATE,
    function (Event $event) use($request) {
        // If a user already logged in we are not on the public registration page
        if (Craft::$app->getUser()->getIdentity()) return;

        if (!$event->isNew) return;

        // Do the custom validation
        if (!$event->sender->firstName) {
            $event->sender->addError('firstName', Craft::t('yii', '{attribute} cannot be blank.', [ 'attribute' => Craft::t('app', 'First Name') ]));
            $event->isValid = false;
        }
...


texts: How to host a huge website on Craft (10k pages, over a dozen languages, 2GB database)

texts:
We have what appears to be a very large website. We have a strong content strategy which has led us to develop a huge number of pages (over 10k) for our website, as well as building out a significant amount of internationalized pages (over a dozen). We're currently on Craft 2 and working on migrating to Craft 3. As part of that, I figured we'd re-evaluate our current hosting strategy. However, all the hosts I've spoken with have agreed that our situation is unique relative to their other customers.

Here's our 2GB database breakdown (with removal of smaller sections):

+--------------------------------------+-----------+
| Table                                | Size (MB) |
+--------------------------------------+-----------+
| searchindex                          |    868.14 |
| content                              |    728.73 |
| entryversions                        |    215.70 |
| elements_i18n                        |    194.59 |
| matrixcontent_comparisonpagetablerow |     10.72 |
| structureelements                    |     10.52 |
| elements                             |      6.97 |
| entrydrafts                          |      5.58 |
...
+--------------------------------------+-----------+

We currently host on Digital Ocean through Forge. We have a 4vCPU CPU optimized server with 8GB of ram.

What we find is that things like assets are slow, navigating the admin is slow, etc etc. Without fastcgi caching, the entire website would be very slow.

Should we just throw more CPUs at it? What's the ideal solution to really improve performance for such a big website? I'd prefer not to have to get super complex with our hosting strategy (ie break out database, have a read-only database, use a caching layer in front, etc), but if that's what's necessary I'd consider it.


texts: `Invalid argument supplied for foreach()` error

texts:
We've made a local copy of a site that is working fine in a staging environment but locally is getting the following error:

`Invalid argument supplied for foreach()`

Seemingly coming from craft/app/fieldtypes/BaseOptionsFieldtype.

Does anybody have any thoughts on what is causing this and how to resolve? Is happening both in the front-end and the admin area.


texts: loop through an entry's "related entries", grouped by category

texts:
Hope somebody can help us with this:

Objective: loop through a given Entry's "Related Entries" entry field and output the results - but group the results by the category to which they belong - not just a straight splurge of related entries.

Where we are:

{% for category in categories %}

{{ category.title }}
{# spit out the Category #}

{% for relatedEntry in entry.relatedEntries %}
    {{ relatedEntry.title }}{# this spits out all entries, but ignores whether the entry is related to the current category #}

    {# So, try and check if it's related to the current category... #}
    {% if relatedEntry.relatedTo(category) %}{# Trying to use this throws "Craft\EntryModel and its behaviors do not have a method or closure named "relatedTo"." #}

{{ relatedEntry.title }}

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


texts: Craft license not recognised with new webhost

texts: I moved a webpage to a new webhost keeping the domain. Somehow I get now the alert that I am running craft pro with a solo license. All my attempts to solve this in CraftID with my acccount have failed so far. Same with the plugin licenses.


texts: Passing value in form with amforms plugin

texts:
I've created a form using amforms to ask some info about the visitor when he request a document.
I want to pass the name of the requested document in the form.

So I created the field nomDocumentEfficy and attached it to my form but I cannot get the value in my submitted forms.

Here is my form :

<div class="form-askemail contact">
    {{ getCsrfInput() }}

    {# This should always be here! #}
    <input type="hidden" name="action" value="/amForms/submissions/saveSubmission">

    {# Insert your form's handle. #}
    <input type="hidden" name="handle" value="{{ form.handle }}">

    {# This will namespace your inputs (for IDs and such), but it's not required though #}
    <input type="hidden" name="namespace" value="{{ form.getNamespace() }}">

    {# Optional: Redirect URL. Will redirect to current page by default. #}
    <input type="hidden" name="redirect" value="{{ craft.request.getParam('redirect') }}">

    {# Optional: Anti-spam protection. #}
    {{ craft.amForms.displayAntispam() }}

    {# Optional: Google reCAPTCHA protection. #}
    {{ craft.amForms.displayRecaptcha() }}

    {# Place the HTML of your fields here #}
    {{ form.displayField('email') }}
    {{ form.displayField('societe') }}
    {{ form.displayField('typeEtablissementAskEmailForm') }}
    {{ form.displayField('numeroDepartement') }}

    {# Hidden input field with my value #}
    <input type="hidden" name="nomDocumentEfficy" value="my_value">
</div>


texts:
I'm trying to decide if FeedMe would be a good choice to sync Craft with a fairly large Airtable database (more than 5k records). I'm inclined to say no just on general principle but I've done some quick tests and everything seems to work fairly well. For my next step in testing I wanted to try a larger sample dataset, but I can't figure out to increment the offset parameter.

When I make a request to Airtable, it returns 100 records, and an offset response that looks like

itrEk3iGk6zOddYqC\/recF5XRtrVtf6t0um

If I add that offset as a parameter to a new request, I get the next 100 records and a new offset value. So how do I tell FeedMe to automatically re-run the feed with the new offset parameter?


texts:
We're having trouble uploading PNG-8s. PNG-24s and JPGs work fine, but after selecting a PNG-8 to upload, the progress bar appears and fills to max in a couple of seconds, but then hangs indefinitely. Sometimes a message appears saying "Upload failed for 'filename.jpg'", sometimes it just hangs with no error message. If we then refresh the page, the image is in the assets list but no thumbnail has been created for it. The PHP error log gets this:

[03-May-2017 14:03:48 UTC] PHP Fatal error: Maximum execution time of 30 seconds exceeded in /home/sitename/webapps/sitename/craft/app/vendor/pixelandtonic/imagine/lib/Imagine/Imagick/Image.php on line 313

We could of course make them all PNG-24s but the file size is often way higher.

We're on Craft 2.6.2958, and the assets are on Amazon S3. Any advice on how to diagnose this would be much appreciated!


texts: Difference between categories and structures

texts:
The recent updates to categories have been great and provide a lot of flexibility.  But now I find myself struggling to decide what should be a category group and what should be a structure.

For example we are working on a site where a lot of the content will be segmented by city.  Originally I had just assumed that cities would be a entry section but now feeling like categories make more sense semantically?

So my question is what are the functional differences between categories and structures?  As far as I can tell they are:

The category fieldtype does not let you reorder the selected categories, the way you can with related entries field.  They always stay in the category groups order
Categories don't have a post date or expiration date
Categories don't have authors
Categories don't have versioning

Are there any other important differences I should consider? It seems like the only advantages are that they get their own tab, and that the ordering is consistant across all related entries


texts: Craft 2.6 incorrect string value SQL error for 4 byte UTF-8 characters when saving entries

texts:
On a Craft site that uses the Dukt Twitter plugin I have started seeing SQL errors when saving certain entries that use Twitter data:

CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xF0\x9F\x93\xB8co...' for column 'keywords' at row 1. The SQL statement executed was: INSERT INTO `craft_searchindex` (`elementId`, `attribute`, `fieldId`, `locale`, `keywords`) VALUES (:elementId, :attribute, :fieldId, :locale, :keywords) ON DUPLICATE KEY UPDATE `keywords` = :keywords. Bound with :elementId='10', :attribute='field', :fieldId='111', :locale='en_gb', :keywords=' lots of keywords here... '

Within the keywords field is an emoji character that actually shows up when Twig throws the error. I've been researching the issue and it appears to be related to the collation of the DB tables and 4 byte UTF-8 characters, currently all the DB tables are utf8_unicode_ci, potentially changing this to something like utf8mb4 should work in theory.

However, what doesn't make sense is the same collation is being used on our staging environment and the error does not occur when saving and its the exact same data. Initially I thought this was due to the schema of the database being different, but I tried recreating my local DB with the same schema matching our staging and re-importing the tables, but the error still happens.

So I'm slightly confused as what the key difference is with our staging environment compared to local dev. Looking at our hosting provider, it seems the MySQL version if 5.6, where as on my local dev its 5.7.22, so this is a key area potentially.

But it does raise the overall question as what is the best course of action for emoji support on Craft 2, should all the tables be changed to utf8mb4?


texts: I am running a local install of Craft 3 Pro dev preview using MAMP and Sequel Pro on my iMac.  I downloaded the Commerce plugin to try it out and dropped the 'commerce' folder into my craft/plugins folder.  When I visit the admin control panel and click on plugins, I can't see the Commerce folder/plugin I just added. Any suggestions as to why?


texts: Passing variables between sibling blocks

texts:
Is there any possibility to use "entry" from the for-loop inside the "main" block inside another block ("header" in my case)? See example below:

{% extends "main" %}
    {% block header %}
        {{ entry.id }}
    {% endblock %}

{% block main %}
    {% for entry in craft.entries.section('blogPosts').limit(5).all() %}
    {% endfor %}
{% endblock %}


texts: .relatedTo() not returning tags with spaces

texts:
I think I'm seeing a bug while using advanced search with relatedTo(). If I use a simple search, like this:

{% set param = {
   order: 'RAND()',
   limit: null,
   search: "#{request.tags}"
} %}

It finds a tag like low confidence without any issue. However, using the code I have below throws no errors, but returns no results:

{% set request = craft.request.getQuery() %}

{% set param = {
  order: 'RAND()',
  limit: null,
} %}

{% set param = craft.config.devMode or craft.config.staging
             ? param|merge({ group: 'testing' })
             : param|merge({ group: 'verified' }) %}

{% set relatedToParam = ['and'] %}

{% if request.tags %}
  {% set tagId = craft.tags.group('specialism').slug(request.tags).ids() %}
  {% set relatedToParam = relatedToParam|merge([{
    targetElement: tagId,
    field: 'tagsSpecialism',
  }]) %}
{% endif %}

{% if relatedToParam|length > 1 %}
    {% set param = param|merge({ relatedTo: relatedToParam }) %}
{% endif %}

{% set users = craft.users(param) %}

I'm fairly confident it's not an issue with my code, as every other search combination is working.

Update

This is expected behaviour and requires proper hyphenated slug-path to work properly with .slug() in my code sample. See answer below!


texts:
We're using Craft 3.5.15.1 .  I updated one plugin and now all plugins are showing as disabled.  when I click to enable, the message pops up saying it's being enabled, but it's not.
There's no errors in storage/logs that I can see.
I can install new plugins, but disabling them will cause the error above on them as well.


texts:
long time listener, first time caller.

I'm having some issues getting localisation setup on my homestead/vagrant craft 2 site. I'm running into issues, I believe, with the craft cache when I try to visit a localised url I have set up.

I've been following the guide here, but haven't been able to have any luck with it.

I am using the folder structure in my public folder as follows

    /public
      -index.php
      -.htaccess
      /es
        -index.php
        -.htaccess

My config/general.php file is like this,

    define('URI_SCHEME', (isset($_SERVER['HTTPS'] ) ) ? "https://" :
    "http://");
    define('SITE_URL',    URI_SCHEME.$_SERVER['SERVER_NAME']);
    define('BASEPATH',     realpath(dirname(__FILE__) . '/../'));

    return array(

    '*' => array(
      'appId' => 'app',
      'validationKey' => getenv('VALIDATION_KEY'),
      'devMode' => true,
      'backupDbOnUpdate' => false,
      'omitScriptNameInUrls' => true,

      'siteUrl' => array(
         'en' => 'http://example.test/',
         'es' => 'http://example.test/es/'
      ),
      'cacheMethod' => getenv('CACHE_METHOD'),

      'environmentVariables' => array(
        'basePath' => BASEPATH,
        'siteUrl'  => SITE_URL

      ),
     ),

    ),
    )

My public/es/index.php file is pointing to the correct craft folder and has a define(CRAFT_LOCALE, 'es'). I'm stuck as how to progress and any pointers or tips are very appreciated
Heres a screen shot of the actual error on example.test/es