texts: How to redirect site root to preferred language in multi-language site?

texts:
I followed the Craft directions for setting up a localized site. In the fifth step I followed the first example for setting up my folder structure. In my case the languages I'm working with are French and Arabic.

craft/
public_html/
   fr/                 --> example.com/fr/ (french)
      .htaccess
      index.php
   ar/                 --> example.com/ar/ (arabic)
      .htaccess
      index.php

The primary language for the site is French, what is the best way to redirect so that if a visitor comes to the root of the site www.example.com they will be redirected to the French version at www.example.com/fr/ ?

Should I use a .htaccess file in main public_html directory of the site, should I use the dynamic routes in Craft, or is there some other, better, way?


texts: Is there a way to override the formatting template used when rendering a Freeform form?

texts:
I have a form that can appear either in the regular body flow of a page, or in a sidebar-esque box. When rendering normally, I want it to use the formatting template selected in the backend, but when I render it in the sidebar box, I want it to use a different formatting template.

I know there's manual overrides for rendering everything exactly the way you want in a custom fashion, but I'm looking for something more like this:

{{ craft.freeform.form(entry.form.handle).render( { template: 'specialtyTemplateHandle' } ) }}

Is something like that possible?

We're using Freeform 3.6.2 Pro.


texts:
I noticed that variants can have their own URL when i outputted URL of line item in the cart. Url looks something like that:
http://localhost/test/web/test-prod?variant=27

Is there any way to change variant keyword in URL to something else?
When we want to display specific variant on product page, we need to perform specific element query based on variant param ourselves, yes? Because only product variable is injected into template.


texts: Order entries by related "Year" category and paginate?

texts:
I have a section called Library, and a category group called libraryYears. The categories in that group are just years (2021, 2020, 2019...)
Each entry in the Library is related to a year in the libraryYears via a related Entries field called theYear.
I want to list all Library entries in order of the related year, so 2021 entries first, followed by 2020 entries, and so on. I don't need year headings, I just need them to be in order of year. But I also want to paginate them so there are only 10 per page.
I tried toying around with the group filter, but can't get it going with pagination.


texts:
I am trying to learn Craft and since I don't know how to create a form with one text area and a button. On the button press, I want to redirect to another html found in the template directory, I am messing around with Craft's contact form to get the desired functionality. I had this code which was working fine:

{% macro errorList(errors) %}
    {% if errors %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

<form method="post" action="" accept-charset="UTF-8">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="contact-form/send">
    {{ redirectInput('contact/thanks.html?from={fromName}') }}

Your Name

    <input id="from-name" type="text" name="fromName" value="{{ message.fromName ?? '' }}">
    {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

Your Email

    <input id="from-email" type="email" name="fromEmail" value="{{ message.fromEmail ?? '' }}">
    {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

Subject

    <input id="subject" type="text" name="subject" value="{{ message.subject ?? '' }}">
    {{ message is defined and message ? errorList(message.getErrors('subject')) }}

Message

    <textarea rows="10" cols="40" id="message" name="message">{{ message.message ?? '' }}</textarea>
    {{ message is defined and message ? errorList(message.getErrors('message')) }}

    <input type="submit" value="Send">
</form>

What I did to only have one textbox and a button, I removed a lot of code:

<form method="post" action="" accept-charset="UTF-8">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="contact-form/send">
    {{ redirectInput('contact/thanks.html?from={fromName}') }}

From

    <input id="from-name" type="text" name="fromName" value="{{ message.fromName ?? '' }}">
    <input type="submit" value="Send">
</form>

My thanks.html has the following code:

Thank you {{ craft.app.request.getQueryParam('from') }} will contact you soon

Before changing the code, the redirect worked fine and I was getting the 'from' replaced after the 'Thank you'. After I changed the code, on pressing the button the page refreshes but nothing happens and it doesn't get redirected to the thanks.html page. Please help.

Also, kindly direct me to the documentation which tells in detail about front end development in Craft as the official documentation is very vague (or seems vague to me :( )


texts: Find Entries with Multiple Matches in a Single Field

texts:
I have entries in a channel called "shorts".
Each of those entries has a field called "size" that can be a value of small, medium or large.

I have created a form where I want users to be able to filter entries where the field could match small and medium (for example). I am using checkboxes on my front end form and a drop down field on the Craft admin form.

The URL I'm utilizing looks like this: http://domain.com/search/results?size=small&size=medium

But only the mediums are being displayed.

This is my code. I am not sure how to join the two together so smalls and mediums are displayed:

{% set params = {section: 'shorts', limit: null}
{% if craft.request.getParam('size') %}
{% set params = params|merge({'size':size}) %}
{% endif %}


texts: How to test if a address is on a list before it gets added? (MailChimp Subscribe Plugin)

texts:
I’m working on implementing this plugin: https://github.com/aelvan/mailchimp-subscribe-craft
I’m wondering: How can I accomplish to test if an address is on the list before it gets added? And on top of that return different results: you’ve already subscribed/you were added to the list.

That's my current status

{% if mailchimpSubscribe is defined %}
    {% if (not mailchimpSubscribe.success) and (mailchimpSubscribe.errorCode) %}
        {# display error message #}
    {% elseif craft.mailchimpSubscribe.checkIfSubscribed(mailchimpSubscribe.values.email, 'list-ID') %}
        {# display that the address is already added #}
    {% elseif (mailchimpSubscribe.success) %}
        {# display success message #}
    {% endif %}
{% else %}
    {# display default form #}
{% endif %}

Logically there can only be an error or already added output and no simple success because of if the form gets submitted the address is already submitted when the page reloads.

So, my question: How can I accomplish to test if an address is on the list before it gets added?


texts: List most recent items combined from Channel and Structure sections

texts:
If we pass through an array of Channels & Structure sections we find that Channels entries tend to be listed first. So the first 15 will comprise of ChannelOne and ChannelTwo and then start listing the Structure section.

{% set homepageEntries = craft.entries({
    section: ['channelOne','StructureOne',channelTwo','StructureTwo'],
    limit: 15
}) %}

{% for item in homepageEntries %}
{{ item.title }}
{% endfor %}

All we want is a list of the 15 most recent items from a number of sections.

It does not look to be as straightforward as it seems. Creating multiple arrays of ids and merging still seems to produce the same results.


texts: Implementing Read-Replica (slave) database connections

texts:
I'm thinking about ways to implement this but don't instinctively know the best route in Craft.

Our infrastructure is in AWS and, due to other applications, we have access to a read-replica DB instance alongside the master instance. I'm wondering about how to write an extension/plugin that would direct all SELECT requests to either the master OR the slave, and all INSERT / UPDATE / DELETE requests to the master only.

What are some possible paths for incorporating this?


texts: How can I sum value across entries assigned to a category for a given year across multiple years?

texts:
I have a category group named country.   Each entry in posts is assigned to a country and a dollar value.  dollar value is a field, NOT a table cell.

On a country's given page (i.e., a category page), I want to sum the total value across all entries assigned to a given country by year (date posted) across all years for which there are entries.

Help...


texts: How can I iterate more than 100 blocks in a matrix field for loop?

texts:
I am looping through a matrix field and it appears to stop looping when the index reaches 100 but I have more than 100 blocks here. How can I loop through the remaining blocks?

{% for block in entry.myMatrixField %}
    {{ loop.index }}
{% endfor %}


texts:
I try to build a complete sentence based on tags as follows:

This is a sentence with tag1, tag2 and tag3.

My code is:

{% set topics = entry.topics.first %}

{% for topic in entry.topics.offset(1) %}
    {% if topic != entry.topics.last %}
       {% set topics = topics ~ ', ' ~ topic %}
    {% endif %}
{% endfor %}

This is a sentence with {{ topics }} and {{ entry.topics.last }}.

My problem is that the if clause does not work. The results is always:

This is a sentence with tag1, tag2, tag3 and tag3.


texts:
I am trying to figure out how to check if a visitor is not logged in so that I can show the correct button. E.g

{% if craft.session.isLoggedIn %}
    Logout
{% else %}
    {% craft.session.isGuest %}
    Client/a>
{% endif %}

What is the best method to display a "sign in" button for a visitor that takes them to a login page and then once logged in, show "Logout"?


texts:
I have to develop a website under Craft CMS 2 and going to Locale Options I see I can add a language, but I need to use a language that is not included in the official codes for the representation of names of languages.
There's a cultural and important question here for my client, because Valencian language is included into Catalan language under the code "ca_ES" but is frowned upon here. So, I want to use other code, for example, "va_ES". How can I do this under Craft CMS 2?
Thanks a lot.


texts: cartCookieDuration and purgeInactiveCartsDuration config settings

texts: How do I set the cartCookieDuration and purgeInactiveCartsDuration for only 24 hours?


texts: How do I add more account fields for user registration?

texts: I'm using the default form found in the Craft CMS docs, however I'd like to create more fields other than username, password and email. How would I add more custom fields to capture user data like address, phone number etc?


texts: How do you use the Venti Calendar plugin with the Element API plugin?

texts: I want an endpoint in the Element API plugin that shows the last event entries from the Venti Calendar plugin. The Element API guide tells that's possible to use the plugin with custom element types. But how?


texts: How to order by related entry type field

texts:
Two sections:

1) Products

2) Authors

The "Products" section pulls the author name from the "Authors" section through an entries type field.

I'd like to order the products first by authors (alphabetically), then by title.

Craft does not accept the author field handle in the

.order('authors','title').

Here is the "Products" template code:

{% set entries = craft.commerce.products.type('Products').relatedTo(category) %}
{% for entry in entries.order('author','title').limit(0) %}

What is missing?


texts: Showing specific category content as well as ALL

texts:
I have a photography website with just two categories, 'Lifestyle' and 'Food'.

I have two problems:

How to display the content

I have a category group called 'photoCategories' to which I have assigned two categories 'Lifestyle' and 'Food'.  I also have a Category field 'imageCategory'.

At the moment I have two Entries, one for Lifestyle and one for Food and I have linked to the appropriate category in the category field.

I have a 'category' template but I can't figure how to pull the appropriate content based on the URI and how to pull All content (within) the category group for when the user selects All?

My navigation needs to look as follows:

Homepage (Single)
All Images ('images' Channel)
Lifestyle Photos ('images' Channel)
Food Photos ('images' Channel)
About Us (Single)
Contact Us (Single)

Any advice is very much appreciated.

Thanks

Martin


texts: Solspace FreeForm assign notifications recipient in entry

texts: I've got a client who would like to be able to assign a notification recipient for each entry where a form appears. I would imagine that a new form needs to be created for each recipient, but is there a way to take the form handle, add it to an entry then output that form on a page? Or is there a better way to do it?


texts:
Ok so this is part I need help part heads up for others. The back story... I a client messaged me saying that they couldn't save posts anymore for specific entries. I noticed the ones that were having issues were the larger ones. The entries are fairly complex with the supertable plugin. I tried EVERYTHING I could to diagnose the problem, modifying every server setting etc. I realized it worked locally but not remote. I also realized it worked fine on my phone but not my machine. it worked on a co-workers air but not my macbook pro. craziness. I did eventually get it to work but I'm not sure why.

Switching out of DevMode made everything work fine, but that isn't a real acceptable solution for me because I use devMode. I hope anyone struggling with this, sees this but I appeal to some of you more seasoned Craft devs, why the heck is this happening in devMode and only remote on some machines?


texts: Unable to access site after importing DB

texts:
I am installing a repo locally, and everything runs smoothly and I am able to see the site and login to my admin. But when I import my DB then visit my site: I get the error message "Site unavailable".

When I visit my admin area I see the message: "To complete the update, some changes must be made to your database." I click proceed and see the message "Craft couldn’t backup the database. How would you like to proceed?".

I am using Craft 3. But the DB I am importing from uses the older 'craft_' prefix, which I defined in the setup. Am stumped on how to solve this.


texts: How to add Facebook pixel code to my website

texts:
How do I add the html code to the head of my website in Craft CMS?

Do I need to install a plugin, or is there somewhere I can access the code?


texts:
When I create a cpUrl like that:
UrlHelper::cpUrl($this->entry->cpEditUrl)
I get something like that:
https://hegi.test/admin/entries/article/7707-test
But that don't work inside of the browser.
I get an 404 Error:
HTTP 404 – Not Found – yii\web\NotFoundHttpException Entry not found
Do I miss something?
Thanks in advance.
Michael


texts: Commerce 2: Custom product fields not showing up in order

texts:
I've created a dropdown field for my users to select from on each of my products, but if the user was to select an option from the dropdown and click 'add to cart' , it doesn't show up in their order once it's all gone through.

What I currently have on my products page is:

<form method="POST" name="main">
    <input type="hidden" name="action" value="commerce/cart/update-cart">
    <input type="hidden" name="paymentCurrency" value="{{ currency }}">

    {{ redirectInput('cart') }}
    <input type="hidden" name="qty" value="1">
    {{ csrfInput() }}

    {% set max = product.max %}
    {% set i = 0 %}

    <select name="options[max]">
        {% for i in 1..max %}
            <option value="{{ i }}">{{ i }}</option>
        {% endfor %}
    </select>

    {%- for purchasable in product.getVariants() -%}
        {% if purchasable.isAvailable %}
            <input type="hidden" name="purchasables[0][id]" value="{{ purchasable.id }}" />
            <input type="hidden" name="purchasables[0][qty]" value="1" />
        {% endif %}
    {%- endfor -%}

    {%- for purchasable in product.getVariants() -%}
        {{ purchasable|currencySalePrice('' ~ currency ~ '') }}
    {%- endfor -%}

    <input type="submit" value="{{ "Add to cart"|t }}" class="button"/>
</form>

Any reason why 'add to cart' wouldn't update this info and show it in the customers order?


texts:
Craft hasn't done this prior (or maybe I just noticed), but I'm currently battling double slashes in URLs returned from {{ asset.getUrl() }}.

The issue appears when I create an Assets field and set the following settings to that field:

Restrict uploads to a single folder (true)
Upload location: [source:Images] somefolder/somesubfolder

Calling {{ asset.getUrl() }} on an asset from this field returns the following URL:

/uploads/images/somefolder//somesubfolder/image.jpg

Notice that the double slash appears inside the path specified in the field's settings – /uploads/images/ is the source path.

This happens both for Asset fields that are inside Matrix fields, and standalone fields. It also happens regardless if I use named transforms, inline transforms or no transforms (getUrl(false)).

If the source configuration should prove relevant somehow, here's the setup:

I've got an asset source (local folder) called Images configured like this:

File System Path: {imagePath}/
URL: {imageUri}/

{imagePath} and {imageUri} are environment variables, set to $_SERVER['DOCUMENT_ROOT'] . "/uploads/images" and "/uploads/images", respectively.

Not sure if this is a bug or something I do wrong somehow (or maybe it has to do with server configurations?). I can remove the double slashes with Twig, but it's annoying. Why does this happen, and is there anything I can do about it?


texts:
We've had software crawl our site to find SEO issues.
The crawl has found every URL twice, once with a token, once without. Each of the URLs with the token is displaying the same, and with the URL-with-token as canonical, so as far as the crawl is concerned, there are two identical URLs.
It is the same token sequence for each URL.
Is there a way to flush this apparently working token out? Or htaccess to redirect to the token-less URL?


texts: Getting ID of first and last Neo blocks of certain type

texts:
With the below {{ module.type }} outputs 'moduleFAQ' but firstFAQId and lastFAQId don't output anything. Why is that?

{% for module in module.children.all() %}
    {% set firstFAQ = module.type('moduleFaq').one() %}
    {% set firstFAQId = firstFAQ ? firstFAQ.id : null %}
    {% set lastFAQ = module.type('moduleFaq').last() %}
    {% set lastFAQId = lastFAQ ? lastFAQ.id : null %}
    {{ module.type }} / {{ firstFAQ }} / {{ lastFAQ }}
{% endfor %}


texts: Craft 3: query matrixBlocks and eager load its owner?

texts:
Does anybody know if it's possible to load matrixBlock and eager load the entries (=owner) the matrixBlocks belong to in Craft 3?

I tried:

{% set blocks = craft.matrixBlocks.type('eventDate').fieldId(4).with('owner') %}

but this does not work. Leaving out the .with('owner') works perfectly and then access its owner by block.owner.<fieldname>


texts: Override SuperTable reverse related entries limit

texts:
I've got two kinds of channel entries: Bills and Legislators. Legislators have a SuperTable of votes. Each vote is related to one Bill. I want to get all the votes associated with a particular Bill and display them on that Bill's page, but I can't fetch more than 100 items. Here's my current code:

{% set reverseRelatedVotes = craft.supertable.getRelatedElements({
    relatedTo: {
        targetElement: entry,
        field: 'scorecardVotes.bill',
        },
    section: 'legislators'
}).limit(null).order('lastName ASC') %}

limit(10) works as expected, but anything over the standard Craft limit of 100 returns 100. How can I get all the related votes for a given Bill?


texts: How can I output the territories array with craft.i18n?

texts:
I found this code in the Craft documentation:

{% set localeData = craft.i18n.getLocaleData() %}
{% for month in localeData.getMonthNames() %}
    {{ month }}
{% endfor %}

What I need is the whole list of countries (from Ascension Island to Zimbabwe).
I tried .getTerritories() but it doesn't exist:

{% set localeData = craft.i18n.getLocaleData() %}
{% for country in localeData.getTerritories() %}
    {{ country }}
{% endfor %}

Is there any solution?


texts:
Is it possible to provide different possible values per case?

I've tried the following formats without success.

{% case "A" or "B" or "C" %}
  {# run this if case matches A or B or C #}

I saw this done somewhere else so I thought I'd give it a shot

{% case "A" %}
{% case "B" %}
{% case "C" %}
  {# run this if case matches A or B or C #}

From the documentation it doesn't seem like this would be possible but wanted to check just in case. If not, any chance we'll see this sometime in the future?


texts:
I have a Matrix block with 2 types: quotes and text. The first block contains a quote and a text. The second and following ones only contain quotes.

I want the type text to be limited to 1 and the type quotes limited to one at a time displayed randomly.
Can't figure out how?

{% for block in entry.intro %}

    {% if block.type == "quote" %}

{{ block.quote|raw }}

                {{ block.caption }}

    {% elseif block.type =="text" %}

{{ block.column1 }}

{{ block.column2 }}

    {% endif %}

{% endfor %}


texts: Pre-select entry type based on site being edited

texts:
I'd like to change the entry type that's pre-selected when creating a new entry depending on the site that's being edited (doing that with JS).
In control panel, does anyone know how I can trigger the Craft.EntryTypeSwitcher change event? I can detect which site is currently being edited and I can change the value of the Entry Type dropdown, but I don't know how to trigger the event that then reloads the page to get the fields for that entry type. I'm assuming I need something similar to this: https://craftcms.stackexchange.com/a/25828/6516 (it's just that I need to trigger an event and not hook up to it)? Does anyone know how to do this?


texts: Is it possible to have Craft send an email on page load?

texts: I'm very new to this so any guidance is greatly appreciated. I've written a couple of simple plugins that will send an email to admins on new user save and and on new entry creation. What I need to do now is to send a weekly email with all new entries created in the last 7 days to a particular user group. I figured it'd be pretty efficient to set up an online CRON job to hit a site url, and on load of that page, trigger my email plugin. However, I'm not sure how to trigger my plugin on page load. Any suggestions?


texts: How do you modify the entry data before the template is rendered?

texts:
I am using a pattern library which expects a different data structure to what is in entry. Is there a way to parse the entry through a transformer class before the template is rendered?

Currently I have created a Twig function to run: {% set job = single(entry) %} which returns the mapped data for each different entry type.

I would like to hook into Craft to do this before the template is rendered and remove any mapping logic from the templates. Is this possible/practical?


texts:
A simple question with hopefully a simple answer.

How can I make the date picker in the admin area start the week (i.e. each new line) with Mondays rather than Sundays?

I'm sure it will just be a configuration issue. I just can't see where to change it.

Thanks


texts:
I wonder if you can help. I need to make some changes to the text on the bottom part of our home-page but I'm not sure how to. This site was designed for us by another agency and although I have access to the template and the back of it I can't seem to figure out how to edit the text on the footer of the site. help please!
Thanks,
Carolina


texts: How to display the title of a category based on its ID?

texts:
I’m passing the ID of a category to a template via a catId query string (i.e. http://example.com/some/path?catId=10).

How do I display the title of that category?


texts: How save data from form in headless Craft via Vue.js

texts: I have front-end form on Vue.js and Craft CMS for the backend. I need form. And I want to save data from the form in Craft CMS. How to save data from user frontend to backend on Craft CMS?


texts:
the file upload always does not finish and it shows no error alert. Also in the logs there is no error.

I only find an error in the browser debugger on actions/assets/uploadFile . Maybe the error helps:

n.ajaxTransport.k.cors.a.crossDomain.send @ jquery-2.1.4.min.js?d=1436808909:4n.extend.ajax @ jquery-2.1.4.min.js?d=1436808909:4$.widget._onSend.send @ jquery.fileupload.js?d=1436808910:880(anonymous function) @ jquery-2.1.4.min.js?d=1436808909:2n.Callbacks.j @ jquery-2.1.4.min.js?d=1436808909:2n.Callbacks.k.add @ jquery-2.1.4.min.js?d=1436808909:2(anonymous function) @ jquery-2.1.4.min.js?d=1436808909:2n.extend.each @ jquery-2.1.4.min.js?d=1436808909:2(anonymous function) @ jquery-2.1.4.min.js?d=1436808909:2n.extend.Deferred @ jquery-2.1.4.min.js?d=1436808909:2n.extend.Deferred.d.then @ jquery-2.1.4.min.js?d=1436808909:2$.widget._onSend @ jquery.fileupload.js?d=1436808910:924(anonymous function) @ jquery.ui.widget.js?d=1436808910:105$.widget._addConvenienceMethods.data.submit @ jquery.fileupload.js?d=1436808910:648(anonymous function) @ craft.js:13685n.extend.proxy.n.isFunction.f @ jquery-2.1.4.min.js?d=1436808909:2n.Callbacks.j @ jquery-2.1.4.min.js?d=1436808909:2n.Callbacks.k.add @ jquery-2.1.4.min.js?d=1436808909:2Craft.Uploader.Garnish.Base.extend.onFileAdd @ craft.js:13653n.extend.proxy.n.isFunction.f @ jquery-2.1.4.min.js?d=1436808909:2n.event.dispatch @ jquery-2.1.4.min.js?d=1436808909:3n.event.add.r.handle @ jquery-2.1.4.min.js?d=1436808909:3n.event.trigger @ jquery-2.1.4.min.js?d=1436808909:3(anonymous function) @ jquery-2.1.4.min.js?d=1436808909:3n.extend.each @ jquery-2.1.4.min.js?d=1436808909:2n.fn.n.each @ jquery-2.1.4.min.js?d=1436808909:2n.fn.extend.trigger @ jquery-2.1.4.min.js?d=1436808909:3$.Widget._trigger @ jquery.ui.widget.js?d=1436808910:487(anonymous function) @ jquery.fileupload.js?d=1436808910:1008n.extend.each @ jquery-2.1.4.min.js?d=1436808909:2$.widget._onAdd @ jquery.fileupload.js?d=1436808910:1001(anonymous function) @ jquery.ui.widget.js?d=1436808910:105(anonymous function) @ jquery.fileupload.js?d=1436808910:1200n.Callbacks.j @ jquery-2.1.4.min.js?d=1436808909:2n.Callbacks.k.add @ jquery-2.1.4.min.js?d=1436808909:2n.extend.Deferred.d.always @ jquery-2.1.4.min.js?d=1436808909:2$.widget._onChange @ jquery.fileupload.js?d=1436808910:1190(anonymous function) @ jquery.ui.widget.js?d=1436808910:105handlerProxy @ jquery.ui.widget.js?d=1436808910:406n.event.dispatch @ jquery-2.1.4.min.js?d=1436808909:3n.event.add.r.handle @ jquery-2.1.4.min.js?d=1436808909:3

Can anybody help me?


texts:
I have a matrix field with a Super Table block type. Then I have a matrix field as a field within the Super Table block. I am having trouble filtering by block type from within the child matrix field. Is what I am trying to achieve even possible? Any solution would save me from pulling my hair out any further.

Below is the last attempt I made to filter through before posting here:

{% for block in entry.matrixFieldParent %}

    {% if block.type == "superTableBlock" %}

        {% for row in superTableBlock %}

            {% for block in row.superTableBlock %}

                {% switch block.type %}

                    {% case "contentBlock1" %}

                       {{ block.contentField }}

                    {% case "contentBlock2" %}

                       {{ block.contentField }}

                {% endswitch %}

            {% endfor %}

        {% endfor %}

    {% endif %}

{% endfor %}

edited to include if statement previously left out by mistake


texts: Getting the order for categories.lft rgt

texts:
While trying to assign a global CSS class based on the order of the categories based on the drag and drop in the admin editor.

The categories I'm using is a single 1 level deep category.

It seems like the lft and rgt values are the only one that changes when they are moved.

It appears I can just divide the lft number by 2 and I get a sequence of the order (1,2,3,4,5,6).

{%- for category in relatedCategories -%}
  {{ category.title }}
{%- endfor -%}

How do the values lft and rgt get assigned and is this a correct assumption that dividing it will always get an incremental pattern?


texts: Where to place Webmaster Tools HTML File on CRAFT CMS?

texts:
Im trying to setup my Web master tools for my site, but i'm not sure where to place the html file google provides:

I've tried the 5 main folders root but with no success. Also in the craft's root.

ANy advise on where should I put this code?

thanks in advanced...


texts: Ordering of ElementCriteriaModel with varying statuses

texts:
I have a built a little plugin that calls the Twitter API to add new Tweets from a user timeline as entries, so that I can return them in an ElementCriteriaModel request to be integrated with content from other Sections.

I am trying to find out the largest tweet ID currently in the Craft system, where tweet IDs are stored as a text field against an entry, so that the next call to the Twitter API can set the sinceId field to only return tweets newer than the latest one currently stored in Craft.

I am doing this by doing an ElementCriteriaModel call, setting the order parameter to 'tweetId desc' and then attempting to find the first() entry, to retrieve the tweetId from that entry.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'tweet';
$criteria->order = array('tweetId desc');
$criteria->status = array(BaseElementModel::ENABLED, BaseElementModel::DISABLED, BaseElementModel::ARCHIVED);

$latestTweet = $criteria->first();
$latestTweetId = $latestTweet->tweetID;

However, when I do this, the ordering of the Tweets seems to be affected by the status of the entry. It seems to be returning the tweet with the largest ID with status DISABLED, rather than the largest ID across all stored tweets.

Is this behaviour correct, or is there a better way to do this? I do need to be able to set certain tweets to disabled, if I don't want them shown on the front-end of the site.


texts: Setting up routes for AMP template with category-based urls

texts:
I'm stuck on implementing AMP templates with category-based URLs as I can't find a way to route the different entry types in the Routes function in the CP.

I have a channel title Articles that has two entry types (Lists and Articles) with a URL format {businessCategory.first.slug}/{slug} that uses a primary category for the first segment of the URL.

I've tried */slug/amp as a route in the CP but then I can't change the AMP template for each entry type.

Any help would be greatly appreciated!


texts: New problem on old implementation of SproutSeo with og:image:secure_url

texts:
Yesterday, things worked fine with SproutSeo 2. I replaced two images for default pages in that plugin.

Today, some entries aren't picking up images correctly.

Some sections have

meta property='og:image' -- Still maps to the correct content image

meta property='og:image:secure_url' is also showing, but this does not map to the image. Instead, it maps to the default image for that section (ie not for the particular post, but for the index in that section) and in others, it maps to an image that is NOT the default image.

I have the craft template set to pick up the default image or to place in a featured image. This is done as in this example: https://sprout.barrelstrengthdesign.com/craft-plugins/seo/docs/sprout-seo-2/overriding-images

So I have an override for ogImage. The problem is that I don't know a way to set the og:image:secure_url property. (I can't say I've ever noticed this property before today) I can't find an override to use within the template. I don't see a setting in the SproutSEO panel.

How can I override og:image:secure_url or make it go away or whatever else I need to do so that the correct images get matched? (Ideally before I LMS over this hiccup)


texts: How do I get extracts in search results?

texts:
Say someone searches for "John Smith". Using the search results template on the Craft website, my search results are then a list of titles for entries that include the term "John Smith". For example:

Dave Taylor wins award
New building built

The user experience is quite poor as there is no indication that these articles are in any way related to "John Smith". What I'm trying to do is output the following:

Dave Taylor wins award

...with the help of his brother John Smith,...

New building built

...architect John Smith was instrumental...

i.e. something similar to Google search. Any ideas how I could go about this?


texts: /admin/install/ missing resource files (css/js 404) and is unstyled

texts:
Has anyone else run into an unstyled /admin/install/ page? Inspector shows 404 on all css and js files and they are pointing to /admin/resources/*

Been searching around and it doesn't seem to be a common issue so I'm a bit stumped. (Trying to install on an ubuntu/nginx digitalocean droplet)

I'm currently staring at this screen:
![enter image description here][1]


texts:
I have a section with a super table field, and I only want to display entries in that section if the super table field has rows (so basically a "not empty" search). How do I do this? I tried using the * and the :notempty: search parameters but neither worked.

{% set entries = craft.entries({
  section: 'mySection',
  superTableField: ':notempty:'
}).all %}


texts:
I am curious how those of you who use a multi-environment development process handle user upload directories? If you use a remote database and one developer uploads some test content, the shared database will think there are files on the other developers machine and they won't be there. This would also show its face if you access a staging server. The database would be out of sync with the upload directory.

Thanks for your input.


texts:
I have a large-ish site built with Joomla and K2, with articles stored in a hierarchy of categories..

What is the proposed way to recreate the Category hierarchy functionality?

What I am interested in is that when a user opens a parent category, he sees all items stored in this category, plus all items stored in children categories.
If he opens a child category, he sees items stored only in this category.

I have tried a demo installation, and experimented a bit with section types and categories, but what I need is some kind of parent-child relation in Categories or Sections.

Could you please help me clarify how these things are distinct and what would be best practice to achieve what I want?

Thanks in advance for your time.


texts: Where is this spam message sent using the Contact Form plugin?

texts:
I've noticed all of my Contact Form spam has a referrer that matches the form's location. Building a module is out of my comfort zone for now (not really a developer). I am currently using the Honeypot plugin, though, so I have a simple conditional in my contact page which compares the referer to the URL and if it's the same, fills the Honeypot field with a value.

The Honeypot plugin will set the isSpam flag to true, which prevents the message from being delivered. Then the form redirects to its default "Thank You" template.

What I want is for this template to display a message that the submission was flagged as spam and not delivered. I can see that /craft/vendor/craftcms/contact-form/src/Mailer.php has code that sets a message when isSpam is set to true:

if ($event->isSpam) {
   Craft::warning('Contact form submission suspected to be spam.', __METHOD__);
   return true;
}

…but for the life of me I can't find how to access Craft::warning or to have it output into a template. Any pointers are greatly appreciated. Thank you!


texts: Entry not saving when date isn't changed using frontend form

texts:
When editing an entry (actually it's a product within Craft Commerce but everything seems the same) with a pre-existing date, the field looks like this:

<input name="fields[date][date]" value="06/12/2016">

But when re-saving the entry it won't save if I leave the date the same. I'm not getting any errors. If I change the date and re-save the entry, all is fine. Any ideas?


texts:
I am performing a query from within a plugin like so:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = $journeyTitle;
$response = $criteria->find();
$attributes = $response[0]->getContent()->getAttributes();
var_dump($attributes);

The dump gives me the following:

array(7) {
  ["id"]=>
  string(1) "3"
  ["elementId"]=>
  string(1) "3"
  ["locale"]=>
  string(5) "en_us"
  ["title"]=>
  string(7) "Armenia"
  ["lifeBeforeColumnOne"]=>
  NULL
  ["lifeBeforeColumnTwo"]=>
  NULL
  ["tester"]=>
  string(12) "fdsfsdfdsfsd"
}

Has anyone ever used Super Table Before, and know why this would be showing up null? I would REALLY like to use this on my project, but am not really sure on how to proceed with this.

For reference, here is a screenshot of the entry that you see outputted within the dump:


texts: How to assign entries to static positions such as footer?

texts:
The footer of my site has some links that can be considered "static" in the sense that they always should point to a specific entry. One for "acknowledgements", one for "cookie info" and one for "more contact info".

What is the recommended way to assign entries to these three "roles"? I need it to work in a multi-site envionment.


texts: Return to specific locale based on cookie?

texts: If we are storing a cookie of a locale the user choose, is there a way to detect that cookie in htaccess so the next time they visit the base url of the site it will take them to the same locale?


texts: Stripe: Craft Commerce_OrderModel and its behaviors do not have a method or closure ....

texts:
I'm trying to accept Stripe payments and am stuck in a loop where I have optimal behavior on the dev and staging versions, but then things broke in production and got the following error message:

Craft\Commerce_OrderModel and its behaviors do not have a method or closure named 'firstName'

Can someone give me some direction around this? Again, it only happens in production, and obviously, we need to be able to receive payment from customers. Thanks!


texts: Cannot invalidate template cache (by element) on entries.onDeleteEntry

texts:
I'm trying to do craft()->templateCache->deleteCachesByElementId on entries.onDeleteEntry, unsuccessfully.

The event listener is working, but the caches don't get invalidated.

Here's the code:

public function init()
{
    craft()->on('entries.onSaveEntry', function($event) {
        $this->clearEntryCache($event);
    });

    craft()->on('entries.onDeleteEntry', function($event) {
        $this->clearEntryCache($event);
    });

}

public function clearEntryCache(Event $event) {
    $entry = $event->params['entry'];
    craft()->templateCache->deleteCachesByElementId($entry->id, true);
}

entries.onSaveEntry works perfectly.
Instead of run deleteCachesByElementId, if I deleteAllCaches, it works (but I don't want to do this)
I've also tried entries.onBeforeDeleteEntry with no luck.
I've tried deleting from the entry, and from the entry listing (bulk delete) screen.

On the surface it seems maybe it isn't working because by the time deleteCachesByElementId, the element is already deleted...though it still seems there should be a way to delete that cache with the elementId reference.


texts: Plugin settings - file field upload location

texts:
My plugin needs to allow admin to upload an image. I have the field setup and saving ok. But i cant seem to control the upload location.

This is what i have so far in my settings:

{{ forms.file({
    label: "My Image"|t,
    instructions: ""|t,
    name: 'myImage',
    value: settings.myImage
}) }}

When I output the settings.myImage, I get the file name on its own and no path. I would like it to upload to my /uploads folder.
So for example, the image I uploaded was "test.jpg". When I output the result of settings.myImage, I get "test.jpg" and no path.


texts:
I have a relationship field within my member profile. It allows users to connect to each other, i can list those that currentUser is connected to, but i need to list all other members that are connected to currentUser, i.e. a reverse relationship.

I have this, but it just lists those that the currentUser is connected to, not the reverse, where am i going wrong?

{% set myReverseConnections = craft.users.relatedTo(currentUser) %}


texts: Where are Matrix Entries Fields Relationships in the Database?

texts:
I can see the simple matrix field data in the craft_matrixcontent_MYMATRIXtable.

craft_matrixcontent_MYMATRIX
---------------------------
id | elementId | locale | field_BLOCKTYPE_FIELDHANDLE | field_BLOCKTYPE_FIELDHANDLE | dateCreated | dateUpdated | uid

If I need to query upon those fields, I can thanks to some of the great posts to this site. But those fields are simple text fields.

I have an Entries field in my matrix. Where can I find this relationship in the database? It doesn't exist in the craft_matrixcontent_MYMATRIX table.


texts: Fetching a Localized Global as a Static Translation Causes Error in How Plugins Load

texts:
I've extended all my "translations/[locale_id].php" to refer to this  function which enables us to put all our translations under a global in the control-panel.

However, when this is done – we lose data attached to our assets. We currently use a Focal Point plugin attached to our assets. It describes with a field how images are to be cropped. This particular plugin stops working when the line highlighted below is executed.

function get_dynamic_translations() {
    $translations = array();

    if (!craft()->request->isCpRequest()) {
        // the following line makes the plugin "FocalPointField" stop loading its data
        $i18n = craft()->globals->getSetByHandle('i18n');

        foreach ($i18n->getFieldValue('translations') as $current_block) {
            $translations[$current_block->content->key] = $current_block->content->value;
        }
    }

    return $translations;

}

I would love for these two solutions to work together in perfect harmony – but I can't seem to figure out why this is not working.

Do you have any idea how I can go forth?


texts: Can't Upload JPEGs to live site (PEL error)

texts:
I'm unable to upload any jpg/jpeg files to the server, it just comes up with an alert saying "upload failed". After checking the PHP error logs for Craft I found this error message is being created every time I try.

PHP Fatal error:  Class 'lsolesen\pel\PelConvert' not found in .../craft/app/vendor/lsolesen/pel/src/PelDataWindow.php on line 96

Any advice on how to fix this error?

I've tried:

Uploading different files to make sure it wasn't an issue with the one jpg
Uploading different file types (no errors occurred with other image file types)
Several local server fixes I found


texts: Is it possible to create a new multisite site via a Craft Plugin/Module?

texts: Does Craft provide a way to programmatically add a new multisite site through a plugin or module?


texts: Printmaker plugin cuts off HTML when rendering PDF link

texts:
I’ve got a funny Printmaker issue here that I hope you can help me with!

I’m using the following code to generate a link to a PDF:

{% set vars = { title: supportGuides.title, body: supportGuides.body } %}

{% set settings = { orientation : 'portrait', filename:supportGuides.slug~'.pdf' } %}

{% set pdf = craft.printmaker.pdfFromTemplate('support-guides/download', vars, settings) %}

Download PDF Support Guide

In my HTML output, the beginning of the line is stripped out inexplicably:

https://mysite.dev/Printmaker/support-guide.pdf" target="_blank">Download PDF Support Guide

How can I prevent the opening tag from being cut out like that?


texts: I'm a bit confused by the notifications set-up in Freeform. The instructions state 'The notification template used to send an email to the email value entered into this field (optional).' I selected the template and entered an email address in the field below, but an email notification is sent to the user of the form as well as the administrator following a submission. So how do I set up a notification to send to admin only? And if I wanted to create a separate notification for the user, how do I do that?


texts: New Project: Wait for Craft 3 or start now with Craft 2?

texts:
I am just about to start a new project and Craft seems the best fit as a CMS. The projects timescale is 3 months.

I understand that a beta for Craft 3 is due out at the end of this year (2016). In view of this, should i start development on Craft 3? Or run with Craft 2 for now?

The project will involved bespoke plugin development and use of the Commerce plugin. Is there any timeframe in place for updating the Commerce plugin to run on v3?


texts:
I want to order entries in an "Entries field" by the order I added them to the field. So Anastasia would be first and Beni would be last.

My only idea was .fixedOrder like you would do it with an asset field:

{% for entry in craft.entries.section('musiker').relatedTo(entry).fixedOrder(true) %}
   {{ entry.name }}
{% endfor %}

But that does nothing.


texts:
In updating a plugin for Craft 3, at one point I also renamed it, and at various times did things in the wrong order. At this point, Craft shows the old, unwanted plugin, but

it is not in composer.json
it is not in the craft_plugins table
none of its tables are in the database
its files have been deleted from craft/vendor/ns/plugin

On the CP Plugins page, if I click Remove, composer updates and says it is successfully removed, but it still shows up under plugins.

How does Craft still know of its existence? Do I need to put it back into composer to do a composer remove?


texts: Extending Craft Commerce admin templates

texts:
I would like to add an option to the gear menu seen below in Craft Commerce, is it possible to extend those templates ?

The idea is to create a plugin to export the selected orders to a CSV file


texts:
Is it possible to define an aspect ratio / set a max height on an image transform, without using a plugin?

Let's say the width is fixed to 600px, but the height can be any value up to 800px?


texts: Assets, Multi Locale and 'Target Locale'

texts:
I've created all my Assets fields with 'Same as Source' selected in 'Target Locale'. When I create an entry in language A, all field content is copied over apart from the assets selections into language B/C/D.

If I change this and select a set Locale in 'Target Locale' what actually happens? (e.g. If I select language A, will it copy that asset into lang B/C/D's entry and can it be changed/updated by an admin who only has access to B?)

P.S. In this situation, all assets are remote on S3.

Thanks!


texts: How can I break up a product into two page templates?

texts:
I have a product overview page, with images and some text, then a call to action that launches a product customiser for that particular product. (the customiser is requiring some bespoke JSON using line items).
It is on the product customise page that the 'add to cart' button is placed.

I would like the following URLS for each seperate page:

Product overview:

myshop.com/products/productname

Product customiser:

myshop.com/products/productname/customise/

How would I go about doing this? By default, Craft only seems to let me use one template per product.

Any help greatly appreciated :)


texts: Loop through structure entry types and matrix blocks

texts:
Single page website. Navigation based on a Structure section (anchor links). Entries depend on entryTypes.

{# set each section ID with for anchor navigation #}
{% for page in craft.entries.section('pages') %}
<section id ="{{ page.slug }}">

    {# check the slug to get the Matrix entries related to the (html) section ID #}
    {% if page.slug == 'home' %}
        {# get the entries for the entry.type #}
        {% set entries = craft.entries.type('pagesHome') %}
            {# loop through the block types and entries #}
            {% for block in page.matrixFieldHandle.type('matrixBlockHandle') %}
                {{ block.title }}
            {% endfor %}
    {% endif %}

    {# and so on.... #}
    {% if page.slug == 'about' %}
        ......
    {% endif %}

</section>
{% endfor %}

Questions: am I setting up this single page website in a too complicated way with too many DB queries?
Thanks for suggestions!


texts: Upcoming events from specific groups using Venti

texts:
I'm new to both Craft and Venti so apologies if this is quite basic.

I've got multiple groups setup using Venti and multiple events within these groups.

On the client side I just want to display the 5 upcoming events from a specific group. Anyone know the best way to go about this?


texts: how can I filter to get only root categories in elementapi.php

texts:
I tried to build JSON-API which returns all categories, whose result will be cascaded like "nav" tag with craft twig templating (see: https://craftcms.com/docs/templating/craft.categories ).

to get all root categories (which has no parent category, and which can have child categories), I've tried to filter giving within "criteria" something like that, but the result was just returned all categories:

'endpoints' => [
    'api/categories' => [
        'elementType' => ElementType::Category,
        'criteria' => [ 'descendantOf' => null ],
        'transformer' => function($entry) {
            return [
                'id' => $entry->id,
                'title' => $entry->title,
                'parent' => ($entry->parent) ? $entry->parent->id : null,
                'children' => ($entry->children) ?
                    children_in_array($entry->children) : null,
            ];
        },
    ]
]

function children_in_array() returns same structure like result of 'transformer' function (id, title, parent, children).

How can I get only root categories in this way?

or is there other solution all cascaded category list in JSON format?


texts: Switching plugin license from Craft 2 to Craft 3

texts:
Dumb question, but...

I purchased a plugin when using Craft 2 and now I'm trying to input the license for it in Craft 3. There's an input for the license key when I go to settings -> plugins, but the submit for it says "buy now" and tries to put the plugin in my cart. How do I give Craft 3 the license?


texts: Craft CMS 3 Boilerpoint Web Project Setups Available?

texts: Does anyone have any recommended boilerpoints or guides on setting up Craft CMS 3 with front-end tooling? Looking for an initial install to be setup properly with a preconfigured database, NPM, node.js, Sass, and page templates configured to get any web project started.


texts:
I am performing the following query, which returns me an array of matrix blocks:

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->relatedTo = array(someCoolId, anotherCoolId);
$relatedStories = $criteria->find();

When looping through this array, I was wondering if it was possible to access the handle of the matrix block that I am currently in. Reason being is I would like to retrieve this as a string, and perform some type of work on it.


texts: Redirecting certain 404s to a page, handling all others as normal

texts:
I'm having trouble setting things up to redirect some old news articles a certain way, while still serving existing articles:

  If a page exists at /news/my-article then it should be served as normal.

  If that URL doesn't exist (ie, all non-functioning /news/* URLs), I want the user to be redirected to /news.

  All 404s that aren't within /news should be handled as normal.

My first thought was to use a redirect tag in the 404 template, only if the request URL matches /news/*... but I'm not sure if that's too late in the process. By that time, has a 404 header already been sent, so the user would get 404 -> 301 -> 404 ?


texts: Do "update cart" and "complete cart" as one action

texts:
I am developing a site which has "normal" shop stuff that is added to cart and bought through the checkout process. But it also has to support submitting requests for food catering jobs. This is a slightly different workflow. I want to do this by creating a "catering product", which has a number of line items which represent the food items the customer wants supplied on the day.
So I can setup a custom product page with all the line item fields etc on it. But now I am wanting to combine "add to cart then complete checkout without payment" into one action, so that this all happens in one go when they submit the catering request form. (The client will then get in touch with the customer, confirm the catering job details, then the customer will pay for the job once everyone is happy.) So really I need to combine two actions - "update cart" and "complete cart".
Any suggestions on the best way to do this? Do I have to write my own module? Any advice/tips greatly appreciated!


texts: Perform "inclusive" relatedTo query with multiple categories

texts:
I want to be able to return all entries that are related to 1 .. n categories:

{% set resources = craft.entries.section('resources').relatedTo('and', categories) %}

in this example, categories contains two categories category1 and category2, and the query returns all entries that have either category1 or category2.

How do I change the syntax to return entries that are related to both category1 and category2?

I thought 'and' would do it, but seemingly not.


texts:
I'm trying to import posts using the Feed Me plugin. I'd like to make a dynamic URL so that I can access the feed from a Cron job or from elsewhere in the CP. It says in the docs that I can use environment variables inside the Feed URL, but it isn't working for me. Am I using them the wrong way?

My Feed URL (not working):

http://some-url.com/{{issueNumber}}

Apart from environment variables, is there some other way to pass variables into Feed Me? The client won't have direct access to the Feed Me plugin and therefore won't be able to manually edit the URL each time.


texts: Sprout Forms Confirmation Page Field Not Defined

texts:
I'm trying to create a confirmation page for a Sprout form, where I want to check if a certain field is present, and if so, check for a value, so I can return a message based on that value.

I'm using lastEntry, and am able to pull the valid fields in without a problem, but it's having issues checking whether the field is defined. I'm currently using the following code:

{% set lastEntry = craft.sproutForms.lastEntry() %}
{% set qualified = true %}
{% if lastEntry.fieldName is defined and lastEntry.fieldName == 'no' %}
    {% set qualified = false %}
{% endif %}

When I use the code above, and the field has not been used in the particular form, I see:
Craft\SproutForms_EntryModel and its behaviors do not have a method or closure named "fieldName".

It appears Craft is seeing the field as defined, but not. Anyone have any ideas on what I could do to figure this out?

Thanks!


texts: What is getContent() / the ContentModel, and how do I use it to get and set custom field values?

texts:
If I want to retrieve content on an element, should I be calling $entry->$fieldHandle or $entry->getContent()->$fieldHandle? What’s the difference?

Likewise, if I’m setting new content on an element, what’s the recommended way to set my new custom field values?


texts:
I need to create a popover on words to explain in more detail what that word actually means. It's kind of a dictionary for technical words.

But I would like to avoid to many queries and use it like Twig's translate filter. But the customer needs to add new descriptions to specific words from CP.

Could I please get some advice or pointer for further development?


texts: My license.key file missing. How do I transfer the license to other servers?

texts:
I just purchased a license from the CP of my production server. Then I went to the config directory to retrieve the license.key for my local dev server but it was not there. I can't find it anywhere. I installed the site the other day using Craft-2.1.2563 and when I went back to look at the zip I see that the license file is missing there as well.

What do I do? How can I transfer the license to my dev environment as well?

FYI - I set up my dev environment a few weeks ago and it was based on a slightly older build of Craft 2 - I'm not sure which version. But, it does have a license.key file. That doesn't do me any good because I purchased a license on the production server.

Thanks.


texts: Is it possible to access users' search query data?

texts:
Is it possible to obtain data on what searches have been performed through the front end of a Craft website?

e.g. If there is a search results page which runs

{% set results = craft.entries.search(query) %}

is that the query data stored anywhere? It would be helpful in terms of understanding what kinds of search terms / keywords people are using to search for information.


texts: How do I pass a user's first name and last name from a user profile page to the title in _layout?

texts:
I am trying to pass a member's firstName and lastName to the title on a member profile page. I am using segment 2 to capture the username. This works well in the for loop in the block:

{% set thePartner = craft.users.username( craft.request.getSegment(2) ) %}
{% for partner in thePartner %}
First Name and Last Name: {{ partner.firstName}} {{ partner.lastName }}
{% endfor %)

Outside the block, where I set the <title>, it doesn't work. Essentially, I would like to set the full name and use it in the title, like:

{% set fullname = partner.firstName ~ ' ' ~ partner.lastName %}

with something like the following in _layout:

<title>{{ fullname }} | {{ siteUrl }} </title>

How can I pass the full name through?


texts: How can I display dateUpdated for the most recent updated entry in a category?

texts: I would like to display the date that the site was last updated. This date is the same as the last entry added to a specific category. Thanks in advance.


texts: Error: Craft\EntryModel and its behaviors do not have a method or closure named "Case Studies"

texts:
I'm new to Craft CMS dev and I'm trying to create a template using Twig and I'm getting this error: Craft\EntryModel and its behaviors do not have a method or closure named "Case Studies"

I have a reference in the view file:

{% for entry in entry.caseStudies %}

I'm assuming there's a config file or somewhere I can add this to the EntryModel but I'm not sure where this is in the default Craft installation. Any suggestions are welcome.

Thanks


texts: How to search by title OR tag using Craft CMS?

texts:
I want to do a search query so the product title or product tag name matches the keyword. below is my code. if I remove the tag related query, this code works as it looks into the product title only and returns the result. But how to make it work so it looks for the keyword in both product title and tag name? and if it exists in any one, it results specific records?
 {% set productValues = {
        keywords: craft.app.request.getParam('keywords'),
        orderBy: craft.app.request.getParam('order') ? craft.app.request.getParam('order') : 'score'
    } %}

    {% set tag = craft.tags.search(craft.app.request.getParam('keywords')).first() %}

    {% set productParameters = {
        search: 'title:' ~ productValues.keywords,
        relatedTo: [
            'OR',
            tag
        ],
        orderBy: productValues.order
 }%}


texts:
I updated to the newest Craft Version 3.1.1. Since then I have the following problem. I lost all the data from Matrix Filed stored in a Super Table Field after changing Field Setup (Matrix - Asset props.) again.

Setting:
Craft CMS: 3.1.1,
Super Table: 2.0.14

1)
I created a Super Table Field which stores a simple Text Field and a Matrix-Field with one Block which stores a simple Text and an Asset.

2)
I added the Field to a Single Entry.

3)
I created all Content with the Super Table Field in the Entry

4)
jumped back to Super Table Field Settings and changed something in the Matrix Asset properties

5) after Saving i lost all the Data in the Matrix Field, which i stored in the entry

Really bad, because the Super Table field i created in the entry was complex.

Does anyone else have the same problem? - What did I Wrong?


texts: Access Image Transforms for S3 images via Element API

texts:
I'm building a small Craft site to function as a content backend, exposing all of the content via the ElementAPI.

One field I'm retrieving and displaying in the API is the URL on Amazon S3 for an image asset that's contained in a Matrix field.

What I'd ideally like to do is, when the user uploads this image and it's added to the S3 bucket, to be able to access S3 URLs for the small, medium and large cropped Image Transforms that I've defined. Then, I can make all of these available as an Element API endpoint.

My understanding of Image Transforms and S3 is that Craft usually handles this on-the-fly when an image is referenced in a frontend template. But is there a way to do this when there will be no frontend templates, and the only way that information will be accessed is via the Element API?


texts: Has anyone migrated a Blogger site to CraftCMS? I'd like to migrate comments and posts. What is the best way to go about this? Could I import my site to Wordpress and then to Craft?


texts:
I came across error Property "Craft\WebApp.assetUpload" is not defined, when registering users from front end. Is this a bug or missing config param?

I have used the example on craft website:
https://craftcms.com/docs/templating/user-registration-form

The Actual template used is:

Membership Registration

<form method="post" action="" enctype="multipart/form-data" accept-charset="UTF-8">

    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="">

    {% macro errorList(errors) %}
        {% if errors %}

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

Username

    <input id="username" type="text" name="username"
    {%- if account is defined %} value="{{ account.username }}"{% endif -%}>

    {% if account is defined %}
        {{ errorList(account.getErrors('username')) }}
    {% endif %}

Email

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

    {% if account is defined %}
        {{ errorList(account.getErrors('email')) }}
    {% endif %}

Password

    <input id="password" type="password" name="password">

    {% if account is defined %}
        {{ errorList(account.getErrors('password')) }}
    {% endif %}

    <input type="submit" value="Register">
</form>

Cheers,
Sil


texts:
I'm trying to import data from another database using locales, but am having trouble saving the other locale after the primary locale is saved.

foreach($row as $data) {

    $entry = new EntryModel();
    $entry->sectionId   = 1;
    $entry->typeId      = 1;
    $entry->authorId    = 1;
    $entry->enabled     = true;
    $entry->locale      = "en";

    $entry->getContent()->setAttributes(array(
        'description' => $data["description-en"],
    ));

    $success = craft()->entries->saveEntry($entry);

    if ($success)
    {
        ImportPlugin::log('Successfully saved entry "'.$entry->id.'"', LogLevel::Info);

        $entryEs = craft()->entries->getEntryById($entry->id, "es");
        $entryEs->getContent()->setAttributes(array(
            'description'   => $data["description-es"],
        ));

        // **** The following doesn't work for some reason ****

        craft()->entries->saveEntry($entryEs);
    };
}

The primary entry saves fine and if I dump vars I can see that both $entry.id and $entryEs exist and are formatted as expected — but it doesn't save.

Is it perhaps being overwritten (or ignored) as the content from the primary locale is being copied to the other locales in the background? What's the recommended way to save multiple locales?


texts:
I would like to select just the children of any given main category (eg. Accessories, Stomps in the picture), regardless of segments in my URL.

I've been trying to understand why the code below won't work.

This just won't work. Why?

{% set categoryGroup = craft.categories.group('productTypes').descendantOf('accessories') %}

    {% for category in categoryGroup %}

{{ category.title }}

    {% endfor %}


texts:
I am trying to store an entry in a plugin. The entry has a field 'tags' that relates to another entry. I am trying to store it with the following code.

$newsItem = new EntryModel();
$newsItem->sectionId = craft()->sections->getSectionByHandle('news')->id;
$newsItem->getContent()->tags = $tag->id;
craft()->entries->saveEntry($newsItem);

When I var_dump(craft()->entries->saveEntry($newsItem)) I get a false response.

Also, in this situation we cannot use the method setContentFromPost() so we need to do it from within the plugin and not from a front-end form.


texts: XAMPP Windows 10 - Could not find your craft/ folder error

texts:
I'm new to Craft CMS and would like to getting started, I searched for several hours now but I was not able to find an answer.

I downloaded and copied craft to my htdocs folder, created a database and changed the db access but when I open my page I get

Could not find your craft/ folder. Please ensure that $craftPath is set correctly in C:\xampp\htdocs\craft\public\index.php

I think I have to change the permission of that folder but I have no idea how to do this. Could you help me?

I didn't change any path, so it is correct and points to the right file but there is only one directory visible in C:\xampp\htdocs\craft\ in my browser

Edit:
my Files looks like this
htdocs
-craft
--craft
---app
---config
---plugins
---storage
---templates
---.htaccess
---web.config
--public
---index.php


texts: Error while sending QUERY packet. PID=881 when using cache key

texts:
If I do:

{% set cacheKey = block.id %}
{% cache using key cacheKey if craft.app.config.general.cache %}
    {% for item in items %}

        <div class="swiper-slide ais-hits--item" data-id="{{ item.id }}">

            {% set object = (block.contentType == 'events') ? item.show.one : item %}

            {% include '_blocks/blockCard/blockCard' with {
                content: object,
                blockId: block.id
            } %}

            {% include '_blocks/blockCardPreview/blockCardPreview' with {
                content: object,
                blockId: block.id
            } %}

        </div>

    {% endfor %}
{% endcache %}

I get an error saying

PHP Warning – yii\base\ErrorException
Error while sending QUERY packet. PID=881

If I remove the using key cacheKey part it works. But of course al the sliders have the same content.


texts:
How do I update the lineItems after I submit the form through ajax? right now it adds the item, but it doesn't show up in the cart, it only shows up when I reload the page.

I am adding an item to the cart through ajax with this code:

$('.form-products').on('submit', function(e) {

    e.preventDefault();

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

    $.ajax({
        type: 'POST',
        data: data,
        url: '/',
        success: function(response) {
            var cartCount = '(' + response.cart.totalQty + ')';
            $('.cart-count').text(cartCount);

            $('#cart').removeClass('close');
        },
        error: function(response) {
            console.log(response);
        }
    });

});

Then under the  div#cart I have this code:

{% for item in cart.lineItems %}
   <li>
     cart information goes here
     this shows the product images, price and other info.
   </li>
{% endfor %}


texts: Updating plugin to Craft 3: craft()->urlManager->setRouteVariables?

texts:
What would be the Craft 3 / Yii 2.0 version of
craft()->urlManager->setRouteVariables(array('calupdateResponse' => $out));

This doesn't work (it doesn't complain, either):

$urlManager = new UrlManager;
$urlManager->setRouteParams(['calupdateResponse' => $out]);


texts: Image Upload & Editing Suddenly not Working

texts:
I'm getting an error on Image Upload and Asset Editing on an existing site. I'm getting the Upload failed. The error message was: “The file “.../storage/runtime/temp/...” does not appear to be an image.” error that's been discussed previously here. Imagick version 3.4.3 (ImageMagick 6.7.8-9) is installed. Switching the file, the format, or reuploading a previously uploaded image also does not work. Editing old assets w/n Craft yields a generic image icon.

No recent changes to the server that Im aware of. PHP 7.0.33. Craft Pro 3.3.1 ('Im stuck in the upgrade process -- see my other question previously).

Any ideas?


texts: Updating index tables' sortable attributes on AJAX

texts:
I'm currently writing a plugin enabling users to easily add custom fields to index tables, using the native field layout designer.

My current goal is to have any datetime, boolean, string or number fields added to a source's FieldLayout, also automatically be added to the relevant index table's sortable attributes. Obviously, I've met a stumbling block with modifyEntrySortableAttributes.

Everything works great on initial pageload (I've found a way to work around the fact that modifyEntrySortableAttributes doesn't have a clue about the source).

My problem is that when navigating between sources, Craft uses AJAX, and the sortable attributes are not updated. Through logging I've confirmed that the modifyEntrySortableAttributes hook does run (see footnote!) every time the source changes, and I also know that my fix for identifying the current source also works (i.e. the plugin fetches the correct FieldLayout whenever the source changes).

So – as far as I can tell – I'm basically stuck with a CP frontend issue, which is that the ".sortmenubtn" button doesn't refresh its ".menu" container contents when the source changes. I'd be happy to refresh the menu myself through some JS in my plugin, but I've looked at the AJAX calls and can't spot any data related to the sortable attributes.

My backup solution is to create my own AJAX service to fetch the updated attributes, but it would be really cool to do this with a minimal amount of hacks (the plugin already contains a few...).

Would greatly appreciate any ideas for solving this!

Footnote: It's actually weird that the hook runs when the source changes, as this directly contradicts the following statement in the docs:

Note that this method will only get called once for the entire index; not each time that a new source is selected.


texts: Indirect Relationship defined in Matrix Block

texts:
I have 3 channels: Reviews, Products and UseCases.

In the section "Reviews" an entry has a list of "Products", based on a matrix field. Every block in this matrix field represents one listed "Product". The block contains of two entries (relationship) fields one to an entry of the Products channel and another one to an entry of the UseCases channel.

Now the question: Based on this setup, is it possible to query all Products with relation to a UseCase? (I am struggling because there is no direct relationship but only an indirect one via a Matrix block.)

I am in general relatively familiar with Craft CMS, but unfortunately not on that level of complexity, therefore I am very happy to get your help.

Thank you very much!


texts:
Just wondered if there's a quick way to see if a specific tag exists from anywhere in the site (by ID)?

I'm creating a navigation bar, and need to include a specific tag... only if it has been created/used.

Cheers, Mark


texts: When using getCriteria() along with buildElementsQuery() raw html gets displayed by the template

texts:
I am trying to use getCriteria() along with buildElementsQuery () in my plugin in order to eventually modify the query.  At the moment, I am not making any modifications to the query.

But when the the fields are outputted in the template, I ended up getting raw html on the screen.  Not nicely formatted HTML.  For example, the paragraph tag shows as <p> and in the source of the page it is &lt;p&gt;.  The <p> should only be in the source.

How do I get the template to display the nice html and not the raw html?

In my plugin service

public function getMyLibrary()
{
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'library';
    $criteria->limit = 10;

    return ($criteria->find());

}

In my template:

{% set my_library = craft.accd.my_library() %}

{% for entry in my_library %}

    {{ entry.title }}
    {{ entry.body}}

{% endfor %}

Everything works as expected and the rich text html from the body displays correctly.

But when I change it to use buildElementsQuery as I will modifying the query, the entry.title and entry.body get displayed in the template as raw html.

Here is the code with the buildElementsQuery added.  I had to also modify the field body to be field_body in the template.

In my plugin service

public function getMyLibrary()
{
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'library';
    $criteria->limit = 10;

    $query = craft()->elements->buildElementsQuery($criteria);

    return ($query->queryAll());

}

In my template:

{% set my_library = craft.accd.my_library() %}

{% for entry in my_library %}

    {{ entry.title }}
    {{ entry.field_body}}

{% endfor %}


texts: Loop through an entry's fields and if the field type is "Categories" get that fields value/s

texts:
In my plugin I need to loop through an entry's fields and if that field is a field type of "Categories" use that entry field value/s.

This is what I have tried so far.

if(array_key_exists('byCategory', $filterAttributes))
{
  foreach ($entry->getFieldLayout()->getFields() as $key)
  {
      $field = $key->getField();
      if($field->type == "Categories"){

         if(!$this->addFilterdCategories($field,$filterAttributes))
         {
             continue;
         }
      }
   }
}


texts: Getting a 'ReflectionException' error, "Class modules\Module does not exist' when I change the namespace of my module in Craft 3

texts:
First attempt at making a module. So far all I've done is try to change the namespace of the template that was included with my freshly installed craft 3.0.23.1 project.

Was following the official docs (https://docs.craftcms.com/v3/extend/module-guide.html#set-up-the-basic-file-structure) and spend a few hours trying to figure this out on various searches here and elsewhere.

So in the file '/modules/Module.php' I changed

namespace modules;

to

namespace banana\modules;

, then in '/composer.json' changed:

  "autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },

to

  "autoload": {
    "psr-4": {
      "banana\\modules\\": "modules/"
    }
  },

Then in Terminal, ran the command 'composer dump-autoload -a' in the project folder. Reload the page and I get the error. Other than just doing the setup wizard, i haven't touched any other files in the project.


texts: How to get an element query into json (for vue) without extra data?

texts:
Lets say I want to get a list of category names and ids and pass them into JSON (for vue.js).

This is how I'm currently doing it:

{% set sections = craft.categories.group('teamCategory').select(['title','elements.id','groupId']).all() %}

<!-- My vue.js tag: -->
<team :sections="{{ sections|json_encode() }}"></team>

My problem is that I only want title and id to be passed to vue, but craft/twig is passing load and loads more data that forms part of the category object.

Is there an easy way to just pass the array columns I need?


texts: Dukt Analytics Plugin - Web Profile not showing up

texts:
I'm trying to configure the Dukt Analytics Plugin to a site for my first time. I was able to successfully configure oAuth on my Google account, and get the account connected via the Analytics Plugin panel in Craft.

However, I'm having some issues getting the web profile dropdown list to populate. While connecting to Google Analytics, the only permissions it asked for was "have offline access" which may be part of the issue.

Is there any sort of troubleshooting methods that can be done to figure out why no web profiles are showing up?


texts: How to fetch products related to every product within an array?

texts:
I’ve got products which are related to various products of another type (product.accessories).

Now I’m trying to fetch all products related to every single product within a given array.

My first attempt was to prepend an array item 'and' in order to tell relatedTo to match all products:

{# simplified code #}
{% set accessories = craft.products().type('accessory') %}
{% set accessories = ['and'] | merge(accessories) %}
{% set products = craft.products().relatedTo(accessories) | all %}

Which leads to an error: 'array_merge(): Expected parameter 2 to be an array, object given'.

I know I could use the object syntax, but this would require an additional traversal in the first place:

{# simplified code #}
{% set accessories = craft.products().type('accessory') %}
{% set constraint = ['and'] %}
{% for accessory in accessories %}
    {% set constraint = constraint | merge([{element: accessory}]) %}
{% endfor %}
{% set products = craft.products().relatedTo(constraint) | all %}

Is there a way to mach all products without the need of an additional loop?


texts:
Does anyone know if there is an API for CRAFT 3 where I can authenticate to and query (CRUD) all the elements (channels, etc.) I have created on it?

Thanks.


texts: Correct timezone for AttributeType::DateTime in CP

texts:
I've written a plugin that stores records in it's own table. I can see that the dateCreated and dateUpdated fields are stored in UTC.

When I want to display them in a CP template, I'm using populateModel and my model contains 'dateCreated' => AttributeType::DateTime.

If I output this with {{ entry.dateCreated|dateTime }} then I'm still getting UTC time and not BST (the Timezone in Settings).

If I use {{ entry.dateCreated|date('d M Y H:i', 'Europe/London') }} then it's correct.

Is there any way to get the date with the correct timezone set automatically?


texts:
I'm trying to add tabs into my Craft Site and have just noticed that when you add an anchor point, the anchor ID doesn't actually show up in the URL as it would a normal site, however I need this anchor to be able to target certain tabs in the menu.

Is there a way or plugin that forces to anchor to be added to the url?

Example:

mysite.com/tabs#anchor1

mysite.com/tabs#anchor2

mysite.com/tabs#anchor3


texts:
I am learning craft and trying add settings page for my plugin. I read that need to define settings like,

class CocktailRecipesPlugin extends BasePlugin
{
    // ...

    protected function defineSettings()
    {
        return array(
            'cocktailCategories' => array(AttributeType::Mixed, 'default' => array('Sours', 'Fizzes', 'Juleps')),
        );
    }
}

So isn't clear and there is no explanation what the array return and how to use it inside the template.

Thank you


texts: How to tell whether a SuperTable column has data or is empty?

texts:
I have a "contact table" SuperTable with columns for Name, Phone, Email, and Website. In the template, I'm displaying the data as a table.

I only want to generate table columns if a column has data. For example, if there are no Phone Numbers included, I don't want a Phone column. If even one row has a phone number, I do want to include that column.

How do I create a conditional to check whether a SuperTable column has data in it?

This might be related to Querying a supertable field.


texts: Split-style button for "New" custom element

texts:
I've got a plugin with a custom element. It evolved based on the basics laid out in the P&T Events sample plugin.

On my element's index page, there's a big button to create a "New Element". When you click on it, you see a dropdown list of every available group for the new element:

This is the result generated by the code in the Events example.

However, I really want a split button format, like Craft provides for its entries:

The advantage there would be the "one click" add, if you're already viewing the target group.

I've tried copy & pasting various HTML from the entries template, but that doesn't really seem to be doing the trick. I suspect JS is playing a large role in generating that menu, but I haven't quite figured it out yet.

How can I make a split-style button for my custom element?


texts: bootstrap.php returns a value of 1 in Craft CMS

texts:
I have a Craft CMS instance that I created a copy of by tarring up the folder and then dumping the mysql database and then transferring that to a different server. On the target server I restored the folder and the database.  When I attempt to access the instance, I get an error in the Apache logs:

[Mon Jul 29 15:48:01.415795 2019] AH01071: Got error 'PHP message: PHP Fatal error:  Uncaught Error: Call to a member function run() on integer in /var/www/html/bsf_public/craft/app/index.php:73\nStack trace:\n#0 /var/www/html/bsf_public/public/index.php(19): require_once()\n#1 {main}\n  thrown in /var/www/html/bsf_public/craft/app/index.php on line 73\n'

I have spent multiple hours chasing the errors.  A phpinfo() call in a file works so I know that PHP is properly configured.  So I focused on line 73 of the index.php file referenced in the error message.  It has these lines (in addition to others):

// Load and run Craft
// -----------------------------------------------------------------------------

$app = require 'bootstrap.php';
$app->run();

$app is returning a value of 1.  bootstrap.php has these final lines of code:

$appClass = '\Craft\WebApp';
$app = new $appClass($config);

return $app;

I can't quite figure out why the bootstrap.php is returning a 1 which is why the error message occurs.  I found one other instance of this being reported in a PHP app but the post had no resolution.

Maybe a Craft CMS guru can point me the right direction although I'll bet it is some kind of permissions or PHP issue.  I checked the PHP files and they all have execute permissions.

Ubuntu 16.04.6 LTS

5.7.26 MySQL

PHP 7.1.29 (cli) (built: May  3 2019 09:33:57) ( NTS )

Craft CMS 2.7.5


texts: How to check whether a named Asset Transform exists?

texts:
I'm using asset transforms in various places to serve appropriately sized images via a Twig macro that I feed an entry and the name of a transform into (the idea is to have the same bit of HTML, but with differently sized images depending on the context). The way I get the image URL is as follows:

entry.mainImage.first().getUrl(transform)

However, at the moment if the named transform is not found (ie. if the value of transform doesn't correspond to the name of an existing transform) I get a Craft error. For my purposes a better failure mode would be to just serve the untransformed, full-size image. I'm wondering if there's a way of checking whether a named transform exists? That way I could just set transform to null if it's not found and it should fail gracefully.


texts: I followed the document to create a migration, add a schema version, install migration and add schema codes into Install.php. Last I run the migrate up command, but no table is created. Anyone could tell me what is going wrong please?


texts: FreeForm: Accessing a fields customAttributes

texts:
Is it possible to access customAttributes on a FreeForm field?

Currently attempting to do this via:

{% for row in form %}
  {% for field in row %}
    {{ dump(field.customAttributes) }}
  {% endfor %}
{% endfor %}

Where form is a FreeForm object.

Currently I'm getting an error that indicates that attribute does not exist or I can't access it.


texts:
How do I parse the breadcrumbs code:

{% if entry.level > 1 %}

        {% for crumb in entry.getAncestors() %}

{{ crumb.getLink() }}

        {% endfor %}

{% endif %}

into lowercase?

Home > blog > entry title

or

  home > blog > entry title


texts: Best solution for get json results from third party api?

texts:
I need to get blog posts from hubspot api using this approach.
http://developers.hubspot.com/docs/methods/blogv2/get_blog_posts

Since craft uses twig I'm unable to use php in the templates, so I thought I could just use jQuery getJson but this causes a cross origin request blocked error.

So is creating a plugin and using php my only option to get json results from an api call?

Has anyone used hubspot api?


texts: From a plugin, how would I go about detecting if an admin user is using the "Login as User" feature?


texts: List Entries in a section that are referenced as a relation in another

texts:
I have a list of entries and I would like to filter them into 2 lists.

Entries that have been made a relation in another section
Entries that have NOT been made a relation in another section

I thought about tackling this the other way round and listing the section with the relations but some entires are related multiple times, so and the titles in the list get repeated multiple times. Unless this can filter out the duplicates, but it starts to get messy at this point.

Ideas welcome thanks.


texts: How to remove siteName from the og:title tag with SEOMatic

texts:
SEOMatic automatically adds the siteName after your title tag, which seems smart, but I don't think it's necessary for social sharing. Is it possible to tweak the og:title and twitter:title tag output in SEOmatic to remove the siteName?

My current seomaticMeta array looks like this:

{% set seomaticMeta = {
  seoTitle: entry.title,
  seoDescription: entry.shortDescription,
  seoImage: entry.thumbnailImage.first(),
  seoKeywords: '',
  canonicalUrl: entry.url,
  twitter: {
      card: seomaticMeta.twitter.card,
      site: seomaticMeta.twitter.site,
      creator: seomaticMeta.twitter.creator,
      title: entry.title,
      description: entry.shortDescription,
      image: entry.thumbnailImage.first(),
  },
  og: {
      type: seomaticMeta.og.type,
      locale: seomaticMeta.og.locale,
      url: entry.url,
      title: entry.title,
      description: entry.shortDescription,
      image: entry.thumbnailImage.first(),
      site_name: seomaticMeta.og.site_name,
      see_also: seomaticMeta.og.see_also
  }
} %}

However, the entry.title tag returns the title with the siteName appended.


texts: Trigger sent before user is added in user group so no email is sent

texts:
I am trying to send custom welcome emails to custom user groups but Sprout email is attempting to send the notification before the user group is created which means the email isn’t sending. The log just outputs that the user doesn't belong to any user group.

Note: We are using a custom plugin to create the user and trigger a set your password email which could be the problem, is there a way to hook into sprout email so we can trigger the send from our plugin?


texts: How to access Craft.EditableTable instance in CraftCM

texts:
I am developing a custom plugin that has a variable setting that can take multiple options. I've decided to use forms.editableTable from Craft's _includes/forms. It does the job great, saving and retrieving the settings.

Now I am trying to add validation to the columns on the table: the validation model is set and I am correctly passing the errors to the "right" position (Meaning I get the row index and which column has the error).

I know Craft.EditableTable has the getRowHtml method that I can use to retrieve the row and apply error classes to the field(s).

I've watched the Javascript in the Control Panel video, but Craft.EditableTable doesn't set a data attribute with it's instance.

Is there any other ways to get it?

Thanks!


texts: Modify a field value before the element is saved

texts:
I have a simple plugin with a field that extends the Craft PlainText field.

Is there some kind of function I can use to modify the field's submitted value before the element is saved?

class myField extends craft\fields\PlainText
{
    private function modifyPostedValue()
    {
        if ($PostedValue == “foo”)  {
            $PostedValue = “bar”;
            // save “bar” to database
        } else {
            // save “foo” to database
        };
    }
}


texts: Is there a "sticky post" function built into Craft?

texts: How would I make a post(s) sticky so that it appears first in the results and does not repeat later in the results?


texts: How can I display category title inside another category

texts:
I would like to display a list of category.
I can display the information inside a category like slug or title.

However, I dont know how to display a category field inside a category.

    {% for category in craft.categories.group('handle') %}
       <p> {{category.title}} </p>
       <p> {{category.title}} </p>

    {% endfor %}


texts: When a user forgets their password multiple times on one my front-end login screen, they sometimes get locked out of the system until an admin can unlock them in the control panel. Is there any way to prevent this behaviour?


texts:
I have defined an entry for a channel, let's say of persons, to have some fields, let's say firstname, lastname and bio, but no title.

When I created the first real entry, craft complained it had no slug. Apparently, that's drawn from the title.

I expected I could define the structure of the entry's slug to be pulled from any field, like {firstname}-{lastname}.

But I didn't find that option in the backend. Am I looking in the wrong place?


texts: Find entries that use a specific block in their Matrix field

texts:
I am using this solution to get the latest article with a video. This works great, until I delete the Matrix block in my latest entry with video, then it still finds that entry, but without any data. I think Craft does not actually delete the Matrix block from the database?
I did not want to retrieve all items and then filter them in Twig, that's why I used orderBy and one(). How can I skip the Matrix blocks that are empty/deleted??
{% set videoNews = craft.entries .section('news') .leftJoin('{{%matrixblocks}} as matrixblocks', 'matrixblocks.ownerId = entries.id') .andWhere({'matrixblocks.typeId': 5 }) .orderBy('postDate desc') .one() %}

PS I am unable to comment in that thread, so I posted a new question, hope this is the way to go.


texts:
I am trying to edit fields.  When I go to Settings->Fields and then click on a field, I get a message that reads:

Internal Server Error

Craft\Model and its behaviors do not have a method or closure named "availableAssetSources".

Then I looked in the utility logs under server info, it reads:

Level:  error
Category:   exception.Twig_Error_Runtime
Message:    exception 'CException' with message 'Craft\Model and its behaviors do not have a method or closure named "availableAssetSources".' in /home/christen/6989-CLG-Web/craft/app/framework/base/CComponent.php:266

I am including the code written on line 266, in case it helps:

throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',

What does all of this mean and how can I fix it?

Thank you so much!


texts: How can I edit/change an existing customer's email address?

texts:
In Craft Commerce (v3), we have a number of orders of customers with a typo in their email address. I'd like to correct those email addresses in Craft, so I went to commerce -> customers. However, I can't seem to find a way to change an existing customer's email address.
Does anyone know how to do this?


texts: Craft 3: Image transformation - grayscale

texts:
Are there any image manipulation options in Craft 3?

Like grayscale or so?
(what imager does for Craft 2: https://imager.vaersaagod.no/?img=5&demo=basic-image-adjustments)


texts: PHP warning on Guzzle failed to open stream: No such file or directory

texts:
We just deployed Craft to Elastic Beanstalk running on a docker container.
When we revisit the site hours later at random it gives us a warning:

PHP warning

include(/var/www/craft/app/vendor/guzzle/guzzle/src/Guzzle/Http/Client.php): failed to open stream: No such file or directory

Refreshing helps and load the application properly.
Has anybody stumbled with this and so yes would be great if you have some tips!

Thanks


texts: Latest update to Craft 3.1.27 crashed server

texts:
I updated the site locally to 3.1.27  (it is working fine) and moved the vendor files, composer.lock and composer.json to the server.

After the update, I went to the admin and clicked on the "finish up" button. On reload the server crashed with the following errors:

18-May-2019 18:42:16 America/Los_Angeles] PHP Warning:  require(C:\home\site\vendor\composer/../symfony/polyfill-intl-idn/bootstrap.php): failed to open stream: No such file or directory in C:\home\site\vendor\composer\autoload_real.php on line 66

The File "C:\home\site\vendor\composer/../symfony/polyfill-intl-idn/bootstrap.php" is on the server.

I've reuploaded the vendor files as well as the composer.json and composer.lock. Not sure what else to do. Any ideas?

https://www.untye.com/Before-The-Wall/Liner-Notes

Thanks,

Rick


texts: Return entries with startDate or endDate within a calendar year

texts:
I have two date fields in my entry and I want to return those entries with either a start date OR and end date within a calendar year.

I can get those with a startDate within the calendar year using:

{% set nextyear = year +1 %}
{% set yearbegins = '1 January ' ~ year %}
{% set yearends = '1 January' ~ nextyear %}
{% set unixbegins = yearbegins | date("U") %}
{% set unixends = yearends | date("U") %}

{% set entries = craft.entries.section('events').limit(null).startDate('and', '>= ' ~ unixbegins, '< ' ~ unixends) %}

How to I then run a test on endDate to further filter them down?


texts: How to register a new System Message email

texts:
I want to send a welcome email to the user when they sign up (not an activation email).

I can see the email and edit its text in the Control Panel, but the email doesn't send when a new user registers.

Here is my code:

Event::on(SystemMessages::class, SystemMessages::EVENT_REGISTER_MESSAGES, function(RegisterEmailMessagesEvent $event) {
    $event->messages[] = [
        'key' => 'after_activate_user',
        'heading' => 'When someone registers:',
        'subject' => 'Subject',
        'body' => 'Message text',
    ];
});

My question, is there anything else I need to do to get this email to send? Do I need to define a recipient?


texts: Search in checkbox field with pagination

texts:
It seems like this should be a simple thing, but it's evading me... I have a checkbox field in my entry named "articles_categories". Just to clarify, these are not actual categories -- they are checkboxes and I cannot modify them at this point.

I want to use the option value of the checkbox as an exact search parameter. I'm using pagination, so it needs to pass through paginate. This is what I have:

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

{% paginate craft.entries.section('blogArticles').limit(10).search(topic) as pageInfo, pageEntries %}

The option values are being passed as the topic parameter. For example, '?topic=healthcare',  or '?topic=food-fitness'. I'm getting a different set of results from each query, however, I don't believe that this is set up to return an exact match on the value passed through the search function.

I need only the articles that have an exact match in that field.


texts: How do you output the value of a checkbox item?

texts:
Seems like it should be simple but it's not working for me.

{% for option in entry.contributionType %}
     <li> {{ option.value }} </li>
{% endfor %}

This code outputs the option's label instead of  the value. I feel like I'm going crazy.


texts:
I have a Structure called Pages which works great on my localhost. When it comes to deploying the website i'm not sure what the issue is.

Before I deploy; I am running ./craft settings/rebuild. If I check my config/project.yml file it contains this:

sections:
  21e80bf5-5bf0-4acd-89fa-e108f377f367:
    name: Pages
    handle: Pages
    type: structure
    enableVersioning: true
    propagationMethod: all
    siteSettings:
      0bbf44af-5493-45e6-a8fd-711fbf205c27:
        enabledByDefault: true
        hasUrls: true
        uriFormat: '{parent.uri}/{slug}'
        template: pages/page
      62a954cf-14e6-4afc-a4ee-721a1fa504ce:
        enabledByDefault: true
        hasUrls: true
        uriFormat: '{parent.uri}/{slug}'
        template: pages/page
      b24e91d9-c16e-4418-a2be-f784c1a5db73:
        enabledByDefault: true
        hasUrls: true
        uriFormat: '{parent.uri}/{slug}'
        template: pages/page
      dcd40638-52ee-4f8e-944b-be8663f015d6:
        enabledByDefault: true
        hasUrls: true
        uriFormat: '{parent.uri}/{slug}'
        template: pages/page
    structure:
      uid: 3051f9fb-d940-42a7-a2bf-1a4dcfbf0bfe
      maxLevels: null
    entryTypes:
      33ed925f-348c-4c9d-bf8e-a18f36ffa2f9:
        name: Homepage
        handle: homepage
        hasTitleField: true
        titleLabel: Title
        titleFormat: ''
        sortOrder: 2
        fieldLayouts:
          b04b3c2b-b371-4c33-8813-5dd41ba38143:
            tabs:
              -
                name: Content
                sortOrder: 1
                fields:
                  7dfc068b-dcde-47e8-92ab-17054e23cd28:
                    required: false
                    sortOrder: 2
      96020cb2-dbdb-42c7-bcae-66762fd7b98c:
        name: Page
        handle: page
        hasTitleField: true
        titleLabel: Title
        titleFormat: ''
        sortOrder: 1
        fieldLayouts:
          63ce77f0-af11-4304-b21d-c1bc6d0c8bb6:
            tabs:
              -
                name: Content
                sortOrder: 1
                fields:
                  0556df33-f19f-4a6e-a26b-73be1b719674:
                    required: false
                    sortOrder: 1
                  7dfc068b-dcde-47e8-92ab-17054e23cd28:
                    required: false
                    sortOrder: 2

When I deploy my changes and run ./craft project-config/sync the Entries section isn't showing up in Admin.

Am I doing something wrong here?

Is it a problem with the URLs maybe?