texts: Reference tags in rich text fields parse and converted on save

texts:
In my rich text field, I have a reference tag: {globalset:34:address}.

When I save and open the entry back up, the content is no longer a reference, but the parsed content, which sort of eliminates its usefulness.


texts: Craft equivalent to EE snippets for use in templates?

texts: I am new to Craft from EE. I have a snippet of code which I will be reusing in several templates. I see Globals but that doesn't seem like like what I am looking for. What is the proper method of doing this within Craft? Thanks


texts: Grouping/sorting for easier view of Craft::log messages

texts:
Is there any way to group or sort my own "Craft::log()" calls for my Plugins?

It's a bit tedius to go through the Application->Logs each page load to try and find my own log messsages.

Maybe someone has a better approach to this?


texts:
Rather than a static price for each product, I need the price to be dynamic based on two other fields of that product. Here's an example of what I need to accomplish:

Product

Field 1: Wholesale Cost (int)
Field 2: Increase Factor (int)

Price: (Wholesale Cost * Increase Factor) + Wholesale Cost

Digging around, I am finding absolutely nothing in regards to making the price of products dynamic. Is this possible at all with Craft Commerce, and if so how would I go about this?


texts: Eager loading relations in Plugins Element Type

texts:
I am creating an ecommerce plugin in Craft, and trying to take advantage of the ElementType. My goal is to list the orders, and also the items ordered in a single column. Is it possible to eager load Element Type's relations for the ElementIndex view?

I have two records: OrderRecord and ItemRecord, with relations defined like this:

// OrderRecord (the ElementType)
    public function defineRelations(){
      return array(
                'element' => array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' => true, 'onDelete' => static::CASCADE),
                'items'   => array(static::HAS_MANY, 'Shopping_ItemRecord', 'orderId', 'onDelete' => static::CASCADE))
    }

// ItemRecord
public function defineRelations(){
  return array(
    'order' => array(static::BELONGS_TO, 'Shopping_OrderRecord', 'required' => true, 'onDelete' => static::CASCADE)
  )
}

Loading the records from a service using OrderRecord::model()->with('items')->find() works really well, but i am struggling with translating this to the ElementType (if it's even possible, i don't know). I tried to using the OrderElementType::modifyElementsQuery() function to add the item columns, but there are a few problems:

The query is not allowing me to specify a different order-by, resulting in MySQL ambigous column error. The query is only containing "order by ´id´" without any alias name, which makes this query fail: select order.customerName, items.*
Joining in the items table, and grouping by anything else than the default ´elements´.´id´ results in duplicate rows in the view. This is my biggest concern about this question, how can i translate several rows from the result to a single OrderModel?

My current solution to this is to query the items from the OrderModel::populateModel($values), but this feels very slow and inefficient, i would like to avoid calling 50 extra queries every time the getMoreElements() is called

Thanks


texts:
I would like to install a Redactor plugin (http://imperavi.com/redactor/plugins/font-color/)

I placed the fontcolor.js into craft/app/ressources/lib/redactor/plugins
and added
    buttons: ['fontcolor', 'backcolor']
    plugins: ['fontcolor'] to my redactor json config file.
but without success.

Am I missing something ?

Thanks a lot,

Antoine


texts: P&T Contact Form plugin: How can I copy "name" and "email address" in the body of the mail?

texts:
I'm currently working with the Contact Form plugin from P&T. I don't need much more, but as usual the client wants to:

See the email address and name in the body of the mail (he won't understand the way it works now).

Is there a way to get this done?


texts:
Newbie here with hopefully a simple question...

I have a structure as per the image below where I want to only show the parent item and it's children on their pages.

I want to exclude the other entries but they should show on their own pages.


texts:
I'm trying to bring in all images from a matrix field but I can only get it to work with first() or last() but obviously it only shows 1 image.

I've found a few article explaining it but I can't seem to get it working.


texts:
Experiencing a headache on a client site where the siteUrl declared in general.php is not being reflected in the Control Panel (which is always showing the local siteUrl) and therefore also the template on the site.

An abridged/edited config file here: https://gist.github.com/cole007/68382039e9ebedceabf7

Thoughts appreciated


texts:
I have a structure for different categories like salad, soup, main course and so on. Basically they share the same fields - but I want to be able to have dynamic singles based on those structures. For example I have a MainMenu-Single where I than can select entries from salads, soups, main courses and so on.

But is there a way to loop through all the fields in that single?

I tried:

{% for category in craft.entries.section('foodMenuCategories') %}
    {% if entry.{category} is defined %}
       ...

Sadly that doesn't work.


texts: Freeform front end submission says smtp timed out but still sends email

texts:
I have a simple form that lags for about 10 - 20 seconds and then succeeds.

I looked into the logs and found a timeout message from my SMTP server, however the email is still sent, and the settings are correct, so I am not sure what is causing this timeout.

90  15:34:07.749    < 9ms >
info    yii\mail\BaseMailer::send   Sending email "Subject Line" to "testemail@mydomain.com"

91  15:34:07.749    < 0ms >
info    yii\swiftmailer\Mailer::sendMessage Sending email "Subject Line" to "testemail@mydomain.com"

92  15:34:19.988    < 12s 238ms >
warning application Error sending email: Connection to ssl://smtp-relay.gmail.com:465 Timed Out

When I use the test button on the Craft Email settings page, it works in under a second.

When I look above the timeout, I can see what looks like 2 send attempts, but maybe this is normal. The subject line and email address were updated for privacy reasons, the real email address used was valid.

UPDATE

So to follow up on this, I have narrowed it down to the attachment that is sent with the notification email. It is a 3mb PDF file, and it throws this time out error. The notification email is still sent, and the attachment arrives without issue. I believe this is a problem with one of the two transport methods, but the logs do not tell me if it is the base mailer or swift mailer that is at issue.

I have also switched to TLS and port 587, and the same result is  found.

UPDATE 2

I set the timeout in the cp mail settings to 30 seconds and now it no longer throws any errors, it still takes about 20 seconds. The command query causing the delay:

SELECT "integration"."id", "integration"."name", "integration"."handle", "integration"."type", "integration"."class", "integration"."accessToken", "integration"."settings", "integration"."forceUpdate", "integration"."lastUpdate"
FROM "freeform_integrations" "integration"
WHERE ("type"='crm') AND ("id" IS NULL)
ORDER BY "id"
LIMIT 1

Since this is related to attachments, I can remove it for now.

I cannot imagine its a bandwidth problem, its on a VPS from Vultr and I have had no other issues with delivering large assets outside of SMTP.

I have Free Form Pro 3.6.11 installed on Craft 3 Pro 3.4.22.1 in a dev environment.

Thanks!


texts: How pass an ElementModel to a Macro in Twig

texts:
I'm trying to pass an AssetModel into a twig macro but all I'm getting is:

Object of class Craft\ElementCriteriaModel could not be converted to string

Is there any way to define my twig macro variable to be an object instead of a string?

This is my macro

{% macro item(thumbnail) %}
    {% if thumbnail %}
        <img src="{{ thumbnail }}"/>
    {% endif %}
{% endmacro %}

This is my template

{% import "macros/grid.html" as grid %}

{% for entry in craft.entries.section('handle') %}
    {{ grid.item(entry.image) }}
{% endfor %}

entry.image is an Asset field


texts:
I would like to loop through entries only if the current date/time is before 5am on the following day from when the entry's eventDate (custom field mind you)is.

In other words I may have an event at 10pm on May/1/2015 and i want to loop through that date as long as it is not 5am (or later) on May/2/2015.

What I have currently is this:

{% for slide in craft.entries.section('events').featured('1').order('dateTime asc').limit(5).find() if (slide.dateTime|date("c","+8hours")) >= now|date("c") %}

However as you might have guessed, as far as i understand it, this loops through all entries as long as the current date/time is less than 8 hours AFTER the date/time of the event entry.

So to my understanding (Based on what i have observed) this will loop the entry up until 6am May/2/2015 which is not what i want.

In short. I'd like to ignore the 'time' portion of my date/time field as if it were May 1, 2015 12:00AM and add 29 hours, rather than including the time parameter of my date/time field and doing the math based on that which outputs variable results based on the time of the event.

Please let me know if i need to clarify any, I hope i've been clear. Also please let me know if there is anything else wrong with my For loop, it seems to work exactly how it should minus the date issue, but i'm always open to improvement.


texts: Feed Me Cron Job failing on 123-reg hosting

texts:
I'm trying to set up a cron job to run the feed me direct feed url in 123-reg hosting. The command they are saying to use is:
/usr/local/bin/php /home/username/public_html/index.php?p=actions/feed-me/feeds/run-task&direct=1&feedId=1&passkey=xxxxxxx

However I'm getting an error:
Could not open input file: /home/username/public_html/index.php?p=actions/feed-me/feeds/run-task
The feed action runs fine when used in a url. So is there something not right with the cron? Looking at the error message that is sent through it seems to be stripping anything after the first & ?


texts:
I scoured the the web to the ends of earth and couldn't find any info on how to install Craft 3 on my VPS. The package I downloaded is unconventional in many ways. Any ideas how to get Craft running?

By the way, why can't Craft 3 be installed like Wordpress?


texts: How to get started with ElementAPI & Ajax

texts:
This is related to the question previously asked and answered by OP. I tried to follow this method but couple of things that I don't understand (and of course can't solve the issue because of that).

I have a page where I fetch data based on a field (it is text field whose values are mm/yy and then I need to look for data that belong to certain categories but that is for round 2). I have drop downs, click on year, then click on the month and that would be the filter for entries.

1: How to do I call the code (even though I tried using this code ElementAPI - Can I use javascript/ajax to load json). I have a button which is supposed to call news.json but nothing happen.
2: He is using _layout.html to put that ajax call. I have many pages where I need to fetch data with different parameters, so ideally I would like to have the ajax code in the template itself rather than _layout.html

What am I really asking is for a working example that I can look at as I find it very confusing at this point. Like how would I debug/ look at the return values from news.json?

Any help is appreciated.
Thank you


texts: Query section entries based on start/end date and type

texts:
I'm having the following layout on a page: a messages page that shows events and news that are grouped in a section called messages. The page starts with current events, then upcoming events and finishes with all messages (old events and news).

The queries i need to run:

Current events

section messages
entry type event
where startdate is = or < now (starting today or earlier)
and enddate is = or > now (ending today or later)
ordered by startdate

Upcoming events

section messages
entry type event
where startdate is > now (starting later than today)
ordered by startdate

All messages

section messages
entry type all (event and news)
that exclude current events
and exclude upcoming events
with pagination

My current code where some parts are working:

Current events

{% set entries = craft.entries.section("messages").type("event").orderBy('startDate asc').all() %}
{% for entry in entries %}
  {% if entry.startDate < now and entry.endDate > now  %}

{{ entry.title }}

  {% endif %}
{% endfor %}

Upcoming events

{% set entries = craft.entries.section('messages').type("event").orderBy('startDate asc').all() %}
{% for entry in entries %}
  {% if entry.startDate > now %}

{{ entry.title }}

  {% endif %}
{% endfor %}

All messages

{% paginate craft.entries.section("messages").limit(9) as pageInfo, pageEntries %}
{% for entry in pageEntries %}

{{ entry.title }}

{% endfor %}

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

{{ page }}

  {% endfor %}

{{ pageInfo.currentPage }}

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

{{ page }}

  {% endfor %}

Two questions i have:

How do i query current events so startDate is < AND =? And endDate is > AND =?

And how do i query all messages (news and events), excluding current and upcoming events but with past events?


texts:
I've noticed that Craft 3 log files in storage/logs e.g. web-404s.log and web.log don't seem to have a max size or rotate like with Craft 2.

The web-404s.log file is nearly 10 megs for 1 site now.

Should the log files continually grow like this or is there just an issue with my setup?

Are there config settings to set the max log file size or disable certain logging that I'm missing?

Thanks


texts:
I'm a beginner and don't understand this error, and how to correct it:

Template error
Impossible to invoke a method ("getUrl") on a string variable ("60")

I'm trying to display only the first entry of one loop. In my case,
'selectedArtwork' has an Entries type and 'pictures' an Assets type.

Here is my code:

{% if entry.selectedArtwork | length %}
    {% for artwork in entry.selectedArtwork %}

        {% set assets = artwork.pictures.first() %}
        {% if assets | length %}
            {% for asset in assets %}

                {% set artworkPicture = { width: 475 } %}
                {% set artworkPictureRetina = { width: 930 } %}

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

And the part of code highlighted in Craft's debug mode are:

This code is working well as an entry template of another page of my website to display all entries, but not here for my homepage to only display the first entry.


texts: Craft Commerce cart timing out but allowing order to be processed

texts:
We had a Stripe order go through recently, where the order value was zero and there were no line items. The client has called the customer to figure out what happened:

The customer added a product to the cart as normal.
They entered their address details.
They reached the payment page and left it there for over an hour.
They returned and went to pay with Stripe, entering their card details and the payment seemingly going through but with a value of £0.00.
They were redirected to the order thank you page and received their order email detailing their purchase of nothing for £0.00.
They then completed the purchase afresh and it went through fine.

It's presumably an issue with the cart timing out. Does anyone know if there is anything I can do about this?


texts: How can I populate some records after my plugin is installed?

texts: When I install the plugin, I need to automatically create a few records. How can I have my plugin automatically create those records when it is installed?


texts: "Activate Your Account" message sent when user signs up, then again when admin activates

texts:
It seems strange that this is happening, but our users are being sent the Activate Your Account message first when they initially register (we aren't including the activation link in this email so admin must manually activate)- but then when admin activates, they are sent the same email.

Shouldn't there be a "Your Account Has Been Activated" message available for this instead? Or at least a way to avoid the email being sent twice?

We are using Pro 2.3.2644, and have "Verify Email Addresses" checked under Users > Settings, and a default user group called "Professionals" - everything else is fairly standard setup.

It doesn't look like a "Your Account has been activated" email message is available- could there be a way for us to hack this in until it's available as a setting in admin?

Thanks!

Ryan

Thanks


texts: Create a custom field with my plugin data

texts:
I want to create a field like categories but using my plugin data.

I need to be able to select one element in entry page to get all the elements from my plugin group base on that selection.

do i go with a custom field type or there is another way ?


texts: When saving an Entry, I receive a JSON response rather than returning to the Entry's edit page

texts:
Craft Version: 3.0.4
Web Server: Apache + Nginx proxy

Recently I've been working on a couple of Craft 3 projects for deployment on my institution's web servers. In the past, I've successfully launched numerous Craft 2 projects without server-specific issues, save for needing to set the Apache HTTP_ACCEPT header as follows in .htaccess (because it wasn't already configured by httpd.conf):

SetEnv HTTP_ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

On my initial attempts to deploy Craft 3 to the same servers (and using the same HTTP_ACCEPT configuration in .htaccess), I ran into odd behavior when trying to log in: initially the login process would fail silently (i.e. submitting username/password would process but remain on the login page), but if I were to then immediately refresh the login page a logged-in session would be established and Craft would load the CP.

Once the CP loaded, Craft would throw an error ("An unknown error occurred") and subsequent attempts to navigate through the CP would throw the same error and content such as lists of entries would not appear. Further investigation of network request showed that /actions (POST, GET) requests were failing with 400 Bad Request, with a response of "Request must accept JSON in response".

Initially, before I happened upon actual bad request response details, the folks at Craft thought the issue might pertain to an inconsistent use of HTTPS, or something specific to the use of the Nginx proxy server.

As a test, however, I added application/json to the HTTP_ACCEPT header as follows:

SetEnv HTTP_ACCEPT text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8

Low and behold, I was then able to successfully log in and navigate the CP. All of the POST and GET requests to /actions responded successfully.

Now, however, I've ended up in spot where saving an entry successfully commits the change to the database but renders the raw JSON response of the POST request on the page rather than returning to the entry's edit page. Here's an example of what I see in the browser when saving an entry:

{"success":true,"id":15107,"title":"test","slug":"test","cpEditUrl":"https://my.domain.com/operations/entries/generalPages/15107-test","authorUsername":"admin","dateCreated":"2018-05-02T10:08:10-05:00","dateUpdated":"2018-05-02T10:08:10-05:00","postDate":null}

The url in the browser remains on the entry such that if I refresh the page, I'm returned to the entry in the CP and see the updated content.

At this point, I'm stuck and not sure if the HTTP_ACCEPT header is configured incorrectly, or if the Nginx proxy server is indeed interfering with the requests.

Many thanks in advance for thoughts/assistance.


texts:
I represent a leading online music tuition platform. We are considering using Craft to develop our new platform. We have a couple of questions about the capabilities of the platform.

1 - Can we build an SVOD and TVOD platform on Craft? The video would be pulled from our CDN and displayed via JW player.

2 - Can we build a social side to our site, where members can share content to a centralized social dashboard.

Any help or advice would be greatly received.


texts: Entries from matrix should not appear in loop

texts:
I have a Matrix with an entry field.
I have a Loop which is looping entries out of a section.

Goal: The entries from the matrix should not appear in the loop of the section.  So the Matrix defines Starred Member Profiles and the loop trough the section is a teamlist, but the two starred profiles should not appear in there.

I tried something like this but i stuck right now...

{# Get the profiles which are in the matrix #}
{% set highlightProfiles = entry.highlightProfiles.all() %}

{% for profile in highlightProfiles %}

 {# Just a test to see the ID of each single entry #}
 {{ profile.hightlightProfileTeaser.one().id() }}

 {% set highlightProfileSingleIds = profile.hightlightProfileTeaser.all().ids() %}

{% endfor %}

{# set something up for the entry ids which should not join in the endloop #}
{% set highlightProfileIdsString = highlightProfileSingleIds | join(', not ') %}

{% set teamMembers = craft.entries({
 section: 'profiles',
 limit: 50
}) %}

{% set allProfilesWithOutHighlights = teamMembers.id('and, not '~highlightProfileIdsString).orderBy('title asc') %}
{% for member in allOtherMembers.orderBy('title asc').all()  %}
 {{ member.title }} {{ member.id() }} {{ loop.index }}
{% endfor %}


texts: Craft News Feed not working after 2.5 Update

texts: Not a major thing but I just noticed the Craft News Feed on the dashboard is not showing.  It is still looking for https://craftcms.com/news.rss.  Any ideas what is up with that?


texts:
I have a form for updating user info, with a field of birth date.
However, I am struggling to develop a validation for this date field by PHP.

Its frontend code is this;

{% set tz = craft.app.getTimezone() %}
{% set df = craft.app.locale.getDateFormat('short', 'php') %}

    Test Date
    <input type="text" id="testDate" name="fields[testDate][date]" {%- if user is defined %} value="{{ user.testDate|date(df, tz) }}"{% endif %}>
    {{ hiddenInput('fields[testDate][timezone]', tz) }}

In PHP, the input date is gotten by this code.

$testDate = $event->sender->testDate;

But this $testDate has already been converted to Date.
Even the input is invalid date (i.e. 5/32/2020), the form converts it to Jun 01.

How can I validate this date?

[Added on Jun 09]

The form's header is like this;

<form method="post" accept-charset="UTF-8" class="members-form updateprofile-form">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="users/save-user">
    <input type="hidden" name="formType" id="formType" value="updateprofile">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

And, the PHP code is triggered by EVENT_BEFORE_VALIDATE event.


texts: Creating a new locale on craft 2, entries won't load

texts:
I have an issue creating a new locale, I already have two set up 'en_gb' and 'en_au' and have added a third 'fr'.

I have added the new locale to general.php:

'.com' => array(
  'siteUrl' => array(
        'en_gb' => 'https://xxx.com/',
        'en_au' => 'https://xxx.com/au/',
        'fr' => 'https://xxx.com/fr/'
    ),
  'devMode' => false
),

And have enabled that locale on the section with exactly the same settings as the others:

When I switch to the French locale on an entry I can live preview without a problem, but when I actually publish the page and visit it the entry cannot be found.

I'm well and truly stumped on why I can't access the published page.

When creating the locale I did have issues with failed tasks re-saving entries which I spent a lot of time trying to debug with this guide without luck and with less hair. Would this be a cause considering the locale shows on an entry and the live preview works?


texts: JSON response displayed as plain text on submission when creating/editing an entry

texts:
I am running Craft Pro 2.2.2601. When I submit an entry, I am getting back JSON rather than being redirected to a success page.

For example, I just go to:

/admin/entries/pages/new

I fill out some fields and click Save. It kicks me to the next page that displays JSON as the source as opposed to an "Entry saved" flash message:

{"success":true,"title":"Services","cpEditUrl":"http:\/\/www.test123.com\/admin\/entries\/pages\/22-services","author":{"id":"1","enabled":"1","archived":"0","locale":"en_us","localeEnabled":true,"slug":null,"uri":null,"dateCreated":{"date":"2014-11-04 15:44:04","timezone_type":1,"timezone":"+00:00"},"dateUpdated":{"date":"2014-11-04 15:44:04","timezone_type":1,"timezone":"+00:00"},"root":null,"lft":null,"rgt":null,"level":null,"username":"test123","photo":null,"firstName":null,"lastName":null,"email":"test123@gmail.com","preferredLocale":null,"admin":"1","client":"0","status":"active","lastLoginDate":{"date":"2014-11-07 02:01:58","timezone_type":1,"timezone":"+00:00"},"invalidLoginCount":null,"lastInvalidLoginDate":null,"lockoutDate":null,"passwordResetRequired":"0","lastPasswordChangeDate":{"date":"2014-11-04 15:44:04","timezone_type":1,"timezone":"+00:00"},"unverifiedEmail":null,"newPassword":null,"currentPassword":null,"verificationCodeIssuedDate":null},"postDate":"11\/6\/2014"}

The page also contains the posted data, so refreshing re-submits the form post. I have disabled JS compression and it worked once (got the "Entry saved" flash message), but now it is back to spitting out JSON.


texts: Correct Limit for Entries with IF statements

texts:
I have content on my site that can't be shown in some countries and requires a basic level of geo-targeting, based on the users profile and not by any form of IP geo-targeting.

I have set up an address field on the users profile with country and created a matrix block  with a geo-targeting toggle (lightswitch field) for my entries. Then I'm using the below code to:

Show all entries to logged out users (as we do not know their country at this point)
Only show content with no geo-targeting or where the users country matches a country code of geo-targeted content.

{% set category = craft.categories()
        .all()
        %}

{% set params = {
              section:    'articlesWhitepapers',
              typeId:      'not 7',
              relatedTo:    category
            } %}

    {% set user = user is defined ? user : currentUser  %}

    {% set recentPosts = craft.entries(params)
    .with([ ['companyName.companyLogo', { kind: 'image' }, { withTransforms: ['featuredImage'] }], 'companyName',['author.userPicture', { kind: 'image' }, { withTransforms: ['featuredImage'] }]])
    .orderBy('RAND()')
    .limit(2)
    .all()
    %}
    {# Fetch the entries #}
    {% set entries = recentPosts %}

    {% for entry in entries %}
    {% set relatedCompany = entry.companyName? entry.companyName[0] : null %}

        {% if craft.app.user.isGuest %}
        {# Show Everything Regardless #}

        {% include "home/_main-feat" %}

        {% else %}

        {# Check Geo Targeting #}

            {% for block in entry.addArticlePaper %}
            {# get the matrix block by type #}
                {% if block.type == "addArticleOrPaper" %}
                    {% if block.geoTargetContent %}

                        {% for country in block.orAddCustomGeoTargeting %}
                        {% set country = country.value %}

                        {# use the variable to filter the entries #}
                            {% if country == user.location.countryCode  %}

                            {% include "home/_main-feat" %}

                            {% endif %}

                        {% endfor %}

                    {% else %}

                    {% include "home/_main-feat" %}

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

 {% endfor %}

This is working great and the correct content is displayed. The problem is I always want to show two pieces of content and currently it is checking the limited results and returning either 0, 1 or 2 pieces of content as its using the if logic against only two results. How would I restructure the above to continue to allow my geo-targeting to work correctly whilst ensuring there are always two pieces of content shown? I have tried a few different ways but no luck so far!

many thanks in advance!!


texts:
I'm trying to build an array of values from 4 entries so I can lay them out in a comparison chart. I figured the best way to do this would be to add all of the values to a nested array. So I've set this up...

{% set plandata = {
        'membership-type' : {
            'title' : 'Membership Type',
            'url' : '',
            'price' : '',
            'items' : []
        }
    }
 %}

then I'm iterating through a field and trying to add them to the items portion like so...

{% for amenity in entry.availableAmenities %}
    {% set plandata.membership-type.items = plandata.membership-type.items|merge(amenity.title) %}
{% endfor %}

However I am getting a Template Error:  Unexpected token "punctuation" of value "." ("end of statement block" expected).

Can anyone give me any insight as to what I'm doing wrong?


texts: Looking at potentially 100,000 users/entries to capture data

texts:
Looking at a small site build, but potentially capturing Names, Email and Addresses /custom fields, then dumping into a csv.

There's no user activation, but any potential issues with so many entries in the sql database in any one go?

User Registration in Craft seems to fit the bill nicely for us.

Any experience or notes welcome.


texts:
What’s the best way to paginate search results?

I was using

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

and then

{% paginate craft.entries.search(query).section('…').limit(…).order('…') as entries %}

but the pagination links (paginate.prevUrl and paginate.nextUrl) don’t contain the query.


texts: FeedMe SSL error - cURL error 35: SSL connect error

texts:
I'm getting an error when trying to access an endpoint over ssl in FeedMe. eg https://jsonplaceholder.typicode.com/posts

The error is
cURL error 35: SSL connect error

Error reported in web.log is
[verbb\feedme\base\PluginTrait::error] Test: Unable to reach https://jsonplaceholder.typicode.com/posts. Message: cURL error 35: SSL connect error (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

I've tried running curl directly from commandline on the server and it runs fine:
curl https://jsonplaceholder.typicode.com/posts prints the JSON.

PHP: 7.2.5
cURL: 7.19.7


texts: Can a non-admin add Entry types into a section?

texts:
Is there a way to allow a user to edit sections without making them site Admins? For example, I have a couple of users that I want to allow them to create new entry types within a Channel, but I don’t want them to be able to access the rest of the Settings section of the CP or do everything an Admin can do.

I'm guessing this is something that will require a custom plugin, but is it possible to sidestep the admin permissions to create new entry types?


texts: AWS S3 permissions issues with referrer conditions

texts:
I've got an odd situation happening with assets stored on AWS S3, which I'd appreciate some help understanding and resolving.
Background
Software Version: Craft CMS v2.9.1
All S3 assets were recently moved to a new AWS account. I can't say if this issue started occurring after that, or if it was pre-existing. I inherited management of the site, and have no prior knowledge of the accessibility of these S3 assets.
The assets have identical permissions on S3, which is via a policy on the Bucket.
The Bucket policy is:
{
    "Id": "Policy1599693986936",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1599693977359",
            "Action": [
                "s3:GetBucketLocation",
                "s3:ListBucket",
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject",
                "s3:GetObjectAcl",
                "s3:PutObjectAcl"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::media2.ourdomain.co.nz",
                "arn:aws:s3:::media2.ourdomain.co.nz/*"
            ],
            "Condition": {
                "StringLike": {
                    "aws:Referer": [
                        "https://ourdomain.co.nz/*",
                        "http://ourdomain.co.nz/*",
                    ]
                }
            },
            "Principal": "*"
        }
    ]
}

The Issue
Most of the assets cause a permissions error when accessed from the front-end of the site. E.g, <Error> AccessDenied <Message>Access Denied</Message> <RequestId>67D10441C68705B6</RequestId> <HostId>AJcRfJh6jciXYC61tb+UUCgPGjtq41aMhDSlVI8kFj/g9COlnW49XhBjIFAOdUtq0DJQoKd+9Iw=</HostId> </Error>
I can, however, access the same file from the back-end of the site (in Assets).
Some files I can access from the front-end. Which is odd, as to the best of my knowledge they all have the same permissions (bucket policies, etc.).
It's not clear to me how files in the same bucket, with the same permissions, can vary in their accessibility. Some I can view on front-end, some I can't (due to Access Denied error).
Can someone suggest what might be causing this, or how to resolve it?
Thank you.
UPDATE
I've discovered it's the Conditional in the policy that's breaking things. If I remove the condition (which is the referrer URL) all files I've tested on front end are now accessible (including those I couldn't access previously). This raises two question:

Why would it be inconsistent when the referrer condition is there? All files are being linked to from the same referrer.
Why would the referrer condition break it at all (when the links are from that referrer)?


texts: Loading an existing entries drafts in template/frontend

texts:
I've been searching for a method to load in an existing entries drafts. Here is what I am trying to implement.

User can add or edit an entry from the front end of my craft site. They cannot publish.
Admin can see new drafts and publish them.

I see how to submit a draft update via the front end using the entryRevisions/saveDraft method. But how can I load in the current entries draft information into a form on the front end for a user to edit? Hopefully I missed this, or is it undocumented.


texts:
I have a strange issue, I can't upload files to the server.

The error message is

Error uploading the file: The folder craft/storage/runtime/assets/tempuploads/user_7/field_101 does not exist

The stranger thing is that another person working on the same project, with the same rights as me (admin) can perfectly upload files.
Once he does that, I can upload files to that same location too

There is no folder called "user_7" in tempuploads. Just field_52, field_54, etc.


texts: I installed the Element API plugin and the elementapi.php file within the craft/config/ folder is set up just like the example on Github. I'm also trying to use this with a section called "news" like the example. However, when I try to access news.json I get a 404. Am I missing something? Do I need to call something in my templates to make that feed available?


texts: Specify number of loops for animated GIF (ImageMagick)?

texts:
I'm experimenting with Craft 2.6, and am having a bit of difficulty with animated GIFs. The original animated GIF files I'm working with are set up to only loop once, but when I upload them into Craft and they're processed, the resulting GIFs loop infinitely.

Craft is running locally on my Mac, and I've made sure that ImageMagick is installed and working via MAMP and PHP 5.6.

Is this something that could be added as a feature to Craft 2 (having it check for the original number of loops in the GIF file, then recreating it with the same value)?  Or is that already in the works for Craft 3 and not in the cards for version 2?  :)  Thanks!


texts: What is the difference between elements.enabled and elements_i18n.enabled?

texts: It appears, toggling the status button on an entry affects only the elements.enabled value.  What affects the elements_i18n.enabled value?  When and how would we choose to update the enabled column in the elements_i18n table?


texts: What does the Timezone in Settings -> General represent?

texts:
Should it be set to the timezone of the server Craft is installed on, or the timezone of the current user, or something else?

I can find no documentation about these settings anywhere.


texts: Is there a way to know if a discount is going to be applied on a product?

texts:
I have set up a number of discounts using Craft Commerce. Those discounts apply to specific groups of users and types of products.

Is there a way to know inside the template, if a discount is going to be applied without checking the product type or user group of the current user?


texts: Loop through entries that share current entry category and restrict to Cat Group Id

texts:
I've been racking my brains trying to get my head around categories and entries, hopefully someone can help and show me the best way.

I have an entry page with product information and this product is assigned to multiple categories across multiple groups. I need to exclude the category 'preferential' and only show entries that belong to the category group 'offers'.

Here's what I've got so far:

{% set categories = craft.categories.relatedTo(entry) %}
{% set excludeCat = craft.categories.slug('preferential').first() %}

{% set allIds = [] %}
{% for id in categories.ids() if id != excludeCat.id %}
    {% set allIds = allIds|merge([id]) %}
{% endfor %}

{% set entries = craft.entries.relatedTo(allIds) %}

{% for offer in entries %}
    {{ offer.title }}

{% endfor %}

I've tried variations of 'group', 'ids' and 'groupId' but no joy. This is my first Craft CMS build so still learning.

Thanks!


texts: Best way to programmatically create categories?

texts:
We're working on an XML import plugin to migrate content from another CMS.

What's the best way to create a new category (with a name, slug etc.) and assign it to the entry when running
$entryModel = new EntryModel(); ?


texts: Craft 3: how to show the Yii Debug Toolbar?

texts: I'm using Craft 3 RC and I am logged as an admin. How can I display the Yii debug toolbar on front-end and Control Panel requests? By default, I don't see this toolbar.


texts: Do ImageOptimize Volume Variant Transforms replace Craft's default Asset Transforms?

texts:
Do the ImageOptimize variants that are set on volumes replace the default image transforms that can be set within Craft asset settings?

I just want to check as the plugin documentation isn't really explicit about this.


texts: Using an IF-statement to define the Entry URL Format

texts:
Within a channel I have two kinds of possible article types, which I separate with the entry type feature. For the entry URL format I want to include the type, but only for one of the two.

I've tried channel{% if type.handle == 'xyz' %}/{type}{% endif %}/{slug} but without success.

I've tested "if 2 > 1" and it did output the type, so I guess the structure of the if-statement is correct. Does anyone have an idea how I could make this work?


texts: Allow user to change or delete their photo for their profile from the front end

texts:
How can I allow a user to change or delete their photo for their profile from the front end?

I currently have a form setup for the user to edit their profile but I want to load their current photo (or a default) and then allow them to change it or delete it.


texts:
I need to get Matrix field content from a entries sibling. Essentially, I have a block type called gallery within my project pages, and under the project content on each page, I have a section for Other Recent Projects. I'd like to be able to get the first image from the gallery block of the previous and next siblings and output it in this recent projects section. How can I do that?

Thanks,
J


texts:
I need to order the results of a search query after I got back the results. The reason to do this is that I want to make different lists on the same page (with the same results) and I dont't want to search over and over again just to reorder te results. Can I do that? So basically I do this:

{% set results =  craft.entries.section('player').search('team:"thenameoftheteam"') %}

What I want to do with this result is:
loop

through the results and order them by playerPosition
show the longest player (lengths are in the field playerHeight)
show the oldest player (birth dates are in the field playerBirth)

I could run this query 3 times and order by a different field each time, but I don't think that's the way to go.


texts: How can I force a request type (HttpRequestService::isCpRequest vs. HttpRequestService::isSiteRequest)?

texts:
Is there a way to force a request type (HttpRequestService::isCpRequest vs. HttpRequestService::isSiteRequest)?

In my case I'm generating some indexing data on entries.onSaveEntry. I'm trying to use some UrlHelper methods, but the resulting urls are wrong, since it thinks it is a cp request.

I have to do something like this load templates:

craft()->templates->setTemplateMode(TemplateMode::Site);

Is there any way to do something similar for request type?


texts: Is it possible to assign fields to entries by category?

texts:
I want to show some fields depending in the category selected for the entry but within the editing stage. is it possible?

If not, then how can i check if the entry is in a category in the template and output a field group.

thanks ahead!


texts:
I'm going wrong here somewhere, but I have a (edit) entry form and I'd like a 'disable' field to change status. The edit form works fine but status changes are ignored. Here's my field:

<input type="checkbox" name="enabled" id="enabled" value="{{ entry.enabled }}"{{ entry.enabled == '1' ? ' checked' }}>

Am I missing something? Thanks guys.


texts: Element-api - filter Draft entries by the draft author (not original author)

texts:
I have a remote app that enables preview based on your editor craft account. I want to retrieve draft entries that they are working on, but i cant find a way to do this. 'authorId' seems to always be the original author of the entry, rather than the draft.

Here is the important bit of my code ->

$user = Craft::$app->users->getUserByUsernameOrEmail($userp);

           return [
          'elementType' => Entry::class,
          'paginate' => false,
          'pretty' => true,
          'criteria' => ['draftId' => $entryId, 'section' => 'cashwrap', 'drafts' => true, 'orderBy'   => 'dateUpdated desc', 'authorId' => $user->id, 'limit' => 10 ],

I cant find any ref for retrieving, or filtering by the draft author id? The above will only show drafts for original author id not draft author.


texts: Listen for checkbox check event for assets table and modify action trigger menu item

texts:
I am able to listen to an event when the user checks the checkbox in the assets table. This is within my js file init file that extends garnish: Garnish.Base.extend

When the checkbox is selected, I see "checkbox clicked" in the console. The commented out in the function below is just to explain what I need to do when the checkbox is checked.

$('.elements:first').on('click', '.checkbox', function(event) {

    if ($(event.target).is('#main .elements:first .checkbox')) {
        console.log('checkbox clicked');

        // if file kind == "Image"
            // hide "View asset" from actions menu in the toolbar
        // else
            // do nothing

    }
});

What I need to do is, when the user checks the box, I need to determine the file kind, using the data-attr kind, the html for that td cell is below.

Image

If it is an image, then hide the "View asset" from the menu dropdown that displays in the toolbar. (image attached)

The view asset has an id of: View-actiontrigger

I am having trouble accessing it as it does not exist when my code is firing on the checkbox click.


texts: "Updating search indexes" message in admin sidebar

texts:
I'm noticing the following error in my admin sidebar:

If I try to retry it just fails again. I can't see anything obviously failing in my logs. I'm not sure if this is related to the queue, but if I look at my queue info I see a failed job:

$> ./craft queue/info
Jobs
- waiting: 0
- delayed: 0
- reserved: 0
- failed: 1

The Craft docs mention the ability to rebuild the search index manually:

  Craft does its best to keep its search indexes as up-to-date as possible, but there are a couple things that might render portions of them inaccurate. If you suspect that your search indexes don’t have the latest and greatest data, you can have Craft rebuild them with the Rebuild Search Indexes tool in Settings.

But looking at this Github issue:

https://github.com/craftcms/cms/issues/3698

It appears that this option has been removed.


texts: How to disable element editor on custom element type?

texts: I'm working on custom element type and I'd like to disable the editor modal at element index view that appears when you double-click on status icons/thumbnails in the title column. Any help?


texts: Extending the Users section of the admin panel

texts:
Is it possible to add additional tab views that aren't related to user fields?

We would like to show a summary of user account activity that includes details of purchases they have made. A plugin would work obviously but we would want all of this information in the existing user area rather than in a new area for the plugin.


texts:
I'm trying to get the category title to render within the following object but it's just returning it as the static string instead of the {{ category.title }} actually rendering.

{% set seo = craft.seo.custom(
    'Welcome back, {{ category.title }}',
    'Test Meta Description!'
) %}


texts: Can I Configure Redactor to Automatically Add a Class to Img Tags?

texts:
I am trying to set up lazy loading for the images on my site but currently, any image added via Redactor lacks the necessary 'lazyload' class.

Is there any way to configure Redactor to automatically add this class to any image added through Redactor? I have been digging through the documentation on their site and doing some googling but so far haven't found anything.


texts: Is it possible to convert string to uppercase?

texts: Is it possible to convert a simple string ("Hello World!") to uppercase ("HELLO WORLD!")?


texts: How to return a hierarchical list of a site's page structure using the ElementAPI

texts:
I'm experimenting with using Craft in a headless way and am successfully using the Element API to return all the data required to show individual pages.

However, to be able to show sub navigation and where a particular page fits into my site's 'structure' hierachy, I'd like to pull out the entire page hierarchy and then use that info in my application.

Does anyone know how to go about that using the Element API?

Thanks in advance for any clues.

Cheers,

Jim


texts: Logging in to Craft via Vue/Javascript apps

texts:
I'm just diving into the world of javascript frameworks (late to the party I know) and can't figure out the missing piece of the authentication puzzle.

What is the preferred way to authenticate users from a Vue or any other javascript app running from element API? My Craft install and the app will be on separate domains.

Is it best to just push them to the craft install to log in then rely on sessions (is this secure?), or is there a preferred way? I have seen JWT's mentioned a few times, but guessing this will be tricky for a non-developer.


texts:
Trying to convert a plugin from Craft 2 to Craft 3, not sure what's the Records equivalent in Craft 3.
How do I get this to work in C3?
class SearchRelationshipRecord extends BaseRecord
{
    public function tableName()
    {
        return 'some_name';
    }

    protected function setAttributes()
    {
        return [
            'aaa' => AttributeType::Number,
            'bbb' => AttributeType::Number,
            'ccc' => AttributeType::String
        ];
    }

    public function defineIndexes()
    {
        return [
            ['columns' => ['aaa']],
            ['columns' => ['bbb']],
            ['columns' => ['aaa', 'ccc']],
            ['columns' => ['bbb', 'ccc']],
        ];
    }
}


texts: Check and remove repeat entries from loop

texts:
Is it possible to loop through the list of entries and filter out any that have the same ID as any of the other entries (duplicates)? I have a specific case where this is an issue. I want to keep the first entry, but filter out the rest of them. I'm thinking it might work something like this...

  {% for event in events %}
    {% IF FIRST INSTANCE OF ENTRY %}
      {{ event.title }}
    {% endif %}
  {% endfor %}


texts:
I deleted a locale and checked to transfer all its contents to a different locale, but now the other locale still shows no entries.  I'm sure all the entries are still in the database.

Any help?


texts: knock-knock plugin How to only password protect a single page?

texts:
I have Craft CMS 3.6.5.1 and have installed Knock Knock plugin because I want to password protect a page on my website BUT NOT MY HOMEPAGE.
There is a tab option that is labeled URLs and within it, there are two text areas.
1.
Protected URLs
Provide a list of URLs to protect with a password. By default, this will be the entire site. You can use absolute or relative URLs and aliases. Regex is also supported (for example /some-channel/(.*)). One URL per line.
www.mysite.ca/about/
2.
Unprotected URLs
Provide a list of URLs to be excluded from password protection. By default, this will be empty. You can use absolute or relative URLs and aliases. Regex is also supported (for example /some-channel/(.*)). One URL per line.
www.mysite.ca/
When I add my URL to my homepage on the Unprotected URls knock knock it just doesn't seem to work and completely removes the password protection altogether. Is there a way to have the homepage unprotected while protect some inner pages of my website?


texts: URL Format of a nested structure with 3 or more layers

texts:
I have a nested Structure with 3 layers like so:

Home
Services

Service A

Sub Service A
Sub Service B

Service B

About Us
Contact

Now I would like the nesting to be reflected in the URL like so:

http://example.com/services/service-a/sub-service-a

I used {parent.slug}/{slug} as the URL Format and this is working for two but not three layers.

How would the correct format look like?


texts:
Hi I'm trying to template out a simple conditional that shows content if the date set in a date field is greater or equal to today, and I can't seem to get the syntax quite right.

I have tried this:

{% if entry.promoEndDate|date ('>= ' ~ now) %}

Price valid until {{ entry.promoEndDate | date('d M Y') }}

{% endif %}

And this:

{% if entry.promoEndDate | date >= now | date %}

Price valid until {{ entry.promoEndDate | date('d M Y') }}

{% endif %}

Both don't yield the result I'm looking for.
Probably missing something really simple here but looked at it too long now.

Thanks in advance


texts: How can I restrict access to the Control Panel to a single port?

texts: Is it possible to limit access to the Control Panel to a specific HTTP port, which is shielded from public access? We want external visitors to only be able to access the front end site.


texts: Can I use Freeform's JavaScript plugin to alter field options on the fly?

texts:
I have a Freeform form that consists of 4 pages. On the first page, the visitor selects a date. Based on that date, the options of the select fields on page 2, 3 and 4 should change.

Can I somehow access the posted data of page 1, on page 2?
Can I alter the options for a Freeform checkbox field after it's been loaded? Would this cause problems when submitting the form?


texts: DRY variable setting across templates (macro for variable?)

texts:
I have a need for something like the following:
{# Template A #}
    {# Do X that sets variable x #}
    {# Do Y that sets variable y #}
    {# Pass x and y into A include partials #}

{# Template B #}
    {# Do X that sets variable x #}
    {# Do Y that sets variable y #}
    {# Pass x and y into B include partials #}

The logic for X and Y is the same in templates A and B.
Is there a way to write each once in some kind of dedicated partial and place them in templates A and B, something akin to return in a JavaScript function?
I'm not sure there is. I think that macros only produce front-end output. And so I have to duplicate the logic in each template. Is that right?


texts:
What's your process for A/B testing a Craft entry? I'm curious about how you'd structure alternative content for a page within Craft and what tools you'd use to measure the results.

Any comments appreciated - I know there are lots of different ways you could approach this!


texts: Check in header file if lightswitch field is on

texts:
For a menu I have to check if a lightswitch field is on or not. The menu is in an extra header file. I've tried:

{% if craft.entries.section('aboutus').lightswitch_field %}style="display: none;"{% else %} ... {% endif %}

but this always jumps into the else part.


texts: How to strip out src="" value with twig from iframe code

texts:
I have have a text field for copy-pasting an iFrame code.

<iframe src="https://webpagelink.com/l/3556456/2019-03-06/34576" width="100%"
height="500" type="text/html" frameborder="0" allowTransparency="true"
style="border: 0"></iframe>

What I need help with is striping out the URL within the src="" value from the iframe. Is this possible using Twig?

Thank you for your help!


texts: Programatically add lines to a Super Table field

texts:
I am trying to add new lines into a SuperTable field of an entry from my plugin.
Following the Developper sample, I am able to change set lines to this SuperTable field.
But it is replacing the existing content.
What should I do to be able to keep existing lines in my SuperTable and add new ones?
Thanks for your help!


texts:
I have three sections:

Discography
Performers
Works

Within "Discography", a Matrix field contains related entries from "Performers" and from "Works".

I am looking to display those related entries in Discography with the code below, but nothing happens (no error, no display):

{% for entry in craft.entries.section('Discography').order('title') %}

    {{ entry.title }}

    {% for block in entry.discoOeuvres %}

        {% set relatedWorks = craft.entries.section('Works').relatedTo(entry) %}
        {% set relatedPerformers = craft.entries.section('Performers').relatedTo(entry) %}

        {% for work in relatedWorks %}
            {{ work.title }}

            {% for performer in relatedPerformers %}
                {{ performer.title }}
            {% endfor %}
        {% endfor %}
    {% endfor %}
{% endfor %}

Also tried to follow this solution, with no success...

Where do I miss something?

Thanks for helping.


texts: Craft Commerce: Custom Rounding (for taxes and discounts)

texts:
Is there a way to change the default rounding behaviour of Craft Commerce? Here in Switzerland we always round to 5 cents, so amounts like 9.99 or 9.22 don't really exist. Here's an example:

9.99 must be rounded to 10.00
9.98 must be rounded to 10.00
9.97 must be rounded to 9.95
9.96 must be rounded to 9.95
9.95 must stay the same
9.94 must be rounded to 9.95
9.93 must be rounded to 9.95
9.92 must be rounded to 9.90
9.91 must be rounded to 9.90

Product Prices
The product prices we enter manually do follow the guidelines mentioned above, so we never get "odd" prices when putting products to the cart.

Shipping Costs
Shipping costs are also no problem (it's either free or fixed price shipping).

Taxes
Taxes are a problem for us since we use a tax rate of 7.7% which can lead to "odd" tax amounts (and this leads to "odd" total amounts).

Discounts
Discounts can also be a problem since they also sometimes lead to "odd" numbers (i.e. a 10% coupon on 14.85 is giving a discount result of -1.49 instead of -1.50).

So is there any way to change the rounding behaviour (either globally or for taxes only)? On the frontend part I think we could achieve that with the Twig filter "number_format", but we need the correct amounts also in the backend.


texts: LastPass causing incorrect email address to be saved in new user form

texts:
I already have a solution for this but am writing it up in case others run into the same issue.

After creating a new user, my email address was showing up as the username of the new user. (This site uses email addresses as the username; useEmailAsUsername is set to true in config/general.php.) Here's how it looked in the user list:

It also showed up on the user page:

I thought I might have stumbled on a bug related to useEmailAsUsername. Silly me. Craft support (hi, Brad) wasn't able to reproduce it and suggested it might be an auto-fill browser extension misbehaving. Sure enough…


texts: One of the pages in the menu header is called Order Online, which takes users to a separate website.  I want to change the link where it takes users to but when I went to the backend of the site, the page is not listed under pages, nor is it listed under entries.  I have no idea where it is listed!


texts: Get query string param that has no value

texts:
Is it possible to determine whether or not a query string has a param with no value. For example

http://www.test.com?myparam

Technically that's a valid url but the craft.request object doesn't appear to have a way to see that. craft.request.getParam('myparam') returns nothing as does craft.request.getQuery('myparam'). I have tried using an explicit test for 'true' and 'false' but no luck.

Right now I'm grabbing the entire query string value and then using the 'in' to find the param name but thats pretty fragile is another param or value contains the same string.


texts:
How would I access the available RedisCache class and it's properties/methods in PHP/plugins? (https://buildwithcraft.com/classreference/etc/cache/RedisCache)

I'm just starting to learn Redis and can't seem to find more information about how to start using the available class. I have set cacheMethod to redis, and created a rediscache.php file in craft/config/.

I want to explore connecting to db, inserting my own keys/values and retrieving data for my other plugins, but can't seem to find the right path path. I tried things like:

echo craft()->redisCache->hostname;

But that returns CExeption errors. What am I missing?


texts: Unable to connect to db via console with a custom config directory path

texts:
I've just used yiic for the first time for a plugin record installation and found that the db.php config file didn't seem to be picked up and I got database connection failures.

I added a console array to the file to try that but still no joy. So I edited the craft/app/etc/config/defaults/db.php with the username, password, table prefix and database name of my local install and it all works fine.

I've not tried this on a vanilla Craft install but I'm guessing that this may be because my config directory has been renamed to config-mydomainname as we are running 2 craft sites off of one craft instance.

That works by way of the following in the ./public_html/index.php file:

define('CRAFT_CONFIG_PATH', '../craft/config-mydomainname/');

Is this change of path causing the issue with the console?


texts: Why are some entry detail views empty in the control panel?

texts:
I can't seem to edit entry details all of a sudden: in this Products section (and only this one section), the page title and "Current Version" button will render, but the rest of the page is missing.

The only clue is this line from Craft's log:

  [31-Jul-2014 19:07:36 UTC] PHP Fatal error: Maximum function nesting level of '100' reached, aborting! in /Users/gob/projects/gobias/craft/app/vendor/twig/twig/lib/Twig/Node.php on line 140

I've loaded earlier MySQL backups, restarted MAMP Pro (PHP 5.5.10), cleared Craft's caches, tried different browsers and machines, and the problem persists.


texts:
I'm wondering if anyone's using .htpasswd for basic site security for a staging site that's in review (where we're testing front-end registrations so we don't want to force control panel logins, either), with an exception opened up for controllers that serve as webhooks for a third-party service to call. (Specifically, in this case, our forms push data to Salesforce via its API, and then Salesforce needs to be able to talk back to our server.)
From what I can tell, the following should be working, matching on a substring in the querystring on the controller URL, which looks like this:
https://mydevsitedomain.com/index.php?p=actions/namespace/controller/method&recordId=123
SetEnvIfExpr "%{QUERY_STRING} =~ /namespace/" api

AuthType Basic
AuthName "Staging"
AuthUserFile /storage/av#####/.htpasswd

Order allow,deny
Require valid-user
Allow from env=api
Deny from env=!api
Satisfy any

Where I left off: Basic authentication is working fine for other parts of the site. The exception URL seems to be in a redirect loop I can't solve for, continually popping up an authentication modal that I haven't submitted credentials via, because I'm trying to test for the exception to be allowed.
I'm about to give up and just redirect the homepage if I don't have a logged-in user, though I really prefer to safeguard against any unwanted eyes (or indexing bots) hitting the sites. If anyone's solved for this before, it'd be worth documenting!


texts: How can I troubleshoot why my queue of tasks in stuck in Craft 3?

texts:
I have a series of tasks lined up in the queue to run but they are just marking one as in progress and then sitting there and not executing.

I have tried updating the DB table "queue" by doing the following:

1) Changing the failed field to 1 and dateFailed to NOW() thus marking the task as failed then clicking the retry option. This just puts the task back into the same routine.

2) Changing both dateReserved and timeUpdated to NULL thus resetting the task and it go back into pending but this also doesn't help.

I'm trying to debug the cause of this but getting lost in the code as it seems the QueueController is setting everything as it should be but then either not getting a response and updating the progress or it's failing silently somewhere along the way.

I have attached my queue logs below for reference but I can't see anything unless I am missing something glaringly obvious!?

I asked on the #craft3 Slack channel and got some help but nothing worked. Hopefully, we can find a solution on here and share with others.

CP Screenshot

Database Screenshot

Queue.log


texts: Contact Form sent via Ajax with file upload returns 302 instead of 200 status code

texts:
I’m using the Contact Form plugin to submit a form that can also upload files via Ajax. The problem ist that instead of a success (200) I get a status code of 302. But I receive the resulting mail properly.

Everything worked fine when I hadn’t set everything up for the file upload. I serialized the form data, expected json, success (200).

...
dataType: 'json',
data: $(this).serialize(),
...

But when I switched to this to enable receiving files, things went south (302):

const formData = new FormData(this.form);

$.post({
    url: '/index.php',
    data: formData,
    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,

    success: response => {
        if (response.success) {
            this.showSuccess();
        } else {
            this.showError();
        }
    },
    error: (xhr) => {
        // FIXME: This is a workaround because for some reason Craft returns a 302, even though everything works
        //        fine. See stackoverflow question here and fix if there is a solution.
        if (xhr.status === 302) {
        this.showSuccess();
        } else {
        this.showError();
        }
    }
});

I’m on Craft 3.0.15 and set up SMTP in Settings -> EMail. I tried it locally (using MAMP) and on my hosted server. Both give me the 302.

Any hint would be much appreciated.

Cheers,
Mark


texts:
Is there a way to disable the general entry enable/disable toggle button for some users and let them have only the localised enable/disable button.
Because I had the problem that a user disabled an entry with the general button and he disabled the entry for all locales. So I want to make it easier for them and remove that general button that affects others.


texts: Is it possible to allow some users to write content & an editor can edit & publish / approve it?


texts: How can I safely identify a single asset-folder?

texts:
Background

I'm writing a plugin that will function as a document-archive with access-rights to different folders set based on user-groups.

In addition to folders which are restricted, there is also one folder in the asset-source which is "open" to everyone.

I have the full plugin working; or at least so I thought until one of the test-users moved the "open" folder inside the asset-source trough the CP.

Suddenly the "open" folder (and it's contents) were no longer displayed anywhere.

I was fetching this folder based on it its ID.

Why you should not rely on folder-ids in Craft

Basically - folder-IDs are dynamic, which means that you cannot safely look up a folder by ID!

Let's do a little experiment.

Create an asset-source named My assets, and under it create two folders: Test and Test2

Now - if you look at your craft_assetfolders database-table, you'll see something akin to:

ID - parentId - sourceId - name        - path
77 - NULL     - 4        - "My-assets" -
78 - 77       - 4        - "Test"      - "Test/"
79 - 77       - 4        - "Test2"     - "Test2/"

Note that id, parentId and sourceId might be different numbers in your example - they depend on how much your craft_assetfolders database-table contained before you started this example.

So far this all makes perfect sense - until you move a folder! Per example, drag and drop Test into Test2, then reload the view of your database-table

It will now read

ID - parentId - sourceId - name        - path
77 - NULL     - 4        - "My-assets" -
79 - 77       - 4        - "Test2"     - "Test2/"
80 - 79       - 4        - "Test"      - "Test2/Test/"

What happened to id 78? It's gone! However the folder Test still exists, it still contains all of its assets etc - it just has a new ID.

Now - for the sake of experimenting, let us drag and drop Test back to the root of our asset-source and reload our view of the database-table

ID - parentId - sourceId - name        - path
77 - NULL     - 4        - "My-assets" -
79 - 77       - 4        - "Test2"     - "Test2/"
81 - 77       - 4        - "Test"      - "Test/"

Basically - whenever you move an asset-folder, rather than simply update the path and parentId values of the associated database-row, the old row is deleted and a new one is created.

Summa summarium - having a plugin or template reference a folder by its ID is hardly safe!

What other options do we have?

Well, in addition to ID folders also have a UID. But, since that is set on row creation, that also changes when a folder is moved. So that's another no-go.

We could look it up by name - but names can be changed, so that's as unreliable as looking it up by ID (or UID).

Even if you were to write up a plugin-setting that allows you to pick the desired folder, that would - given that you move (or - if your plugin stores name rather than ID - rename) the folder - contain a null-reference.

So how can we - safely - identify a single asset-folder in a plugin, and know that it will always point to said folder and subsequently its contents?


texts: Pushing additional key values without overwriting existing key values in an array

texts:
For an existing key in an associative array, I'm trying to push a new value to it without overwriting the existing values in the key. I've tried this:

{% set myArray = {
    myKey: [
        'value1',
    ]
} %}
{% set myArray = myArray|merge({key: 'value2'}) %}

But this returns [ 'myKey' : 'value2']. I'm trying to get it to return [ 'myKey' : [ 0 => 'value1', 1 => 'value2'].


texts: If one wished to manually update for any reason, would one need to change anything outside of the the app folder, or be concerned with anything else?


texts: What is the best way to create breadcrumbs based on a structure?

texts:
How do you create breadcrumbs based on a structure?

My structure:

Parent

Child (active)
Other Child

Child

My url:

site.com/parent/child

So my breadcrumb need to be:

home (url) / parent (url) / child


texts:
I'm trying to figure out how to set the size of a marker on a map.

{% set options = {
  zoom: 6,
  markerOptions: {
    icon: 'https://www.mysite.com/images/map/marker.png',
    scaledSize: 'new google.maps.Size(20,20)'
  },
} %}

It pulls in my marker file correctly, but I don't know what the correct option is to make it scale.

It's a 40px square image, but I want it to show at 20px, so it doesn't look like garbage on a retina screen.

Help?


texts: Users not fully deleting from the database

texts:
From the admin, if I delete a user they disappear from the admin list but not from the users database table.
Looking through the code I can see UsersService.php has a function deleteUser which calls the deleteElementById from ElementsService.php - but it does not seem to actually remove the user from the main users table at all.
The version of craft in use has recently been updated to 2.9.2 following the Craft CMS guide and I've read there maybe Foreign Key issues in the database, but the fixes (plugins) seem to only be for Craft 3, and we are unable to upgrade at this time.
Also looked at > Users not being deleted from the craft_users table?
But as this did not have a full answer and is not a fix for the CMS side of things it's not viable.
How can I determine 1) where the issue is, and 2) how to resolve it?


texts: How to improve search performance on front-end?

texts:
I am trying to improve the performance of our site search. I'm wondering if there is anything I can implement that may speed things up. Currently we have a search being sent to a results page. In the results page we have this call to the database.

{% set entries = craft.entries.search(query).order('score') %}

query is returned from the q parameter in the url.

We are using a matrix field for all the main content blocks on the site. This field has 10 block types with a max of 7 fields in each. This is used on all entries across the site.

Looking at the profiler after running a query on a phrase that is very popular across the site it takes around 11s and queries the db 500+ times.

Any suggestions how we may reduce this time down? Or is this just a disadvantage of using matrix fields?


texts: Apply shipping without the shipping screen

texts:
Folks:

All the products in the store I am working have only one shipping method (ground). It seems redundant to have people go through the shipping screen since there is only one shipping option. Is there a way to just apply the default shipping for the product(s) based on the address they enter rather than going through the shipping screen?


texts: Translate filter and nested vocabulary properties

texts:
Is it possible to use the translate filter in order to get nested vocabulary entries? For example having a vocabulary file like this:

<?php

return [
    'login'             => 'Einloggen',
    'registration'      => 'Anmeldung',
    'forms'             => [
      'email'                => 'Email',
      'password'             => 'Passwort',
    ]
];

I would like to get the vocabulary properties in the template in the following way:

<p>{{ 'forms.email' | t }}</p>

Thanks


texts: Possible to Directly access related records (Laravel ORM style)?

texts:
This post may scream ignorance (Still delving into the plugin world). I'm coming from a background using mostly laravel for PHP application development and building a few plugins now on Craft has felt a bit verbose to access related objects. Is there any "nice" way to allow something like the following in Craft?

$phone = User::find(1)->phone;

or in terms of craft plugins, just include related data in the model itself instead of having dozens of findXbyId methods littering the code?

related: populateModel usage with eager loading related records

Any generic solutions?

Thanks!


texts:
I'm trying to crawl a site, I've tried using Screaming Frog and https://www.internetmarketingninjas.com/seo-tools/google-sitemap-generator/ and both return the same results when I try a crawl.  It finds the home page, but it then will give 404's for all the links it finds on the page.  If I got to the site manually I don't get 404's.

I'm new to Craft CMS so I don't know much (yet).  Inherited this site not too long ago.

Site is: https://highparknaturecentre.com/

In addition, I also noticed that If I go to https://highparknaturecentre.com/about the server returns http status 404 but returns the body content.  Could this be a server issue?


texts: Include with -- variable does not exist error

texts:
New guy here. Can someone explain what the proper way to pass a variable into an include? I'm using this:

{% include "singlepage" with { currentPage:'leaders' } %}

.. and I'm getting a Variable "currentPage" does not exist error.

In short, I have a template that I want to use for my singles pages, but I need to set a couple of variables for the template to use. So, I have a template for each single that simply sets the current page and then includes the single page template. Is this a good approach?

Thanks for any help.


texts: How do I redirect to a corresponding route when user switches languages?

texts:
I'm working on a multilingual site with english and spanish locales. I've built persistent switcher that resides in the site footer. When users click it, it redirects to a corresponding entry in the other locale if one exists and the homepage if one does not.

The problem is that I have a handful of pages on my site that aren't entries: they are routes that are tied to particular templates. For example:

news-events/tags

Is the route for a template that lists all tags in use in my news section, and:

noticias-eventos/tags

would be the corresponding route on the spanish site.

I'd like to be able to check if the current uri is covered by a route and if so, whether there is a corresponding route in the other locale. If so, I'd redirect to that and if not, back to the homepage as per usual.

But from what I can see, routes are not localizable and exist independently of each other. Am I wrong? How would I go about this?


texts: How to define template routes for a custom element type

texts:
So I'm working on a prototyping plugin that has its own element type for pages.  My hope was to have a single _page.html template and much like entries or categories be able to tell Craft to map the routes for all the elements URIs to that template?

But not having much luck figuring out how to do that?

I have URIs saving with my elements but how do I note which template to load?

I assume it has something to do with registering routes but I'm not exactly sure where to start?


texts: Same shipping rule name in different methods not allowed?

texts:
We are setting up shipping methods and rules as follows:

Methods: FedEx Standard, FedEx Priority, FedEx Overnight

For each method we wanted to add the following rules: US, Canada, International

However, when trying to add another rule for another Shipping Method, we get this error:

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'Canada' for key 'craft_commerce_shippingrules_name_unq_idx'

I assume we cannot have duplicate rule names across different methods? If so, this seems odd. Of course we can make each rule have a unique name (ex. US Standard, US Prioriy, etc) but it seems like unnecessary complication. Is that our only option?


texts: Can structure entries have their own entries?

texts:
I have a bunch of categories within a section on my website, but I want each category item within that section to be able to have an additional slug. For example:

mywebsite.com/categories/category/information (information being the additional slug)

Is this possible with Craft?


texts: I am trying to fetch the content from an event onEntrySave but I don't know how to access the entry's properties from the event. So far I have got the event handler working I would just like to fetch the data, any ideas?


texts:
i have created my first plugin and have hit a bit of a wall... its a plugin with a custom element type, i have it creating its own database table (migrations/install.php) and i have the form displaying, and the bit i am struggling with is the saving bit. I build a new element type based on the form details, then do a Craft::$app->getElements()->saveElement($song); ($song is my element type) , i keep getting a getSection method missing error from my Song element type, but i dont have a sectionId, or need a section for this as it is stored entirely in its own table, what have i not understood about creating and saving a custom element type?
Is there a demo plugin or some example i can learn from?
This is my controller
new SongElementType();
$SongElementType->name = Craft::$app->request->getParam('name', $SongElementType->name);
$SongElementType->band = Craft::$app->request->getParam('band', $SongElementType->band);

then i call save that is in my service from my controller like so:
songscatalogue::getInstance()->SongsService->saveSong($SongElementType)

            $this->trigger(self::EVENT_SONG_SAVED_BEFORE, new SongEvent([
                'song' => $song,
                'isNew' => $isNew,
            ]));

            $success = Craft::$app->getElements()->saveElement($song);

            $this->trigger(self::EVENT_SONG_SAVED_AFTER, new SongEvent([
                'song' => $song,
                'isNew' => $isNew,
            ]));

but i get this error:
Calling unknown method: robsplugin\songscatalogue\elements\Song::getSection()

where am i going wrong?


texts: Search for href parameter in rich text field

texts:
I'm trying to find using craft search "bitly" urls in body rich-text field in articles. It's for generation of list of popular articles.
So if query is a link (like "http://bit.ly/1eZFQMY") search doesn't find anything.

Tried "fuzzy" search and all methods listed on craft search page.


texts: Combining custom field filters on craft.entries

texts:
I'm building a book store which filters entries based on GET variables. For the most part, this is working well just merging in various filters to a params variable and then passing craft.entries(params).

The tricky bit is that each book can have an ebook price and a paperback price.

If the books are being filtered to a certain format, then I just do this:

{% if 'ebook' in formats %}
    {% set params = params|merge({ 'ebookRrp' : 'and, > '~price_from~', < '~price_to }) %}
{% endif %}
{% if 'pback' in formats %}
    {% set params = params|merge({ 'paperbackRrp' : 'and, > '~price_from~', < '~price_to }) %}
{% endif %}

That works well for an individual format, but if no format is selected it becomes too specific.

It seems like I need to do something like the following, but this doesn't seem to have any effect on what is returned:

{% set params = params|merge(['or',
    { 'ebookRrp' : 'and, > '~price_from~', < '~price_to },
    { 'paperbackRrp' : 'and, > '~price_from~', < '~price_to }
]) %}

Any ideas?

--- Update with full code: ---

{# Prep the entries params #}
{% set params = {
    section: 'books',
    with: [
        'bookAuthor',
        'booksImage',
    ]
} %}

{# Prep the relatedTo params #}
{% set relatedToParams = ['and'] %}

{# need to do a bunch of checks here and combine them into one relatedto query #}

{% if craft.request.getParam('author') %}
    {% set relatedToParams = relatedToParams|merge([{
        targetElement: craft.request.getParam('author'),
        field: 'bookAuthor'
    }]) %}
{% endif %}

{% if entry.section.handle == 'collections' %}
    {% set relatedToParams = relatedToParams|merge([{
        sourceElement: entry
    }]) %}
{% endif %}

{% if craft.request.getParam('genre') %}
    {% set relatedToParams = relatedToParams|merge([{
        targetElement: ['and']|merge(craft.request.getParam('genre')),
        field: 'genre'
    }]) %}
{% endif %}

{# Merge in the relatedTo params if they exist #}
{% if relatedToParams|length > 1 %}
    {% set params = params|merge({ 'relatedTo' : relatedToParams }) %}
{% endif %}

{% set maxPrice = 10000 %} {# temp high number before working out highest value #}
{% set price_from = craft.request.getParam('price_from') ?? 0 %}
{% set price_to = craft.request.getParam('price_to') ?? maxPrice %}

{% set formats = craft.request.getParam('format') ?? null %}
{% if 'ebook' in formats %}
    {% set params = params|merge({ 'isEbook' : 1 }) %}
    {% set params = params|merge({ 'ebookRrp' : 'and, > '~price_from~', < '~price_to }) %}
{% endif %}
{% if 'pback' in formats %}
    {% set params = params|merge({ 'isPaperback' : 1 }) %}
    {% set params = params|merge({ 'paperbackRrp' : 'and, > '~price_from~', < '~price_to }) %}
{% endif %}

{#
{% if formats is null %}
    somehow filter price for both formats as an or?
    This doesn't work:
    {% set params = params|merge(['or',
        { 'ebookRrp' : 'and, > '~price_from~', < '~price_to },
        { 'paperbackRrp' : 'and, > '~price_from~', < '~price_to }
    ]) %}
{% endif %}
#}

{# Finally get the relevant books #}
{% set books = craft.entries(params) %}


texts:
I am trying to set up a form with checkboxes that allows users to filter entries by selecting multiple categories, but I am not quite getting it right.

Currently this is my form:

{% set subcategoryParam = craft.request.getParam('subcategory') %}
{% set subcategories = craft.categories.group('partnerAreas').find() %}

<form action="{{ craft.request.url }}">

  {% for subcategory in subcategories %}
    <input type="checkbox" value="{{ subcategory.slug }}" id="{{ subcategory.slug }}" name="subcategory" {{ subcategory.slug in subcategoryParam ? 'checked'}}>
    <label class="label__checkbox" for="{{ subcategory.slug }}">
      {{ subcategory.title }}
    </label>
  {% endfor %}

  <button type="submit">
    Search
  </button>
</form>

Submitting this form gets me URL query strings like this:

?subcategory=sourcing-local-products&subcategory=communication

When I am using craft.request.getParam('subcategory'), only the last selected subcategory gets picked up (as you would expect).

I've tried setting the name on the checkbox field to subcategory[], but that gets me an array to string conversion template error and the URL query string then looks like this:

?subcategory%5B%5D=sourcing-local-products&subcategory%5B%5D=communication

What do I need to do to get a comma separated list for the subcategory parameter like this:

?subcategory=sourcing-local-products,communication

And once that is working, how do I then get all the entries that have any of the selected categories assigned via a Matrix field?

This is what I've currently got:

{% set subcategoryParam = craft.request.getParam('subcategory') %}
{% set selectedSubcategories = craft.categories.slug(subcategoryParam) %}
{% set entries = craft.entries({
  section: listingType,
  relatedTo: {
    targetElement: selectedSubcategories,
    field: 'involvementAreas.area'
  }
}) %}

But I imagine that's not quite right if I want to account for an array of selected categories...


texts: Date filtering returning wrong results - timezone issue?

texts:
I'm running into an issue where incorrect results are being returned when filtering Craft Commerce orders by date in a template. Can anyone help? I cannot figure out what is going on.

FACTS:

Craft install is using America/Denver for timezone.
I'm passing dates via the query string with this format: YYYY-mm-dd
PHP version is 7.1.
Problem timestamp from the DB is (2017-11-10 00:14:04)... this doesn't match the screenshot below because I've been fiddling with dates.

This is my reduced code:

{% set start = "2017-11-09" | date('Y-m-d 00:00:00', 'America/Denver')  %}
{% set end = "2017-11-09" | date('Y-m-d 23:59:59', 'America/Denver') %}
{% set orders = craft.commerce.orders.dateOrdered('and', '>= ' ~ start, '<= ' ~ end).find() %}

{% for order in orders %}
    {{ order.dateOrdered | date('Y-m-d H:i:s e') }}<br/>
{% endfor %}

This is the returned data with the incorrect entry:


texts: User Login issue for users, its only allowing admin to login from front-end its buffering with username or password is wrong for other users

texts: i used user login form from craft document https://docs.craftcms.com/v3/dev/examples/login-form.html


texts: LJ Dynamic Fields - Only Seeing Latest 100 entries

texts:
I am currently creating various component entries (under channels). Once created I can then add that specific component to structure (know on my site as a work page).

On the work page I have a dynamic field (see https://github.com/lewisjenkins/craft-dynamic-fields) that allows a user to scroll through these already created component entries in a dropdown list style. That drop down is a dynamic dropdown generated through LJ dynamic fields with the following code in the CMS.

{% include '_dynamicfields/sections' ignore missing %}

From there the included file is as follows...

{% for channel in craft.entries.section('components') %}
   { "value":"{{ channel.id }}" , "label":"{{ channel | raw }}" }
   {% if not loop.last %},{% endif %}
{% endfor %}

Unfortunately as of late I'm only seeing the latest 100 entries. I haven't seen any reference in either craft CMS documentation or the LJ Dynamic fields documentation.


texts: Auto enable/install plugin through config

texts: Is it possible to auto enable/install a plugin through config (or another way) rather than having to do this through the database?


texts:
I have created an entry that requires users to be logged into to see it. This was just a minor request from our client and we didn't want to spend a lot of time setting up login forms etc.

Therefore I have just added {% requireLogin %} to the top of the entry's Twig file. This works great, so far so good.

The problem comes however when a user visits the URL for that page:

www.foo.com/lorem

They are re-directed to the Craft login, as expected, but once they successfully login, instead of being re-directed back to the page, they are instead taken to the Craft admin dashboard, with the pages' slug at the end. So:

www.foo.com/admin/lorem

Can anyone shed some light as to what is going on here? How can I make it so once users are loged in, they are re-directed back to the page? I've seen Craft has a postLoginRedirect config, but I'm guessing this can't be set on a per-page basis.


texts: Check if an order has been refunded in a template?

texts:
What’s the best way to check if an order has been refunded in a template?

For example, you may want to:

Add a message to the order/invoice template if a refund has been successful.
Determine the status of the refund; perhaps displaying a different message if the status is not yet success.
Show the time of refund.


texts: Hiding enclosing div if all matrix block fields are empty (although they do exist because of another language)

texts:
I have an entry with matrix fields. If I add blocks in the main language, but its fields only contain data in one language, the block query (the for loop) still finds these empty fields since they do contain data in the other language. It is easy not to display the fields and their enclosing divs with an if statement.
However, if all the fields are empty, I don't even want to display the enclosing/parent div/title of all the blocks; and also do not want it to show on the page menu. I could loop through all of the blocks each time to find out if all the fields are empty — and then not display the enclosing title – but is there an easier way?
{% set referenceBlocks = entry.references.all() %}
{% if referenceBlocks|length %}

{{ "References"|t }}

            {% for block in referenceBlocks %}
                {% if block.referenceLink|length or block.referenceText|length or block.referenceSource|length %}

                    {% if block.referenceLink|length %}

                    {% endif %}

                        {{ block.referenceText }}
                        {{ block.referenceSource }}

                    {{ block.referenceLink|length ? "" }}
                    {% endif %}

                {% endif %}
            {% endfor %}

{% endif %}

So I don't want to show the elements outside the for loop if all the blocks and fields in those blocks are empty. The first if statement only works when there are no matrix block in ALL languages, but when there are some in the main language but not in the other one, it will display the parent div and title.


texts:
In my cart on Commerce, I only get to have one item at a time. If I try to add another item, it replaces the item that was already in the cart.

I have used {% set cart = craft.commerce.getCart() %} and the for item in cart.lineItem to loop through the items, to no avail.


texts: Craft 3 / Sprout Forms Bootstrap field classes

texts:
How can I add a css class directly to the INPUT tag generated by {{ input|raw }} from the accessible template of the sprout form plugin? I do not wish to add the class to a surrounding div.

I ended up looping through the form fields, which works almost but lacks the field types:

This is my field.html. It seems I cant get the field.type thus it defaults to text for all fields.

{%- do craft.sproutForms.addFieldVariables(_context) -%}

{%- set label            = field.name ?? null %}
{%- set name             = field.handle ?? null %}
{%- set type             = field.type ?? 'text' %}
{%- set required         = field.required is defined and field.required ? true : false %}

{%- set id               = renderingOptions.id ?? name %}
{%- set class            = renderingOptions.class ?? name %}
{%- set value            = entry is not empty ? entry.getFieldValue(name) : null %}
{%- set errors           = entry is not empty ? entry.getErrors(name) : null %}

{%- namespace field.getNamespace() -%}
    {%- if field.isPlainInput() -%}

        {{ input|raw }}

    {%- else %}

        {% if label -%}

                {% if label -%}

                            {{- label|raw|t('sprout-forms') -}}

                {%- endif -%}

        {% endif -%}

                <input type="{{type}}" name="{{name}}" class="{{class}}" {%- if required %} required{% endif -%}>

        {% include "errors" with {
            errors: errors,
            name: name
        } %}

    {%- endif -%}
{%- endnamespace -%}

In the tab.html which calls uses the field.html:

{%- for tab in tabs -%}

    {%- set layoutFields = tab.getFields() %}

    {% set fieldOptions = {
        "class": "form-control",
        "errorClass": "has-error",
        "data": {
            "hidden": "false",
        }
    } %}

    {% for field in layoutFields -%}
        {{- craft.sproutForms.displayField(form, field, fieldOptions) }}
    {%- endfor %}

{%- endfor -%}

This is all based on the default "accessible" template from the plugin. While I know I could put the fields manually in the template, I would prefer to learn how this is actually done "nicely". Thanks!


texts:
I want to reroute old html pages.
The format is:  /title-35-of-page.863.en.html
I want to route every adresse with .html at the end also get the lang and id part of the address for further handling, but have problems with the dots.
This are some versions that i tried, but none of them worked.

'(?P<title>[-\w\d]+).html' => array('action' => 'jpk/rerouteOldPages')
'(?P<title>[-\w\d]+)html' => array('action' => 'jpk/rerouteOldPages')
'(?P<title>[-\w\d]+)\.(?P<papayaId>\d+)\.(?P<language>\[a-z]{2})\.html' => array('action' => 'jpk/rerouteOldPages')


texts: Freeform user account creation form: handling prior user account exists

texts:
This is more or less a duplicate of a support ticket raised with Solspace. I’ve no doubt they will provide an answer but if anyone else has one feel free to pitch in.

I'm using Freeform forms to register user accounts into a specific user group per form. It could arise that a would-be user is already registered, so I need to handle them trying to create a user account for an email address already in the system.
It appears that form.hasErrors prevents a duplicate account being created but doesn’t return any message that that’s what has happened within the form.errors loop.
I'm imagining I could do something like the following to assume that a prior user account is the issue, but it would be good if there was something more systematically robust:
{% if form.hasErrors %}
    {% if form.errors|length %}
        {# Report errors #}
    {% else %}
        {# Assume that an existing user account is the issue #}
    {% endif %}
{% endif %}

Is there a better way?


texts: Is there a way to use the includeCssFile tag to include a css file for print media?

texts: {% includeCssFile %} can be used to add "regular" css files in the head tag. Is it possible to use this tag for print media?


texts:
We want to add a little more structure to our templates directory by adding folders to group templates files.

For example:

templates
--_macros
--_views
--_layouts

In general this works fine but we encountered a problem with the index pages of sections.
All pages are grouped in the views directory, so in views we could have a folder "articles" and within that a file "_entry.twig" and "index.twig".

For the entry to work we change the template path of the section in the backend.
But there is no place to this for the index file.

Anybody an idea how best to handel this?
Is there a way to tell craft to also look in de _views folder?


texts:
When is it advisable or prudent to use without rather than a conditional statement to exclude something, eg a set of entries, based on one parameter?

For example, say I have real towns and fictional Towns that are listed on a related Regional page. These Towns are sorted real/fictional by a toggle field -- 0 for real, 1 for fictional.

The fictional towns are used elsewhere and should not be listed on any Regional page. In this case, should I be using if (see below) or without?

Here is how I am doing it right now in my Regional template:

{% if town.townFictional == 0 %}
    <li>{{town.link}}</li>
{% endif %}

This is working fine, but I came across this question where using without was suggested.

Is without preferred in my case, and if so how do I use it? Here is my towns variable:

{% set towns = craft.entries.section('towns').relatedTo(counties) %}


texts: Freeform: How do you change a name of a form that you have cloned?

texts:
I clone the form.

Click on the cloned form from the list.

Change handle.

Click into name field and start to type and the save button disappears.

Craft 3.4.02


texts: Mandatory order fields in Craft Commerce 2

texts:
Ist it possible to add validation rules for Carts/Orders? I need to check whether there is at least one list item added to the cart before payment is initiated.

Unlike addresses (Address::EVENT_REGISTER_ADDRESS_VALIDATION_RULES) there seems not to be an event for manipulating rules.

I’d prefer a server-side solution.


texts: Is there a way to add custom aspect ratios in the image editor?

texts: We'd like to add a custom aspect ratio to the list of aspect aspect ratios in the image editor so our client doesn't have to look it up to remember each time. Is this possible?


texts:
In the plugin I'm creating I've got a form that has inputs which are set as disabled if they are overridden in a conifg file.

The problem that is occurring is that disabled class is added to the input but the disabled attribute is not.

This is what I've got:

{% import "_includes/forms" as forms %}
{% set configSettings = craft.config.get('settings', 'myPlugin') %}
{% for paramKey, paramValue in array %}
       {% set disabled = (configSettings[paramKey] is defined) %}
       {# other variable sets here #}
       {{ forms.textField({
            label: paramLabel,
            name: inputName,
            value : paramValue,
            disabled: disabled,
            required: required
            }) }}

{% endfor %}

When I navigate to the page, the input field is greyed out but I can still input data to the input field.

This is the HTML that I see when I inspect the element:

<input class="text disabled fullwidth" type="text" name="settings[abcd]" value="abc" autocomplete="off">

I tried disabled: true and disabled: 1 in the code above to test and the same html is returned.


texts: Shouldn't the asset "View source" privilege limit access to an asset source in the selection modal?

texts:
I've created an asset source: 'restricted uploads' and a user: 'Jim', who is a member of the 'staff' User Group.

Neither 'Jim' or the 'staff' group have any privileges for the 'restricted uploads' source.

If Jim logs into the admin panel and goes to 'Assets' in the sidebar, he can't see the "restricted uploads" source (as expected).

However, if Jim opens a file selection modal which includes access to the "restricted upload" source he can see "restricted uploads" listed in the modal source sidebar, and can select files from that folder.

Shouldn't Jim's missing asset "View source" privilege prevent him from being able to see the files in the "restricted upload" folder?


texts: Is there any Booking/Reservation system for Craft 3?

texts:
I couldn't find any booking/reservation system for Craft. Is there any? I found questions from 2014, so things could change.

Maybe there is community-approved booking/reservation service that is commonly used with Craft, but it doesn't have the native plugin?

Or maybe it can be done within Craft core? I'm open to ideas.

If you saw a Craft project with booking/reservations feel free to comment it here