texts: Get new level from ElementStructureEvent

texts:
I'm trying to prevent a type of entry from being a root entry (level 1). something like:
    Event::on(
        Entry::class,
        Element::EVENT_BEFORE_MOVE_IN_STRUCTURE,
        function (ElementStructureEvent $event) {
          if ($event->sender->type->handle === 'MY_TYPE' && NEW_LEVEL === 1) {
             $event->isValid = false;
          }
        }
    );

I don't see any information in the ElementStructureEvent about the new level. One workaround I found was to hook into the EVENT_AFTER_MOVE_IN_STRUCTURE, this has the new level as the senders level.
The issue here is that $event->isValid = false; does not work, I assume because the validation happened already, And i have to throw an error to prevent the entry from saving. This works but its ugly, the UI doesn't reflect the state of the structure until you refresh the page.
Is there a better way to achieve this?
Thanks


texts:
I use a responsive image plugin similar to picturefill.

On my local environement it works well, on my live install however the last trasnform isn't applied and I receive a 404. I guess it might be some memory_limit issue, so I wonder if there is a more efficent way to write this:

{% set fullw_trans_xs = { mode: 'crop', width: 767, } %}
{% set fullw_trans_sm = { mode: 'crop', width: 768, } %}
{% set fullw_trans_md = { mode: 'crop', width: 992, } %}
{% set fullw_trans_lg = { mode: 'crop', width: 1200, } %}
<img class="bttr img-responsive" alt="{{asset.title}}"
   data-bttrlazyloading-xs='{"src": "{{ asset.getUrl(fullw_trans_xs) }}", "width" : {{ asset.getWidth(fullw_trans_xs) }},  "height" : {{ asset.getHeight(fullw_trans_xs) }}}'
   data-bttrlazyloading-sm='{"src": "{{ asset.getUrl(fullw_trans_sm) }}", "width" : {{ asset.getWidth(fullw_trans_sm) }},  "height" : {{ asset.getHeight(fullw_trans_sm) }}}'
   data-bttrlazyloading-md='{"src": "{{ asset.getUrl(fullw_trans_md) }}", "width" : {{ asset.getWidth(fullw_trans_md) }},  "height" : {{ asset.getHeight(fullw_trans_md) }}}'
   data-bttrlazyloading-lg='{"src": "{{ asset.getUrl(fullw_trans_lg) }}", "width" : {{ asset.getWidth(fullw_trans_lg) }},  "height" : {{ asset.getHeight(fullw_trans_lg) }}}'
            />

I saw the answer of Brandon Kelly about retina images with that macro thing but frankly, I don't get it. Could that be applied in some way to solve this problem as well?


texts: List subfolders of a specific asset folder

texts:
Is it possible to list subfolders from a specific folder?

Context:
I'm printing out hundreds of icons which are maintained by moving a directory structure directly over to my public assets folder. Currently, I grab and list all icons by looking at the parent folder for icons:

{% for image in craft.assets.source('iconLibrary').limit(null) %}
   <li>...</li>
{% endfor %}

I'd like to call and list them by their individual folder names though. Is there a way to take a specific folder and return a list of subfolders?

Update:
Brad's solution works! Though it's somewhat awkward having to call an image first to start at AssetFileModel. Hopefully this can be optimized as I'm running through a loop like
 the one above for each child folder now—

<!--find image in parent icon folder to access folder via AssetFileModel.-->
{% for image in craft.assets.id('9328') %}
   <!-- get children of that asset's folder -->
   {% for subfolder in image.folder.getChildren() %} //
      {{ subfolder }}   //prints each child folder name
   {% endfor %}
{% endfor %}


texts: How do I access current site handle in Craft 3 controllers

texts:
When my multisite is set up as @web/site, I cannot access the current site handle from my controllers.

Craft::$app->getSites()->currentSite->handle

I think this is because my form action defaults to the root site ie @web/actions/controller... rather than @web/site/actions/controller...

Is there a way to get the current site or do I need to pass it into the controller from the form?


texts: How to display a featured image in the list of entries

texts:
I created a field which uploads an image, and I want it to display it for each of my entries inside my for loop.

What's the code I should use to do it?


texts: Return element criteria model from attribute of a model

texts:
In one of my Plugin's CP templates I am using a element select field to grab elements from a custom element type.  This field saves an array of element ids to a specific record's attribute called "location".  How do you return an element criteria model instead of the array of ids when the model attribute is called via twig?

// Model
protected function defineAttributes()
{
    return array_merge(parent::defineAttributes(), array(
        'location'          => Attributetype::Mixed,
        'specificLocation'  => AttributeType::String,
        'registration'      => AttributeType::Mixed,
    ));
}

// Front end template
{{ craft.pluginname.variable.location }}


texts: How can I use the entry UID in the entry URI

texts:
The entries in my Craft app need a unique ‘non-guessable’ URL, so I figured I could use the UID in the URI of the entry.

So in the section, where I need to provide the URI format I entered "section-name/{uid}".

But this is giving me issues, since when I initially save an entry, the URI is "section-name". I think this is because the UID is not available on creation of the URI.

If I save the element for the second time, my problem is solved and the correct URI is generated.

Is there a way to prevent this issue from happening?

I already thought about creating a route, but that means that I need to generate the URI myself in every template, and this is prone to error and not future proof if we would like to change the URI format.

I also thought about creating a module which saves the entry for a second time when a new entry is saved for that section, but I can't find a way to create the correct event-listener.

Does anyone have a better solution or can help me with the event listener in a module?


texts:
Craft 3.3.8

Commerce 2 Lite Version

If I change the base currency from default(USD) to NZD or AU in the setting

CP > Commerce > Store Settings > Payment Currencies

and browse to /shop/ or /shop/[otherpages] the website shows error:

Invalid Configuration – yii\base\InvalidConfigException
Payment currency not allowed.
1. in vendor/craftcms/commerce/src/elements/Order.php at line 1580

And if I switch it back to USD it works fine. It also works fine if I am a public register.

I need to use NZD only, if not, I'm open to other work arounds using USD.


texts:
I have an entry that has a entries field where 9 entries have been added.

The first three entries are displayed in one block at the top of the page and this works correctly using .limit(3)

However further down the page I expect 6 entries to be displayed when using .offset(3). That is not happening. Instead you only see the next 3 entries, not the next 6. If I change to offset(6) I still see 3 entries but it's the final three entries.

Below is simplified relevant code.

{% for secondaryEntry in entry.secondaryFeatures.offset(3).all() %}

        {{ secondaryEntry.title }}

{% endfor %}

Please advise.

edit
Here is the code calling the first three entries at the top of the page

{% for secondaryEntry in entry.secondaryFeatures.limit(3).all() %}

      more code

{% endfor %}


texts: How to link to previous/next entries in a section?

texts:
What would be the equivalent in Craft of ExpressionEngine's Next/Previous entry linking? I was looking at getNext() and getPrev() (and their aliases next and prev) (via the EntryModel docs), but when I try the obvious:

Previously: {{ entry.prev.title }}

I just get the current entry's data.

What piece am I missing here?


texts: Search return wrong result with special character like æ ø å in Craft 3

texts: I had created search in Craft 3, but it returns wrong result when I enter some special characters in it, for example æ ø å. Looking for the solution.


texts:
Our users were getting a blank white screen on our homepage yesterday. Inspecting revealed it was just an empty page. All other pages on the site worked fine. I ended up clearing the cache and it resolved the issue.

Any idea why the cache would have been serving an empty page instead of the home page?


texts:
I have a front-end registration page and need to change the validation to add (minimum characters for information on the page and to make fields to accept only letters and other to accept only number how can I accomplish this )
if there is any guide or step by step it will be nice ,
thanks in advance
my site is on this link : todo.net
registration page is : todo.net/register


texts: Google Maps plugin - How to trigger an info window

texts:
I'm migrating Smart Map over to the Google Maps plugin, and I want to open a popup on button click. But it seems there is no JS method available to open an info window.
Here's how it was done in Smart Map:

Trigger Info window in Smart Map using external navigation

How can I do the same thing with the Google Maps plugin?


texts: How could I create a button to loop through entries and re-save them?

texts:
I've been working on a plugin that updates entry data based on the results from a json array using entries.onBeforeSaveEntry.

Since this API might put out different information in the future, I would like to create an "update all" button that would cycle through all entries and just save them rather than going through each one and clicking save manually.

Any ideas?


texts: Returning specific fields with elementCriteriaModel

texts:
I'm writing a plugin that adds or updates users profiles in Craft from a JSON file. Every user profile could have a lot of custom fields in the future which store a lot of data.
To check if a user exist and if its data is up to date with the data in the JSON file, I need to retrieve 2 fields from every user profile. Is that possible with the elementCriteriaModel?

I've seen examples of the criteriaModel by which you filter which users are returned by adding parameters. And then you get an array back filled with users that match the criteria and all of their custom fields.

But I need all users returned, but not with all their custom fields. Because I think that will slow things down.
Is it possible to fetch all users but returning only 2 specific fields by using the criteria model? Or some other way?
I know I can filter the results afterwards and return another array, but then the slow database query is allready been made. I want to limit the amount of queries made and the amount of data retrieved to the bare necessities.


texts: "Template not found: dashboard" error on setup

texts:
When setting up Craft CMS I get a 404 error page that says

HTTP 404 - Not Found - yii\web\NotFoundHttpException
Template not found: dashboard

I am running MAMP (PHP 7.2.8 and MySql 5.7.23) on a Mac and followed the installation instructions (using Composer) found on https://docs.craftcms.com/v3/installation.html.

Everything seems to run smoothly until I hit the "Web Browser Setup" part (https://docs.craftcms.com/v3/installation.html#step-6-run-the-setup-wizard), which is where I get the 404 page instead of the setup wizard.

Any clues to what could have gone wrong?

Thanx!


texts:
I am looking into the idea of porting my first site into Craft CMS. It is the site of a friend/client who has a railway engineering consultancy, and it's currently running on another CMS (TidyCMS). Before I dive in and look through all your documentation, I would appreciate some help, just so that I don’t run into a design roadblock further down the road.

There are really only two areas where I am concerned about porting to Craft CMS :

Actualités (News) page :
http://www.study-technologies.com/fr/actualites.html
These are news listings on the page (image + date + title/text), which point to individual article pages when clicked. Can this be done in Craft?

Project pages :
http://www.study-technologies.com/fr/projets-ferro.html
These are project galleries which are dynamically populated as individual project pages are created. An image in the project page is chosen to appear in the gallery grid. Can this be done in Craft?

A few other questions :

Can Craft CMS handle bilingual sites?
Is the Craft CMS admin available in French?
Can my client set up different user permission levels?**

I hope you can answer all of these, and if so, I’ll be diving in right away! I have other clients that I’d like to port over, but this client has the most complex design, so I’d like to use it as a test case.

Thanks,
Ric


texts: Getting "do not have method or closure named" error when trying to eager load

texts:
Below is the full block of code I am working with. This is part of a template for showing all businesses that belong to a sub-category. I need to load all businesses related to the current category, but in addition to that I need to group the businesses by state and list the town each business belongs to. I've asked other questions related to this before. This time I am actively trying to use Eager Loading to load each related town for each business. From there I'm hoping to pull out the state each business belongs to (this needs to be daisy chained, however, from business->town->county->region->state).

The code below results in the following error:

CException
Craft\EntryModel and its behaviors do not have a method or closure named "N".

And finally, here's the code:

    {% block entry_content %}
        {%
            set businesses = craft.entries.section('businesses').relatedTo(category).find({
                with: ['bizTown']
            })
        %}

        {% set state = entry.bizTown.first.townCounty.first.countyRegion.first.regionState.first ?? 'N/A' %}

        {% set businessesByState = businesses|group(state) %}

Businesses with video stories will have the video icon  in front of their names.

                {% if businesses|length %}
                    {% for state, businessesInState in businessesByState %}

{{state}}

                                {% for business in businessesInState %}

                                        {% if business.ytVideoId|length %}

                                        {% endif %}
                                        {{ business.link }}

                                        {% set twn = business.bizTown.first %}
                                        {{twn.title}}

                                {% endfor %}

                    {% endfor %}
                {% else %}

We apologize, we appear to be experiencing some technical difficulties…

                {% endif %}

    {% endblock entry_content %}

There's got to be something simple I'm overlooking, or I could be approaching my problem all wrong. I feel out of my element and could use some advice/wisdom.

Thanks!


texts: Entries grouped by Category and then Sub Category

texts:
Been trying to get this working for a few hours but no joy, hope someone can help.

I'm looking like an post archive of all entries.

Something like

Category1

Sub Category 1

Entry / Entry

Sub Category 2

Entry / Entry

Category 2

Sub Category 3

Entry / Entry

Etc.

Tried with grouping and even tried with a plugin - https://github.com/timkelty/groupby-craft But no luck so far, help greatly appreciated.


texts:
I found this part of code in the documentation

{% set title = "Cocktail Recipes"|t %}

What does |t mean there?


texts: Display parent category with nested child categories and related entries

texts:
I'm struggling to loop through level 1 categories
and display as a category title
and then show nested level 2 categories (via a category title) under which I want to nest related categories
to achieve:
PARENT CATEGORY

CHILD CATEGORY

related entry

related entry

related entry

CHILD CATEGORY

related entry

related entry

related entry

although the content and order is correct, I have divs closing in the wrong place so can't control which content is positioned by flexbox using this code:
{% for category in craft.categories.group('team') %}

{% if category.level == 1 %}

{{ category.title }} LEVEL 1

     {% endif %}

               {% if category.level == 2 %}

               {{ category.title }} LEVEL 2

               {% for entry in craft.entries.section('team').relatedTo(category).all() %}

{{entry.title}}

{{entry.positionTitle}}

{{entry.emailAddress}}

Tel: {{entry.telephoneNumber}}

Mob: {{entry.mobileNumber}}

               {% endfor %}

               {% endif %}

{% endfor %}


texts: What is the best way to format a button macro?

texts:
I'm looking for a solution on the best way to setup a macro for buttons that are defined in a matrix fieldtype.

My current code works fine but it really isn't that DRY and I feel it could be made better.

I first import my button macro in a main template:

{% import "_includes/buttons" as buttons %}

Then my code for the matrix field is:

{% for block in cube.button %}
   {{ buttons.span(block.buttonType, block.buttonText, block.buttonColour, block.buttonSize, block.fullWidthButton, cube.linkUrl) }}
{% endfor %}

And now my not so DRY button macro

{% macro span(type, text, colour, size, fullWidth, url) -%}
    {{ text }}
{% endmacro -%}

{% macro a(type, text, colour, size, fullWidth, url) -%}
    {{ text }}
{% endmacro -%}

{% macro button(type, text, colour, size, fullWidth, url) -%}
    <button class="btn {{ type }} {{ colour }} {{ size }}{% if fullWidth %} btn-block{% endif %}">{{ text }}</button>
{% endmacro -%}

{% macro submit(type, text, colour, size, fullWidth, url) -%}
    <input type="submit" class="btn {{ type }} {{ colour }} {{ size }}{% if fullWidth %} btn-block{% endif %}" value="{{ text }}"/>
{% endmacro -%}


texts: Some orders recieve double amount of products

texts:
I have a pretty critical issue with one of my clients websites.

The site, running Craft CMS 2.7.2 and craft commerce 1.2.1364, uses a event/tickets plugin and uses Mollie as the payment provider.

The problem is the following:

A customer goes to the site, selects an event and adds 2 tickets to their cart. The customer goes through checkout, pays for 2 tickets successfully and returns back to the site, but receives 4 tickets.

The only difference between this bugged order and a normal order (that I can tell anyway) is the status updates. A normal order will have only one status update but bugged orders have three updates in the orderhistory (see screenshot)

This order has purchased and paid for 7 tickets but has received 14 tickets.

The problem seems to be happening randomly from what I can tell.

Any help or information about what the problem could be would be much appreciated.

(Note: we have contacted the plugin owner but have not yet received a response. We also contacted craft support but awaiting a response decided to ask here as well). If we receive any answer/solution we will post it below.

UPDATE: This is the response from Craft support:

Hi Yoshi,

Something in your site setup, or a plugin, is setting the orderStatusId on the order to one that triggers an email. Somehow the status is being set twice.

My guess is, without seeing the email setup or the plugin, that since the same status is set twice, the emails are sending twice. That makes sense, but my guess is that the emails themselves generate the ticket numbers on send, hence the additional tickets being issued.

The plugin developer should have saved the tickets numbers on order complete, and linked them to the order. Then the email could be sent out as many times as needed, without it regenerating multiple ticket numbers.

Hope that helps.

-Luke


texts: Assets Uploader Just Spins and Does Nothing Else

texts:
I am using Craft locally, at localhost:8888 with free MAMP. I am unable to upload images using the Assets uploader. The images in Assets were dropped in manually in their directory.

Permissions for Craft are 774 (/app, /config, /storage)
File system path: /Users/myuser/repos/craft-learn/craftapp/public/assets/i/artists/
URL: http://localhost:8888/assets/i/artists/
version 2.6.2958

What should I check?


texts: Check paginated currentPage before setting the paginate tag

texts:
This might sound counter-intuitive, but I'm trying to set a specific limit; if the currentPage is the first paginated entry.

{% set limit = paginate.currentPage == 1 ? 5 : 8 %}
{% paginate craft.entries.section('news').limit(limit) as articles %}

I know this isn't going to work because I'm querying the paginate tag before I've set it.

So is there a way to set a custom limit for the first page only?


texts: Checking if a value matches an entry type handle

texts:
I am trying to check if a value provided by the user (url segment) matches an entry type, and if not redirect to 404.

{% set section = craft.sections.getSectionByHandle('shop') %}
{% set entryTypes = section.getEntryTypes('handle') %}
{% if not segmentEntryType in entryTypes|keys %}
    {% exit 404 %}
{% endif %}

segmentEntryType is the string from the segment.
i get the error:

An exception has been thrown during the compilation of a template ("Node "1" does not exist for Node "Twig_Node".").


texts:
The admin panel's icon font refuses to load, throwing a 404 along with the full body of the font file. The result looks like this:

I don't know nginx well, but we recently added a change to the config to categorically lock down cross-domain font usage where suddenvalleydevelopment.com is our primary domain and balboatowers.com is another one authorized to use fonts. Relevant lines:

map $http_origin $cors_permitted_domain {
    hostnames;
    default suddenvalleydevelopment.com;
    .suddenvalleydevelopment.com $http_origin;
    .balboatowers.com $http_origin;
}

location ~* \.(otf|ttf|eot|woff)$ {
    add_header "Access-Control-Allow-Origin" "$cors_permitted_domain";
    add_header 'Vary' 'Origin';
}

I'm pretty sure this created the problem you see above, but I don't understand how and therefore how to fix it. We know that Craft stores its own font files at craft/app/resources/fonts, and not in public/admin/resources/fonts like you'd expect from the request.

How does Craft get its icon font (Craft.woff, etc.) to the browser, and why would the CORS provision interfere with that?


texts:
We are updating an old Craft Commerce 2 site to Craft Commerce 3 which features a fair bit of bespoke code from a previous developer. The site features bespoke pricing based on a values stored in/saved to the options variable for line items alongside a bespoke line item event in our module that fetches the relevant price based on the options specified.
However, with the update to Craft 3 these values are not being updated when the cart is updated.
I can see in the documentation that this would instead create a new line item but that isn't happening either.
Any thoughts of experiences of similar? I can see in the POST submission that the updated options are being sent but the item record is not changing.


texts:
I have a section with an text field and an image field. the asset field may sometimes be left blank. in this case, in my template, i want to grab the image from another random entry.

This is the code I'm trying to use, but when the image field is blank in my initial entry, I'm getting an error that Variable "image" doesn't exist.
Am I calling the random image incorrectly?

{% for stat in craft.entries.section('statistics').limit(1).order('RAND()') %}
{% if stat.image|length %}
    {% set image = stat.image.first() %}
{% else %}
    {% for random in craft.entries.section('statistics').limit(1).image(':notempty:').order('RAND()') %}
        {% set image = random.image.first() %}
    {% endfor %}
{% endif %}

{{ image.url('medium') }}')

{% endfor %}


texts:
I just realized that my page is also accessible when there is a .html extension on the url.

The url would be:
http://musikwerkluzern.ch/programm

but http://musikwerkluzern.ch/programm.html works as well but some tags are not being rendered with the html extension attached.

And for some reason the google search results link to the page with .html attached.

That's bad. How can I prevent this? Is this a .htaccess thing?


texts: How fixed are the ICC profile in core app?

texts:
Will ICC profiles here always be a core part of Craft app?
/craft/app/vendor/pixelandtonic/imagine/lib/Imagine/resources/Adobe/CMYK


texts: Output random blocks from a matrix but without the first

texts:
I have quotes inside a global matrix which i want to output randomly on the homepage but without the first quote-block. this does not work:

{% set quotes = city.cityBlocks.offset(1) %}
{% set randomQuotes = quotes.limit(1).order('RAND()') %}

the offset in 'quotes' works fine but the first block is still in randomQuotes anyway.


texts:
Am I completely stupid or have the e-mail settings been removed after an update?
I am searching for the text E-Mails they are sent if a new User is created, someone has his Passwort forgotten and so on… I am really sure that i saw this already but where?

Thanks for any help!


texts: Updating fails (except it does indeed update)

texts:
Updating Craft (and sometimes plugins like Commerce) through Craft 3 admin gives errors. Usually undefined, but have gotten "Backend fetch failed" most recently. Once I refresh the window, it seems to be updated. Since the prior update pseudo-failure there was a message about maintenance mode and a button to continue (which I'm assuming is a flag set somewhere from the prior update). It's a live site on shared open_basedir hosting and proc_open() disabled—which is accounted for in the general config, disabling backups when updating.

Anybody experience this and/or have a solution? All the folder permissions and so forth look correct.


texts:
I'm making a change to the CP so that clicking an asset thumbnail from the asset preview HUD will open the asset in a new tab. Specifically, I'm changing line 1685 of craftcms/cms/src/elements/Asset.php to this:

url . '" target="_blank" style="width:100%;height:100%;position:absolute;">';
This achieves what I want, but it's obviously not the right way to do it. My question is, what is the right way? Can I do this with a module as opposed to a full plugin?


texts: Craft Commerce 2.0.2 Shipping Rule Names & Descriptions—How?

texts:
I just noticed I had to update some templates after updating to the latest Commerce version (2.0.2).

How does one go about getting the method's rule description?

I currently have it set up to apply a rule based on geographical shipping location (like contiguous US states / Hawaii and Alaska / Russia / World / Oceania)—but {{ method.description }} from within {% for handle, method in cart.availableShippingMethods %} breaks the site.

Cheers!


texts: There seems to be an issue with HelveticaNeue in chrome, on Windows 7. If I manually edit the fontface using dev tools I can get the text to display in the default font. Doing a bit of searching online and this seems to be a bit of chrome bug for certain people, so is there any way to change the font altogether for the cp? Or a chrome fix?


texts: Entries search without using asset fields

texts:
I have a search form on a website to search through all the entries of the website and return the entries that match the search query.

But the search query is also used on asset fields within an entry. Which for the companies channel results in many entries found when you search on the word: logo.

I like to know if there is a way to search through all the fields of an entry, but without looking through the asset field type?

So for the companies example, I only want to find entries that match the word: logo. When that word is in the content text, and not in an asset name/title.

My code now is this, but it returns the asset fieldtype result as well:

{% set entries = craft.entries({ section: 'not comments' }).search( query ).order('score') %}


texts: Internal server error in Admin after migration

texts:
I'm setting up a website using Craft Cms.

Everything was working fine on local dev, but now I moved it to a development server, I'm getting an error every time I try to create a new entry (or section).

When devMode == false I get:

  CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]:
  General error: 1785 Statement violates GTID consistency: Updates to
  non-transactional tables can only be done in either autocommitted
  statements or single-statement transactions, and never in the same
  statement as updates to transactional tables.. The SQL statement
  executed was: INSERT INTO craft_searchindex (elementId,
  attribute, fieldId, locale, keywords) VALUES (:elementId,
  :attribute, :fieldId, :locale, :keywords) ON DUPLICATE KEY UPDATE
  keywords = :keywords. Bound with :elementId='61',
  :attribute='field', :fieldId='1', :locale='en', :keywords=''


texts: What's the trick to importing an entry with a categories field?

texts:
We are using Hampsink's Import plug-in (0.8.33) and we have a very simple CSV for testing. One row, three columns. One of these columns contains a comma-separated list of categories. These are top level, no heiarchy.

We've tried the titles:

Provider Id,Provider Name,Service Areas
62686,Walgreens,"Defiance County,Erie County,Fulton County,Henry County,Lucas County,Ottawa County,Paulding County,Sandusky County,Williams County,Wood County"

We've tried the slugs:

Provider Id,Provider Name,Service Areas
62686,Walgreens,"defiance-county,erie-county,fulton-county,henry-county,lucas-county,ottawa-county,paulding-county,sandusky-county,williams-county,wood-county"

Category field always ends up blank after an otherwise successful import.

Yes, categories are set and have their own URL. Since there is no heirarchy, that is set to simply {slug}

We've read the several, several related posts and questions about this and there seems to be a lot of frustration around importing entries with categories. Yet still... What are we doing wrong? What's the trick?

Craft CMS 2.6.2931


texts:
When a payment is made and something is incorrect e.g. card number is invalid, expiry date is in the past etc. The form just refreshes with no warning / notification of what's happened.

I've noticed that this message is stored in the CMS on each order, under the "Message" column (e.g. Card Has Expired)

Is there a way to output this message in to the template when the error occurs? Even on the example templates it does this issue.


texts: All URLs changed path after upgrading to 3.6?

texts:
I'm not sure exactly what has changed here. All links are directing to "site.test/admin/site.test/blog/{slug}", when clicking on the link from the entry page. Before they would be "site.test/blog/{slug}". All links across the entire site are doing this. Is there a new variable or setting I need to change?
I have the sites 'Base URL' set to an .env variable, $PRIMARY_SITE_URL which I then have set as 'site.test'


texts: Include the URL of a related entry field

texts:
I would like to add the URL of the channel entry I have selected (atm 2 channels are available to choose from), so I would like a url like:

summerhouses/product1

or

greehnouses/product2

how would I modify the code below to achieve this?

The code below just shows: /product1

{% for row in entry.homeFeaturedProducts.order('RAND()')|batch(4) %}
{% for entry in row %}

{{ entry.title }}

    Product Description
    {{ entry.price }}
{% endfor %}
{% endfor %}


texts: Unable to backup the database or apply migrations

texts:
I'm running CraftCMS via 3 Docker containers in 1 Docker network:

Container 1 - MySQL
Container 2 - Nginx
Container 3 - PHP:7.4-fpm

When I run php craft update craft from container 3 and choose to backup the db, I get this error:
Backup the database? (yes|no) [yes]:yes
Backing up the database ... error: The shell command "mysqldump --defaults-extra-file="/tmp/hvncbmcornry.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --default-character-set=utf8 --set-charset --triggers --no-tablespaces --single-transaction --no-data --result-file="/app/storage/backups/my-site--2021-05-26-052145--v3.6.15.sql" craftcms && mysqldump --defaults-extra-file="/tmp/hvncbmcornry.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --default-character-set=utf8 --set-charset --triggers --no-tablespaces --no-create-info --ignore-table=craftcms.assetindexdata --ignore-table=craftcms.assettransformindex --ignore-table=craftcms.sessions --ignore-table=craftcms.templatecaches --ignore-table=craftcms.templatecachequeries --ignore-table=craftcms.templatecacheelements --ignore-table=craftcms.cache --ignore-table=craftcms.templatecachecriteria craftcms >> "/app/storage/backups/my-site--2021-05-26-052145--v3.6.15.sql"" failed with exit code 127: sh: 1: mysqldump: not found

It looks like the mysqldump command doesn't exist in Container 3 as I don't get a result when running: which mysqldump. Running this which command from container 1 does however return: /usr/bin/mysqldump. But in this container, I don't have access to my project.


texts: How to get entries related to current category only (not children)

texts:
I need to get entries which are only in current category, not child categories.

So if I have a category structured like this:

Food
----Fruit
-------Apples
-------Bananas

I've got a categories template and I'm on the page for the Fruit category I want to know whether there's any entries just in the Fruit category and not all the entries in the Apples and Bananas categories.

Current I'm doing this

 craft.entries.relatedTo(category)

But I'm getting all the entries from the children categories as well, how do I get only the entries related to this specific category not child categories?


texts:
I want to add a batch filter with a variable number depending on a conditional. Is this even possible this way:

{% if category.id == '647' %}
    {% set nr = '5' %}
{% else %}
    {% set nr = '4' %}
{% endif %}

{% for batch in craft.entries.section('xy')|batch('{{ nr }}') %}
    {{ batch.title }}
{% endfor %}

This doesn't work. How should I write {{ nr }} or is it impossible due to things like parse order?


texts: HTTP 500 Error after trying to update to Craft 3.1.1

texts:
I just tried to update Craft to 3.1.1 from within the CP. The install failed and I got an Internal Server 500 error. I now can't load either the front or backend of the site, I get a 500 error in both cases. The phperror log shows these errors:

[18-Jan-2019 06:03:54 America/Los_Angeles] PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 14680096 bytes) in /home/vps/proto.site.com/craft/vendor/composer/composer/src/Composer/Util/RemoteFilesystem.php on line 300
[18-Jan-2019 06:03:54 America/Los_Angeles] PHP Fatal error:  Uncaught yii\base\InvalidRouteException: Unable to resolve the request "templates/render-error". in /home/vps/proto.ibiscycles.com/craft/vendor/yiisoft/yii2/base/Module.php:537
Stack trace:
#0 /home/vps/proto.site.com/craft/vendor/craftcms/cms/src/web/Application.php(284): yii\base\Module->runAction('templates/rende...', Array)
#1 /home/vps/proto.site.com/craft/vendor/yiisoft/yii2/web/ErrorHandler.php(108): craft\web\Application->runAction('templates/rende...')
#2 /home/vps/proto.site.com/craft/vendor/craftcms/cms/src/web/ErrorHandler.php(132): yii\web\ErrorHandler->renderException(Object(yii\base\ErrorException))
#3 /home/vps/proto.site.com/craft/vendor/yiisoft/yii2/base/ErrorHandler.php(262): craft\web\ErrorHandler->renderException(Object(yii\base\ErrorException))
#4 [internal function]: yii\base\ErrorHandler->handleFatalError()
#5 {main}
  thrown in /home/vps/proto.site.com/craft/vendor/yiisoft/yii2/base/Module.php on line 537

I have successfully updated Craft via the CP over the last couple of months, this is the first time it's failed. I also updated the php.ini memory_limit to 512M (from 256M) and the max_execution_time to 300 (from 30) after the update failed but I still can't view either the front end or CP.

I'm in the middle of migrating a site from Expression Engine to Craft, this is kind of worrying! I've never see a complete failure like this without any indication of what the problem is.

Thanks for any help.


texts: Issue with uploading files from frontend

texts:
I'm currently trying to implement a simple file-upload form with CraftCMS.

However, even though there are no errors on submitting the form, no file actually seems to get uploaded.

This is the form:

<form action="" method="post" accept-charset="UTF-8" enctype="multipart/form-data">
        <input type="hidden" name="action" value="entries/saveEntry"/>
        <input type="hidden" name="sectionId" value="29">
        <input type="hidden" name="enabled" value="1">

        <input type="file" name="useruploads" style="margin-bottom: 30px"/>

        <select class="form-control" id="sel1" style="margin-bottom: 30px">
            <option>x-challenge auswählen</option>
            {% for entry in craft.entries.section('challenges') %}
                {% for ch in entry.allOverChallenge %} %}
                    <option>( Tirol ) {{ch.allOverName}}</option>
                {% endfor %}
            {% endfor %}

            {% for entry in craft.entries.section('xSpots') %}
                {% for ch in entry.standaloneChallenges %} %}
                <option>( {{entry.title}} ) {{ch.standaloneName}}</option>
                {% endfor %}
            {% endfor %}
        </select>

        <input type="text" class="form-control" id="challenge_select" placeholder="Titel eingeben" style="margin-bottom: 30px">

        <textarea class="form-control" rows="5" id="challenge_description" placeholder="Beschreibung eingeben" style="margin-bottom: 30px"></textarea>

        <input type="text" class="form-control" id="challenge_customtags" placeholder="Hashtags ( max. 3 )" style="margin-bottom: 30px">
        <div style="margin-bottom: 30px">
            <input type="reset" value="abbrechen">
            <input type="submit" value="hochladen">
        </div>
    </form>

I'm attaching two screenshots that show both the actual field and the section:

When submitting the form in it's current state, no entries actually get added to the field as shown in the image below. Am I doing something wrong here? I'd appreciate some help on the topic.


texts:
We are setting our Cache-Control headers in the layout file for all templates.  However some templates the Cache-Control is being overridden.  Why might this be?

{% set expiry = now|date_modify('+10 minutes') %}
{% header "Cache-Control: max-age=" ~ (expiry.timestamp - now.timestamp) %}
{% header "Pragma: cache" %}
{% header "Expires: " ~ expiry|date('D, d M Y H:i:s', 'GMT') ~ " GMT" %}


texts: Is there any way to add memcache servers to use per environment? I mean, one server for dev, one for staging and one for production.


texts: Gatekeeper/Knock Knock Pluging not working

texts:
I feel like there must be something i've missed but i've followed the ReadMes for both of these plugins and they don't seem to work on my website. Does anyone have any experience with them?

I'm using Craft 3 and used the plugin store to install them. I have tried them one at a time so that they don't interfere with each other. I've also made sure the site environment is set to production.

Gatekeeper:
https://github.com/tomdiggle/craft-gatekeeper/blob/v1/README.md

Knock Knock
https://github.com/verbb/knock-knock

Thanks


texts:
Ok this should be pretty simple I feel! But I can't find the documentation for it.

I can set assign a user to a user group within a plugin with:

craft()->userGroups->assignUserToGroups($userid, $groupid);

How do I do the reverse and remove a user from a user group?

Cheers.


texts: Show Live Preview even if whole page is disabled

texts:
The whole page is disabled in the backend. Like in this screenshot:

Now I can't see anything in the Live Preview.

My code starts with: {% for entry in craft.entries.section('aboutus') %}

If I set .status(null) I see everything in the Live Preview, but also the entries which are disabled.

So is it possible to show a disabled page in a Live Preview but not the disabled entries of this page?

UPDATE

In the Live Preview I can see all outside of this for loop {% for entry in craft.entries.section('aboutus') %} but nothing inside.

I uploaded my code here.


texts:
I want to redirect http://example.com to coming-soon.html template, but not index.html.

Possible to do it in route settings?


texts: Order Sprout Forms by field handle returns an error

texts:
For some reason Sprout Forms entries will not accept the usual order by field handle setup. When I want to order the contact entries by address for instance:

{% for formEntry in craft.sproutForms.entries.formHandle('contact').order('address') %}
    {{formEntry.address}}
{% endfor %}

I get the error:

  Column not found: 1054 Unknown column 'address' in 'order clause'

This field does exist. If I remove 'order', it parses the field


texts: How to: Flexible Twig Templates in Craft

texts:
I am just starting out with Craft CMS.

What I see right now is a lot of static content in the html templates. Even in the demo.

{% block content %}

{{ entry.title }}

{{ entry.body }}

Recent News

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

{{ entry.title }}

    {% endfor %}

{% endblock %}

You see, that is very static. Is there a way to make it all more flexible and dynamic?

I want my site to be totally flexible so that users can change the outcome completely with dragging and dropping sections in the admin area.

I only want to define HTML for a field / section. Then, I would simply need to loop all fields through and load the html template for each section that is being used.

This would allow massive reusability of these 'content boxes' everywhere. Basically, it'll become drag and drop website building to a large extend.

Do you have some advice on how to do this best?

Basically this guy is talking about it: https://mijingo.com/products/screencasts/reusable-twig-templates-craft/


texts: How to add two variables into one conditional

texts:
I'm using Freeform Pro to manually output a select field, but I think my question is a general Craft/Twig conditional question so I'm posting it here.

The option values in my dropdown field are made up of two variables outputted together - an entry title and a category title.

I'm trying to add a conditional for the 'selected' state of the dropdown but I can't get the conditional to work as I'm not sure of the proper syntax to for a concatenated value like this.

I've tried each of the following but none of them work:

<option value="{{ entry.title }} {{ category.entryAlternativeTitle }}" {% if requestTeam.value == 'entry.title category.title' %}selected{% endif %}>{{ entry.title }} {{ category.entryAlternativeTitle }}</option>

<option value="{{ entry.title }} {{ category.entryAlternativeTitle }}" {% if requestTeam.value == entry.title category.title %}selected{% endif %}>{{ entry.title }} {{ category.entryAlternativeTitle }}</option>

<option value="{{ entry.title }} {{ category.entryAlternativeTitle }}" {% if requestTeam.value == entry.title ~ category.title %}selected{% endif %}>{{ entry.title }} {{ category.entryAlternativeTitle }}</option>

<option value="{{ entry.title }} {{ category.entryAlternativeTitle }}" {% if requestTeam.value == {{ entry.title }} {{ category.title }} %}selected{% endif %}>{{ entry.title }} {{ category.entryAlternativeTitle }}</option>

Thanks for any help with this.


texts: Do 404s get access to variables set with setRouteVariables?

texts:
I have a plugin with nothing but the following in the init() method other than the basics (just for testing purposes):

craft()->urlManager->setRouteVariables(array(
    'foo' => array('bar' => 'baz')
));

From all of my routes I can access this just fine. It's working for static templates, dynamic entries, etc. To access it I'm using the following code in my main base template /_layouts/base.twig:

{{ foo.bar }}

The output is as expected: baz

However, I cannot access this from a page that does not exist, i.e., a 404. If I go to my-site.com/doesnt-exist I receive the following:

Twig_Error_Runtime

Variable "foo" does not exist in "_layouts/base" at line 1

My 404 template is extending base as well.

What am I doing wrong?

It's probably worth noting that the reason I'm trying to do this is because I want to include a form on the 404 page (that I also include in other areas, so it's setup as a partial) and I'm having trouble passing error validation back and forth with setRouteVariables, but only for 404 pages. I know I could do this with a session and that is my current work around, but I wanted to see if there was a better way.


texts: Modifying the search order “Score” criteria

texts:
I'm a Craft newbie, just searching for something and spotted this related post Search order "Score" criteria

What I would like to know, is there a way to add a Modifier value to a field, like LOW Search does for EE?

For example; lets imagine we want trees listed first.

We would add a 'keyword' field, and a modifier value too help ensure a far higher score than any other fields, possibly including the title.

So an entry with the words 'Top Trees' in our 'keyword' field would trump all other entries containing the words 'Top Trees'.


texts: What is the correct way to use UserIdentity?

texts:
I am planning to create a micropub plugin so that any micropub client can post to craft, particularly useful for automatic data logging and mobile clients. But I am trying to work out the best way to authenticate.

I have read through the UserIdentity docs but I was wondering if anybody has an examples of how to use it correctly?


texts: Modifying a GraphQL element query using a custom field

texts:
There’s an address field plugin that doesn't yet support GraphQL, but I'd like to re-create something that I could do using Twig in GraphQL based on this plugin’s custom field.
In Twig you would do something like this:
craft.entries.myAddressHandle({target: 12345, distance: 25}).all()

The results would be the returned entries are filtered down based on the custom field factoring in the target and distance arguments.
From a high level, what has to be done in a module or a plugin to allow something like this?
entries(myAddressHandle:{target: 12345, distance: 25}) {
    title
  }
}

I was able to add arguments to the custom field output using the EVENT_DEFINE_GQL_TYPE_FIELDS event, but that doesn't seem like the thing that adds myAddressHandle to the schema for an entries query. The other events in the Gql service don't seem to do this either, right?


texts:
I'm trying to use <input type="hidden" name="entryId" value="{{entry.id}}"> on a GuestEntries form. However, instead of editing the entry with the set ID, it creates a new post.

Am I missing something? Or is this not possible with the GuestEntries plugin.


texts: Cannot declare class because the name is already in use

texts:
I'm trying to port a Craft 2 plugin to Craft 3, and don't seem smart enough to work out the namespaces. I've stripped out everything except what the docs recommend, but keep getting Cannot declare class kr37\Calendar37\Calendar37, because the name is already in use  Thank you in advance for any suggestions.

Folder structure

composer.json
src/Plugin.php

Plugin.php

namespace kr37\Calendar37;

class Calendar37 extends \craft\base\Plugin
{
    public function init()
    {
        parent::init();

        // Custom initialization code goes here...
    }
}

composer.json

{
  "name": "kr37/calendar37",
  "description": "Event calendar with unrestricted repetition",
  "version": "3.0.18046",
  "type": "craft-plugin",
  "minimum-stability": "dev",
  "require": {
    "craftcms/cms": "^3.0.1"
  },
  "autoload": {
    "psr-4": {
      "kr37\\calendar\\": "src/"
    }
  },
  "support": {
    "email": "???"
  },
  "extra": {
    "handle": "calendar37",
    "name": "Calendar",
    "developer": "???",
    "developerUrl": "???",
    "hasSettings": "true",
    "hasCpSection": "true"
  }
}


texts: Matrix Field - variable entry does not exist

texts:
I'm trying to loop a Matrix field that has one block containing 3 items.

{% for block in entry.galeria.type('itemsGaleria') %}
    {% if block.titulo|length %}
        {{ block.titulo.first }}
    {% endif %}
{% endfor %}

But Craft always throws the error variable entry does not exist.

I read the Matrix section from Craft 3 docs but cannot fix this problem.

Any clues?


texts: Deleted matrix block means deleted data?

texts: If I delete the Matrix block content (while editing an entry) does the associated is deleted as well or only the block but its data still remains in db?


texts:
Is it possible to hide the week start day on the 'Account' tab?

I'm about to import 400+ members and don't want to confuse them with this unnecessary setting (from their perspective).

Thanks in advance.

Adam


texts:
I've built a product filtering system using tags and currently have 2 available tag groups under different fields. Size and Type

Currently if I select 1 tag from both size and type, it shows all products with either selected, however I want it to only show if the product contains both tags.

{% set query = craft.request.getQuery() %}
{% set selectedTagsIds = query.tags ?? [] %}

{% for tag in craft.tags.group('size').all() %}
    {% set checkedAttr = tag.id in selectedTagsIds ? 'checked' : '' %}
    <input type="checkbox" name="tags[]" value="{{ tag.id }}" {{ checkedAttr }}>{{ tag.title }}</input>
{% endfor %}

{% for tag in craft.tags.group('type').all() %}
    {% set checkedAttr = tag.id in selectedTagsIds ? 'checked' : '' %}
    <input type="checkbox" name="tags[]" value="{{ tag.id }}" {{ checkedAttr }}>{{ tag.title }}</input>
{% endfor %}

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

{% for id in selectedTagsIds %}
    {% set relatedToParam = relatedToParam|merge([{
        targetElement: id
    }]) %}
{% endfor %}

{% set relatedToParam = relatedToParam|length > 1 ? relatedToParam : null %}

{% set entries = craft.products.type('accommodation').relatedTo(relatedToParam) %}

{% for product in entries %}
    // Product content here
{% endfor %}

Is there a way I can modify what I have above to make it so that if user selects an option from each tag group, that it only shows products with both selected tags? And if more than 1 of each group are selected to show those too?

I've based my current code based off this answer.


texts: How can I debug `craft\web\User::_validateUserAgentAndIp()` warnings

texts:
On a production site, we're seeing a ton of the following warning in our web.log files for (seemingly) every request, creating a ton of noise in the logs and making it hard to spot "real" issues:

<DATE> [-][-][-][warning][craft\web\User::_validateUserAgentAndIp] Request didn’t meet the user agent and IP requirement for maintaining a user session.

Under the hood craft\web\User::_validateUserAgentAndIp() does the following

private function _validateUserAgentAndIp(): bool
{
    if (!Craft::$app->getConfig()->getGeneral()->requireUserAgentAndIpForSession) {
        return true;
    }
    $request = Craft::$app->getRequest();
    if ($request->getUserAgent() === null || $request->getUserIP() === null) {
        Craft::warning('Request didn’t meet the user agent and IP requirement for maintaining a user session.', __METHOD__);
        return false;
    }
    return true;
}

As far as I can see, (for front end templates at least) craft.app.request.userAgent and craft.app.request.userIP are correctly populated with the UA and IP respectively, so I'm not sure why/how Craft is throwing this warning.

We don't see the same issue in dev / staging environments, so I know this is likely to be a configuration issue, but I'm asking this question to try and understand what's going on so I have some idea of what to look for.

Question:

What should I look for / how can I debug what's causing this issue?

(Note: I know I could turn requireUserAgentAndIpForSession off in config/general.php, but I don't really want to do that from a security POV)

Notes:

This is on a site running Craft 3.3.13 (latest at time of writing)
It's in a load-balanced environment
We're using nginx as our webserver


texts: Is it possible to install Craft on a cPanel temp user URL?

texts:
When you create an account in cpanel you can use a URL to access it like http://ip/%7Eusername/, which is basically http://ip/~username/. Since the client is not ready to take down their old site and we are moving hosts, can Craft run on a URL with the ~username or %7E in the URL? They do not have a dedicated IP unfortunately. Thanks in advance.

I know the license will be needed, but can we change the URL to the real one when ready to go LIVE?


texts: Best practices to name Matrix fields handles

texts:
About matrix block fields handles: should they be unique ?

For instance if I have a matrix with handle galleryMatrix,
than should I name my block galleryMatrixImage or just image?
And than my fields in my block: galleryMatrixImageName, galleryMatrixImageAsset or name and asset?

I'm not quite sure about how to manage these handles the proper way?

I would prefer being able to name them with short handles, but i'm not sure if they have to be unique within a block, or unique for a whole website ?

Thanks


texts: Can you insert Craft variables into SCSS files and have a plugin generate CSS?

texts:
I'm using SCSS to write all of my styles and am currently using Codekit for processing it. I want to be able to add some global variables to Craft so I can change color and font vars, which would then be re-compiled into CSS for the site.

Looking through the plugins, I've found the Sprockets port (https://github.com/rkingon/Craft-Plugin--Sprockets/) and AutoMin (https://github.com/aelvan/AutoMin-Craft/). They both look like they'll take a bit to get set up so I wanted to see if I could get some input before I dive in.

My questions are:

Is what I want to do possible? With either one or both, can I set vars in the CMS that are then pulled into a _config.scss file, which is in turn imported into my main.scss file, compiled, and then fed to the browser automatically? I've tried pulling a craft color var into the main css file but it did not replace the twig syntax with the hex color.
Would one of the plugins is better suited to my needs than the other?


texts: Error when calling methods between two services (triggered by init)

texts:
I have two Services in my plugin. MyPluginService is the "main" service, and MyPlugin_OtherService accomplishes some other tasks (when it is occasionally needed).

There is an init method in MyPluginService which starts a chain of events, and under certain circumstances will call a method in MyPlugin_OtherService.

MyPluginService

public function init() {
    parent::init();
    if ("conditions are met") {
        craft()->myPlugin_otherService->methodInOtherService();
    }
}

public function methodInMainService() {
    // ...
}

MyPlugin_OtherService

public function methodInOtherService() {
    craft()->myPlugin->methodInMainService();
}

While the method in MyPlugin_OtherService is being run, it will refer back to a method in MyPluginService. This is where the error is triggered:

  Fatal error: Call to undefined method stdClass::methodInMainService()

I don't understand why it's not recognizing that call to the main service method. Hasn't the main service already been initialized before this point? There is a lot about "lazy loading" that I don't understand, maybe this falls in that knowledge gap.


texts: Check user is in User Group / Custom User Permissions

texts:
I'm trying to restrict access to items in a channel using some form of custom user permissions however I don't appear to be able to create or set custom read permissions for a channel using crafts permissions as they currently are, I'm therefore trying to do something using either user groups or custom fields on the user and validate if a user has access that way.

I'm hoping this is along the right lines, although it doesn't seem ideal, so is it possible to check if a user is in a certain user group elegantly using twig?

I can do {{ if currentUser.admin }} and I'm guessing I could therefore do something like {{if 'groupnamewithaccess' in currentUser.groups }}


texts: Migrate forms from EE2 Freeform to Craft 3 Freeform

texts: I need to migrate some forms from Freeform in ExpressionEngine 2 to Freeform in Craft 3. Do you know of any tools or methods that exist that can help me out with this? Or am I doomed to do this manually?


texts:
We have a site that is running event pages, that will show live content (via Ustream or similar). Users have to be reg'd and logged in to view content.

We would like to establish who is online and how many logged in viewers at the time of the event. Is there a function that will display this to admin users?

Thanks
Dan


texts: Send Password Reset Email to all users at once

texts:
I have a bunch (about 3000) of imported users from a website, which is currently on a redesign.
When the site is finished, I would like to send an email to all users,
saying that the site is relaunched, has a new structure ect. and therefore they have to set a new password.

I found nothing in the Craft settings, as well in the forum.

Do I have to write a plugin?
Or can I achieve this with the Sprout Email plugin?
I saw, there is a event "When a user logs in".

This could also work for me: a users logs in and gets automatically
to the a page to set a new password.


texts: Re-render Widget after column number changes

texts:
Is it possible to automatically re-render a widget after the number of columns is changed? I have a widget that has to be re-rendered/re-executed after the widget columns change and I don't know how to realize it.

I can't just make a javascript event like $(window).resize() because I already have this function and check if the client client height changes there because otherwise it would trigger every second for no reason.


texts: Inserting Multiple Block Types in one div row

texts:
I have a matrix with a block type call pageRelatedContent. A user can add multiple block to their entry. I am trying to put all the pageRelatedContent blocks in one div row. For this example, I have three pageRelatedContent blocks in this entry. My code is generating three separate rows. Its a coding thing that I am missing. Can someone please assist.

Here is the rendered HTML:

Here is the desired output:

Here is my code. I can see that it is creating a row for every block, but I can't seem to figure out how to insert all the block in one row.

    {% case 'pageRelatedContent' %}
{% set relatedContentBlocks = entry.memberCommunicationsPageContent.type('pageRelatedContent') %}
{% if entry.memberCommunicationsPageContent.type('pageRelatedContent')|length == 1 %}
    {% set colSize = 12 %}
{% elseif entry.memberCommunicationsPageContent.type('pageRelatedContent')|length == 2 %}
    {% set colSize = 6 %}
{% elseif entry.memberCommunicationsPageContent.type('pageRelatedContent')|length == 3 %}
    {% set colSize = 4 %}
{% endif %}

                {% set relatedBlockInfo = relatedContentBlocks|batch(colSize) %}
                {% for blocks in relatedBlockInfo %}

                             {{ block.relatedContentTitle }}

                                        {% for row in block.relatedLinkInformation %}

{{ row.linkTitle }}

                                        {% endfor %}

                {% endfor %}

Here is the matrix information:


texts: How to Fix Error 403 Attempting to Access Craft Admin Page Using XAMPP

texts:
I'm using XAMPP for the very first time and am also new to Craft so any help with this issue would be very much appreciated. I'm attempting to set-up a local dev environment through XAMPP and then be able to make content changes via Craft. I found this set-up guide for MAMP / Craft CMS and have followed it step by step except adapting it for XAMPP:

http://unakravets.tumblr.com/post/58150139083/the-absolute-beginners-guide-to-setting-up-craft

At the end, when I attempt to go to localhost/Craft/public/admin to access the Craft Admin Panel, I get the following message:

Access forbidden!

You don't have permission to access the requested object. It is either read-protected or not readable by the server.

If you think this is a server error, please contact the webmaster.

Error 403

localhost
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3

What could be causing this and what can I do to fix it?

Thanks in advance for any help!


texts:
When attempting to backup with Craft, the system returns the following error:
The shell command "mysqldump --defaults-extra-file="D:\local\Temp\my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --default-character-set=utf8 --set-charset --triggers --no-tablespaces --single-transaction --no-data --result-file="D:\home\site\wwwroot\storage\backups/feedme-210122_193236_orhnxunfoa.sql" tusabcraft && mysqldump --defaults-extra-file="D:\local\Temp\my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --default-character-set=utf8 --set-charset --triggers --no-tablespaces --no-create-info --ignore-table=tusabcraft.craft_assetindexdata --ignore-table=tusabcraft.craft_assettransformindex --ignore-table=tusabcraft.craft_sessions --ignore-table=tusabcraft.craft_templatecaches --ignore-table=tusabcraft.craft_templatecachequeries --ignore-table=tusabcraft.craft_templatecacheelements --ignore-table=tusabcraft.craft_cache --ignore-table=tusabcraft.craft_templatecachecriteria tusabcraft >> "D:\home\site\wwwroot\storage\backups/feedme-210122_193236_orhnxunfoa.sql"" failed with exit code 2. - Connection.php: 597.

Backups worked fine when using MySQL in-app, but it is now connecting to an external MariaDB. Everything except this works fine on the installation. Looking up exit code 2 indicates a permission issue, maybe connecting to the DB?
Has anybody dealt with this? The most helpful thing I could find in the docs was this, but not sure how to implement it:
https://craftcms.com/docs/3.x/config/config-settings.html#backupcommand


texts:
Tags are used to categorize blog post topics.

How can I delete or manage unused tags?

For example, one user created a "Success Factors" tag and another created a "SAP SuccessFactors" tag. The goal is to remove one of these to keep the categories tight.


texts:
I'm getting an error when I start the installation process, i.e., <domain>/admin.

Here's the error I'm getting:

CDbCommand failed to execute the SQL statement: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected. The SQL statement executed was: SHOW TABLES LIKE 'craft_%'

Since I've enabled dev mode, you can see the full stack trace here:

http://onehanders.info/admin

I've done the following prior to starting the install:

set up db and identified server, db name, user, & password that are needed
put proper settings in db.php in the config folder
put the craft folder one level above web root
updated all 3 of the relevant folder permissions (including enclosed)
enabled dev mode in general.php

I even added a statement to craft/etc/behaviors/AppBehaviors.php. After line 852, at which point the db connection appears to be valid, I echo'd a "db connection is valid" line and got there. That line is now commented out.

I'd love to hear your thoughts on what I might try to fix this.

Contents of config/db.php:

<?php

/**
* Database Configuration
*
* All of your system's database configuration settings go in here.
* You can see a list of the default settings in craft/app/etc/config/defaults/db.php
*/

return array(

// The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
'server' => 'internal-db.s<my acct #>.gridserver.com',

// The name of the database to select.
'd<my acct #>_onehanders_db' => '',

// The database username to connect with.
'user' => 'db<my acct #>',

// The database password to connect with.
'password' => '<my password>',

// The prefix to use when naming tables. This can be no more than 5 characters.
'tablePrefix' => 'craft',

);


texts: Changing a product's Tax Category ID onSaveProduct event

texts:
I'm trying to alter a products tax category whenever it's saved based on a condition.

craft()->on('commerce_products.onSaveProduct', function(Event $event){
    $product = $event->params['product'];
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->id = $product->productFilterArtist[0]->id;
    $artist = $criteria->first();

    //Craft::dd($product->taxCategoryId); // 2

    if ($artist->getContent()->vatRegistered) {
        $product->taxCategoryId = 1;
        //Craft::dd($product->taxCategoryId); // 1
    }

    $success = craft()->elements->saveElement($product);

    //Craft::dd($product->taxCategoryId); // 1
});

It appears to work as the output of each Craft::dd is correct. However the entry still shows the original tax category in the CP.

I have been able to alter the shipping category in the same way without trouble. Am I missing something?


texts:
I'm trying to migrate an existing blog into Craft using the FeedMe plugin. The old blog has an XML RSS feed that I'm importing and for the most part, everything works fine but the content section of the XML element contains HTML tags. When importing these tags are not removed or displayed properly.

Is there a way using the FeedMe plugin (Free or Pro version) to strip these tags or have them display properly?


texts: Plugin development - Querying related data

texts:
I am working on a Craft plugin.

I have a main entities are 'Courses' and 'Entries'. If I click on an Entries in the CMS there is an option to select and associated 'Course'.

In my controller I can get a Course as follows:

$course = craft()->entries->getEntryById($variables['pathId']);

So far so good, but now I want to get all related 'Entries', so I do the following:

$entries=$course->entries->find();

This gives the following error:

Property "Craft\EntryModel.entries" is not defined.

What am I doing wrong? Clearly the two are related so why isn't this method working?


texts: Search Assets in Matrix fields, if they appear in a Section

texts:
I want to run a search on Assets that are in use within a particular section. The Assets are added to entries via a Matrix field.

The search term is provided via a url parameter:

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

Somewhat optimistically I tried this:

{% set imagesInUse = craft.assets.relatedTo({
  targetElement: craft.entries({
    section : 'agency'
  }),
  field : imageList.keyImage
}) %}

Where imageList is the Matrix field and keyImage is the Assets field. The block name is imageSpread.

This apparently returns nothing.

For the search part, I'm trying to search within 'imagesInUse':

{% for image in imagesInUse.search('*' ~ searchTerm ~ '*').order('score') %} ... {% endfor %}

It looks like a relatively complex query might be required, but I'm not sure where to go from here.


texts: I just downloaded the latest version of Craft (2.3.2617) and extracted the zip to check it out. Every file has execute permissions turned on for all users. Is there any reason for this?


texts:
This is a very loosely associated question but looking at the plugin page for Pimp My Matrix, they depict icons for Crop Position, and Crop Aspect Ratio:

Are these custom fields from somewhere or is it possible somehow to add your own icons for something which looks to be essentially a radio button or select type of field?


texts: Dependency Conflict Updating to Craft 3.5

texts:
I'm trying to update to Craft 3.5 from 3.4.3 but running into this error message:
Composer output: Package "craftcms/vue-asset" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Conclusion: remove tcb13/substringy 1.0.0
- Conclusion: don't install tcb13/substringy 1.0.0
- Conclusion: remove danielstjules/stringy 3.1.0
- Installation request for tcb13/substringy (locked at 1.0.0) -> satisfiable by tcb13/substringy[1.0.0].
- Installation request for craftcms/cms 3.5.5 -> satisfiable by craftcms/cms[3.5.5].
- Conclusion: don't install voku/stringy 6.3.1
- craftcms/cms 3.5.5 requires voku/stringy ^6.2.2 -> satisfiable by voku/stringy[6.3.1, 6.3.0, 6.2.2].
- don't install voku/stringy 6.3.0|don't install danielstjules/stringy 3.1.0
- don't install voku/stringy 6.2.2|don't install danielstjules/stringy 3.1.0
- tcb13/substringy 1.0.0 requires danielstjules/stringy ^3.1 -> satisfiable by danielstjules/stringy[3.1.0].
- Conclusion: don't install danielstjules/stringy 3.1.0|install voku/stringy 6.3.1

I've uninstalled a bunch of plugins but still running into the issue. Uninstalling anything else may be problematic, so is there any way I can track down where the conflict is occurring?
For reference, this is my composer.json:
{
  "require": {
    "craftcms/cms": "3.4.30",
    "craftcms/element-api": "2.6.0",
    "craftcms/redactor": "2.6.1",
    "doublesecretagency/craft-cpcss": "2.2.1",
    "elivz/craft-single-cat": "1.2.1",
    "ether/tags": "1.0.7",
    "jungleminds/nethooks": "1.1.2",
    "venveo/craft-bulkedit": "2.0.5",
    "verbb/cp-nav": "3.0.13.1",
    "verbb/image-resizer": "2.0.10",
    "verbb/super-table": "2.5.4",
    "vlucas/phpdotenv": "^2.4.0"
  },
  "autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },
  "config": {
    "sort-packages": true,
    "optimize-autoloader": true,
    "platform": {
      "php": "7.0"
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ]
  }
}


texts:
In Craft Commerce, is it possible to make the product variant weight a required field?
We are using weight to calculate shipping so it would be good if we could make it a required field to ensure that the store admin doesn't forget to enter it.
Thanks


texts: Client not able to access live preview or offline site

texts: Is there any obvious reason why a client is not able to access live preview or an offline site? I've tested the login myself and it works OK. The client has tried using IE on a PC and Chrome and Safari on a Mac.


texts: Live Preview not loading - https / http conflict

texts:
My live preview isn't loading. I'm getting the following error:

Mixed Content: The page at 'https://www.site.com/admin/entries/pages/611-title' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www.site.com/path/title?token=lxDnfeMzRFOM-xI2IylUQZ2r1XkiQlgR'. This request has been blocked; the content must be served over HTTPS

I'm not sure where the http request is coming from though. My env file sets the site url using https, and the Base URL in settings > sites also uses https. Is there another location where Craft could be getting the http from?

UPDATE: I tweaked my htaccess settings, and now I'm getting a different error:
[Error] Failed to load resource: the server responded with a status of 500 () (page-title, line 0) https://www.example.com/path/page-title?token=zVyQLpLN9K8fZ9FJKYf6Y6l9gEvHAWts
If I try to access the url in the error, I get a HTTP 400 – Bad Request – yii\web\BadRequestHttpException error


texts:
Ok, this is the first time I need this, but here's my question:

If crop is selected for a transition, what you get is a scaleAndCrop. Is there a way to do a 'real' crop, so no resizing before cropping?


texts:
After some issues with our host, our site has returned - but the search function hasn't.

Any search on either back or front end brings zero results - when the entries which fit the criteria do exist.

Each time I try and rebuild search indexes, I get a timeout, and my browser gives me an error - meaning I'd have to try again.

Any ideas of what I can try would be much appreciated.


texts:
I have an for entry loop in which I need to look for two different field conditions. Separately they are:

craft.entries.eventStartDate('>=' ~ (now.date))

craft.entries.genericEventDate(':notempty:’)

How can I ask craft to look to see if either of these parameters is true?

Update

A work around is to pull the query without these paramaters and then run an if statement like:

{% if entry.eventStartDate >= now.date or entry.genericEventDate is not empty %}

This works but it's not really ideal since the query is pulling more entries than necessary.


texts: multi-environment config for {siteURL} not working

texts:
I've got a multi-environment setup working well for my database - that was easy to setup and i've had no issues getting it to work. Now i'm trying to set the siteUrl as a multi-config variable and no luck. I have this in general.php

return array(

  '.dev' => array(
    'environmentVariables' => array(
      'siteUrl'  => 'http://mysite.dev:8888',
    )
  ),
  '.org' => array(
    'environmentVariables' => array(
      'siteUrl'  => 'http://mysite.org',
    )
  )

);

and i've set "Site URL" in settings > General Settings to {siteUrl}

the problem is, now when I load the front-end of my site, it is outputting my links with {siteURL} written out as the actual links, eg

<a href="{siteUrl}/about#start">

All the documentation and posts I can find seem to imply that this is all I should have to do. Any idea what's missing?


texts: Why does Bootup.php run with PHP 5.4.16 from with Craft script but PHP 7.4.10 from the terminal command line?

texts:
This is a problem encountered apparently by a lot of users when installing from the Craft setup/install files from the Craft web site.
PHP Warning: Unsupported declare 'strict_types' in /var/craft/vendor/voku/portable-utf8/src/voku/helper/Bootup.php on li PHP Fatal error: Default value for parameters with a class type hint can only be NULL in /var/craft/vendor/voku/portablec/voku/helper/Bootup.php on line 27 Script @php craft setup/welcome handling the post-create-project-cmd event returned with error code 255
The following scenario yields this error:

A fresh install of craftcms

installed with composer

using these instructions: https://craftcms.com/docs/getting-started-tutorial/install/files.html#what-s-composer

On a bran new unused DigitalOcean Plesk/Centos7 machine

with php aliased to the Plesk php 7.4 folder

With CLI php -v verified as returning 7.4

With all the required php extensions

With the web server visited and phpver command verified as returning 7.4

with composer updated
# composer depends danielstjules/stringy
# voku/stringy 6.4.0 replaces danielstjules/stringy (~3.0)

Diagnosing it, Right, putting echo phpversion(); into Bootup.php and running from Bash returns 7.4.
But comment everything in Bootup.php out, put echo phpversion(); into it and run craft, and when it calls Bootup.php, it returns 5.4.16.
Why is this?  Why does it run with a different php version when run from within the Craft script, and how is this fixed to run with 7.4?


texts: Instructions for external or integrating auth?

texts:
I'm looking to either use my own auth or use Craft's for additional functionality outside of Craft. Our client has some very specific requirements that we'll be building separately and we'd like to save them having to log into the CMS for one thing and a separate system for another.
Are there instructions, docs, tutorials, etc for something like this? Or is it possible?
I've seen some plugins for adding things like oauth, but I'm wondering if there's any official info instead of looking at someone else's code.


texts: Prevent foreign characters in filenames?

texts:
It seems that some of our users are uploading filenames with foreign characters...

Is there any way to prevent this?

I'd like to keep the filenames to all English letters (plus numbers, dash & underscore).

(If relevant, this is for Craft 2.)


texts: Feed Me Not importing json data for suggested feed elements in the cms

texts:
Ok I've used feedme previously and with success. And I also have a feed currently set up for a simple json file importing news articles. However I am trying to import another feed from the same source which I can see as json if I view it in a browser. The problem is that in the plugin cms it suggests what feed elements I should use (not always all of them). But it doesn't import the data value. So for example when trouble shooting just adding the title it imports title:"" when I can clearly see a title for each node in the json?
I'm beginning to wonder if the json is formatted correctly or it's a problem with feedme's mapping.
As an example I have this suggested mapping in the plugin:
Title: <items/DisplayName> eg: Factsheets

So it can read the json.
I set the title as a unique identifier and leave the slug field empty so it should be generated from the title.
This produces log entries of:
Match existing element with data {"title":""}.
Error: Unable to match an existing element. Have you set a unique identifier for ["title"]? Make sure you are also mapping this in your feed and it has a value. - Element.php: 160

This is the same error for each node. The error is obviously due to an empty string being set for the title.
There are clearly DisplayNames set in the json but for some reason nothing is being mapped?
If anyone has any ideas why this isn't working that would be great.
Following is a json snippet:
{
    "error":"",
    "status":0,
    "items":
    [
        {
            "DisplayName":"Factsheets",
            "SafeURL":"\/factsheets",
            "SourceFSItemID":"12345xxxx",
            "childviewitem":
            [
                {
                    "DisplayName":"Factsheets",
                    "SafeURL":"\/factsheets\/factsheets",
                    "SourceFSItemID":"12345xxxx",
                    "childviewitem":null
                },
                {
                    "DisplayName":"Business start-up",
                    "SafeURL":"\/factsheets\/business-start-up",
                    "SourceFSItemID":"12345xxxx",
                    "childviewitem":
                    [
                        {
                            "DisplayName":"Business start-up",
                            "SafeURL":"\/factsheets\/business-start-up\/business-start-up",
                            "SourceFSItemID":"12345xxxx",
                            "childviewitem":null
                        },
                        {
                            "DisplayName":"An introduction to the tax system for the self employed",
                            "SafeURL":"\/factsheets\/business-start-up\/an-introduction-to-the-tax-system-for-the-self-employed",
                            "SourceFSItemID":"12345xxxx",
                            "childviewitem":null
                        },
                        {
                            "DisplayName":"Business structures - which should I use?",
                            "SafeURL":"\/factsheets\/business-start-up\/business-structures-which-should-i-use",
                            "SourceFSItemID":"12345xxxx",
                            "childviewitem":null
                        }
                    ]
                },
                {
                    "DisplayName":"Capital taxes", .....


texts:
I have created a front-end form to facilitate editorial review of user submitted content. I have created a controller action to receive the post.

My question, how do I locate the email address of the author tied to this entry? My objective is to be able to email the author with the results of the editorial review. In order to accomplish this I need to know the user (author) email address etc. Here is my code.

$this->requirePostRequest();

$entryId = craft()->request->getRequiredPost('entryId');
$editorialNotesInternal = craft()->request->getPost('fields.editorialNotesInternal');
$editorialScore = craft()->request->getPost('fields.editorialScore');
$editorialNotes = craft()->request->getPost('fields.editorialNotes');
$sectionId = craft()->request->getPost('sectionId');

$entry = new EntryModel();

$entry->id = $entryId;
$entry->sectionId = $sectionId;

if ( $editorialScore >= 3) {
    $entry->enabled = true;
} else {
    $entry->enabled = false;
}

$entry->getContent()->editorialScore = $editorialScore;
$entry->getContent()->editorialNotes  = $editorialNotes;
$entry->getContent()->editorialNotesInternal  = $editorialNotesInternal;

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


texts:
We are building a family community website with 600+ members.

One of the gimmicks will be some stats, like average age all members.

Is there a smart way to calculate this?


texts: Removing the Save button based on some condition

texts:
I want to remove the Create button of an entry based on some condition (review states) for some users.
Is there a way to hook in within a module?


texts: Issue with Matrix `type` property and Live Preview?

texts:
I have problems getting Live Preview to work with this Twig code that gets data from a Matrix field.

{{ entry.matrixField.type('copy').nth(0).plainText }}

As soon as I remove the type property from the criteria model, it does update on entry changes again!


texts:
I'm looking for a way to get search results, even if people make typos, so apple as a result when looking for aple. Not fuzzy search, but some implementation of, for example, a Levenshtein function. I know I could go the Algolia way and that there's even a plugin for that, but before I pay Algolia for it, I would like to know:

Is there an easy/quick way to do this without using an external service?
If so, would you be willing to share your thoughts on the subject?


texts: Phantom routes load index template, no 404 and no errors

texts:
I have an issue regarding two (that I’ve come across) routes just simply loading the index template when they shouldn’t.

My template structure looked like this:

- search
 - index.twig
- index.twig

When I visited /search the root /index.twig template (front page) loads up.

If I create search.twig next to /index.twig and again go to /search I still get the home template rendered. Removing all search templates and going to /search again, still renders the index.twig template.

There is nothing in config/routes.php and there are also no routes present in craft_routes within the database.

I may have had these routes set up at some point in the past (the project is a bit old), so I created a new database and installed Craft again (kept all other template files, replaced craft/app folder) and the problem went away. Switched database in config (kept new craft/app folder) and now the problem is back again.

Is there anything in the database somewhere that would cause old routes to persist or be funky when the templates and any config/routes.php have been deleted?

I did try and look through the tables but couldn’t really spot anything that stood out, any help would be awesome!


texts:
I am running an app project, which consists of three "components".

1) The app itself

2) Laravel API serving the data for the app

3) Marketing website based on Craft CMS

Now I plan to extend the Craft CMS website with landing pages for all records of the API.

So for example there should be a new url like this:

https://example.com/more-about-{slug}
https://example.com/more-about-tarifa

The Craft system should not know about the available slugs / landing pages. Craft should only take this slug, call the API to fetch the information (content, images, ...) and show it in a template.

Can anyone of you give me some advice how you would realize this?


texts: Output tags in the order they were added to an entry

texts:
Is it possible to output tags for an entry page in the order they were added to related entry?

For example on a News page I would like to output any/all tags added to the News article on the specific article page in the order the tags were added to that article, I currently output the tags using the following:

        {% for tag in craft.tags.relatedTo(entry) %}
            <li>{{ tag }}</li>
        {% endfor %}

This works great as it only outputs the tags that have been added to that entry, but it shows the tags in the default title ascending order rather than reflecting the order on the entry.

I can switch the order by setting it to desc on the title .order('title desc') and I've also read through the docs on ordering but I'm still not sure how to achieve this.

Thanks,


texts: $event->performAction = false; doesn't stop action

texts:
I've got a plugin which creates an entry on user activation. I'm trying to extend the plugin so that after public registration the account is not activated (i.e., force an Admin to activate the account).

According to the documentation I'd expect this code block to stop activation:

public function init() {
    craft()->on('users.beforeActivateUser', function(Event $event){
        // stop the user from being able to activate their account. Forces admins to do so.
        //if($event->params['user']->isInGroup('artists')){
            $event->performAction = false;
        //}
    });
}

But it doesn't. What am I doing wrong? Full plugin code here: https://gist.github.com/MattWilcox/1549fb9d5787288b3b84


texts:
I'm trying to get a record from my database for a UserGroup (although I'm guessing this applies to a few scenarios really - anything that isn't a Craft Element.

I'm still new to plugin development so I could be approaching this entirely wrong but I'm pretty sure I don't want to be using craft()->db->createCommand() because it might break in a future version of craft when the schema changes and I also can't do it by using craft()->elements->getCriteria(ElementType::UserGroup); because it's not an element.

Is there a best practice for this?


texts: Bulk upload images, generating a seperate page for each image

texts:
Building a photography website for a client, need a way to bulk upload images, much like using the assets field. I want these to be grouped into different sets by entry or category. So that I can apply whatever fields I need to the set then loop through these images based on set in the Front-End.

The method I have tried is using entries and having an assets field to upload the images. The problem I am having is I also need to have each image generate it's own seperate URL, meaning a template page for the set of images and then another template for each image in that set.

Is there a way to accomplish this using Craft's core features?


texts: Unsure whether to use Sprout Forms or code forms regularly

texts:
I was wondering if anyone who has experience using Sprout Forms might be able to steer me in the right direction on whether I'm better off using the Sprout Forms plugin or coding the forms traditionally. Here's a list of some of the main things in the forms.

10 unique forms with about 30 fields each
One field will be Users Field Type (or another way to choose up to 3 users)
Front end forms will allow guests and logged in members to fill out
Back end admin will edit submitted entry form and fill out admin only fields which are hidden on front end
Ideally be able to conditionally display certain fields on the front end based on selections made by the person filling out the form (example: if person selected "Apple" choice in question 2, then show sub choices "gala", "Granny Smith". If person selected "banana" choice in question 2, then don't show any sub choices)
Form field content will need to be searchable so info can be displayed on front end template (show user how many forms he submitted, show field content based on date period)
Need to be able to create and display different reports on all 10 forms on a front end page (possibly export to csv too)

Thank you very much!


texts:
I'm currenty running Craft (v3) Commerce (v2) and have a difficult structure.

This is my menu now:

single home page.
single about page.
channel blog page.

It has to be with the products in the menu, but I don't know what would be the best structure. The products are under 2 categories. So it has te be something like this:

single home page.
single about page.
channel blog page.
? cars (products) page

? fast cars page

Fast car 1
Fast car 2
Fast car 3

? slow cars

? brand

Slow car 1
Slow car 2
Slow car 3

? other brand

Slow car 4
Slow car 5

At the ? I don't know what is the best type of page, or maybe it has to be a category. Also, the uri for the slow car has to be: cars/slow-cars/brand/{slug}.

Anyone an idea what would be the best solution?


texts: Search for assets containing a custom field

texts:
How can I search for assets containing a custom field? The field on the asset is called lang. When I use this code no assets are found.
{% set folderId = craft.app.request.getQueryParam('folderId') %}
{% set query = craft.app.request.getQueryParam('q') %}
{% set lang = craft.app.request.getQueryParam('lang') %}

{# Search for assets in the downlaoads folder #}
{% set assets = craft.assets().volume('downloads') %}
{% set assets = assets.folderId(folderId).includeSubFolders() %}

{% set searchQuery = [] %}

{# Check if a query was supplied, if so then search for it. #}
{% if query is not empty %}
{%     set searchQuery = searchQuery|merge({query: query}) %}
{% endif %}

{% if lang is not empty %}
{%   set searchQuery = searchQuery|merge({query: 'lang:' ~ lang}) %}
{% endif %}

{% paginate assets.search(searchQuery).limit(10) as pageInfo, pageEntries %}
I also tried:
{% set query = query ~ ' lang: ' ~lang %}
{% paginate assets.search(query).limit(10) as pageInfo, pageEntries %}

If I remove the lang part results will show up.
The field is a Dropdown field with languages. Value is ISO code and Label the language name. The variable lang in the code contains nl, en etc.


texts: bootstrap.php how to include environment variables for multi-environment configuration?

texts:
I recently had to run a couple of migrations to move entries from one structure to the other, but had problems when running the migration PHP script being able to get environment variables e.g. DB and stuff in .env. In the end I temporarily replaced my craft/config/db.php and hard coded my DB on local so I could run the script, however this isn't really ideal but did the job. It seemed the script couldn't get the DB environment variables.

I'm wondering what should I be including in my bootstrap migration scripts going forward in order to utilise the environment variables properly. I used a version of the script here:

Move entry from one structure to another with parenting

Slightly modified to take an array of ids, as well as mapping the old and new entry types as an arry, so it could be done in one go.

I essentially tried copying most of the beginning portion of the index.php like this and transplanting it into my migration script

// Composer: https://getcomposer.org/doc/
require_once('../vendor/autoload.php');

// PHP dotenv: https://github.com/vlucas/phpdotenv
if (!getenv('APP_SECRETS'))
{
    $root_dir = dirname(dirname(__FILE__));
    if (file_exists($root_dir . '/.env'))
    {
        Dotenv::load($root_dir);
        Dotenv::required(array('APP_SECRETS', 'CRAFT_ENVIRONMENT'));
    }
}
define('CRAFT_ENVIRONMENT', getenv('CRAFT_ENVIRONMENT'));

However, no matter what I just got a die() error from craft/local/db.php saying the path to the file containing the DB crendentials (secrets.json) couldn't be found, so it seems the environment variables weren't available at runtime. APP_SECRETS is the path to the json file.

Any ideas, what I'm missing for environment variables to be loaded in?

Thanks.


texts: I am working on a field type that is similar to the table field type. Is it possible to tap into Garnish for the sorting. I’ve tried a few things and have had no luck. Can anyone help me out?


texts: How can I loop through a field and print each value individually?

texts:
I have a field isotope.  It's a dropdown field with a single word text input.   Only one value (out of 6) can be assigned to an entry.  It is not a tag.  It is not a category.

I want to create a button for each value within the isotope field.

{% for button in entry.isotope %}

    <button class="button" data-filter="{{button.title}}">{{button.title}}</button>

{% endear %}

This is wrong and generates the error Variable "entry" does not exist.  I know this is basic, but I am obviously missing something.


texts: How can I get unpublished drafts in my plugin?

texts: I'm building a widget where I want to list all unpublished drafts (made by users without access to publish live changes), but I can't figure out how to get them.


texts:
On my local machine, every time I've added a new field and want to add content to it for the first time I get the following error:

  CDbException

  CDbCommand failed to execute the SQL statement:
  SQLSTATE[HY000]: General error: 145 Table
  './databasename/craft_searchindex' is marked as crashed and should
  be repaired.

A simple mysql repair table fixes it, but this happens way too often. Is there something I can do to prevent this?


texts: Search only in entries with own urls checked

texts:
Is it possible to search only in entries that have the own URLs option checked.

Now i've this code:

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

{% paginate craft.entries({
    search: queryWords|join(' OR '),
    subLeft: true,
    subRight: true,
    order: 'score'
}).id('not ' ~ entry.id).limit(10) as pageInfo, items %}


texts:
I'm looking to add a custom fields to the details section on the right of the entry edit view in the control panel.

I know that in Craft 2 this was possible using:
Craft::$app->view->hook('cp.entries.edit.details', functionThatReturnsView())

Is there a more Craft 3 way to do this or do we still use the Craft 2 API for this kind of extension to control panel?


texts: Craft CMS with Google Cloud SQL as backend database

texts: Did anybody successfully install Craft on Google Cloud SQL? Or on any MySQL engine with activated replication and active GTID mode?


texts:
I have a site for a company that is established in US markets and expanding into markets overseas.  The site has products and those products are grouped into categories.

Due to the costs of translating content, the client has opted to translate some of their product content but not all of it.  Out of 8 categories of products, only 2 of those categories have been translated.

Category 1 => translated
Category 2
Category 3
Category 4
Category 5 => translated
Category 6
Category 7
Category 8

As far as I can tell, there is no way to output only a list of categories that have been translated in a specific locale. Unlike entries, Categories don't appear to have a way to be enabled or disabled - they are all active for all locales.

Am I missing anything?  Or has anybody come up with a way to display only translated categories?  Ideally, in the secondary locale, I would be able to display a list of only the two categories that have been translated:

Category 1 => translated
Category 5 => translated


texts: Laravel Forge not honoring Craft 3 maxUploadFileSize config setting

texts:
I have a Craft 3 site deployed to a Digital Ocean droplet via Laravel Forge. I have the maxUploadFileSize set to 256B (268435456 in bytes) in my config/general.php like so:

<?php

return [
  // Global settings
  '*' => [
    'omitScriptNameInUrls' => true,
    'securityKey' => getenv('SECURITY_KEY'),
    'maxUploadFileSize'=> 268435456,
    'useProjectConfigFile' => true,
    'defaultSearchTermOptions' => array(
      'subLeft' => true,
      'subRight' => true,
    ),
  ],
  'dev' => [
    'devMode' => true,
    'rememberedUserSessionDuration' => 'P1Y',
    'userSessionDuration' => 'P1Y',
  ],
  'production' => [
    'allowAdminChanges' => false,
  ],
];

When I go to upload a file larger than 8mb I get this error:

  The file “.mp3” could not be uploaded, because it exceeds the maximum upload size of 8.0 MB.

My php.ini has upload_max_filesize set to 256M. I can't figure out what exactly is blocking uploads. Nothing in my .env file or my nginx.conf appears to be hindering the upload size.

Any help you can provide would be greatly appreciated!


texts: Is it possible to use Craft as a webservice when no useragent is sent?

texts:
We're setting up craft as a webservice. One of my programmers came to me and said every "slug" he called from the frontend application resulted in a 302 redirect to the login page of craft CP. Afer some investigation it seems that he didnt sent any Useragent string from his frontend curl client. After adding a useragent string everything went ok. Is this normal behaviour or can it be configured?

Thanks


texts: How can I Prevent CSRF Tokens from being Cached?

texts:
We have a Craft site in which we include a partial that includes in several different places. CSRF is enabled, and we're appending {{ getCsrfInput() }} to the form.

Because of the way we've set up the site, and are including this partial in so many places, nearly all of the forms we're rendering are using cached CSRF tokens, which invalidates them.

Is there a way to prevent Craft's {% cache %} tag from including the generated CSRF token without ending the cache and starting it up again each time? (eg, {% endcache %}{{ getCsrfInpt() }}{% cache %})

I worry doing so would be risky, because we may include this partial in a part of the site that is not cached, so there'd be no cache tag to end.

Thanks!

Update: I failed to mention that our site works right now without Javascript, so I'd like to avoid it. Otherwise, Lindsey's answer is perfect.


texts: Is it possible to have a unique cart for different users? If I log in as a user and add items to my cart, and then log in as another user, it shows the same items in my cart. Can this be changed?


texts: Change the fill or stroke colour of an SVG using a field value?

texts:
Is it possible to change the fill or stroke colour of an SVG using a value pulled from a custom field?  For example:
{{ svg('@webroot/_dist/stat/link-arrow.svg')|attr({
    stroke: '{{ entry.myCustomFieldValue }}'
}) }}

I can only get it to partially work by using a class but unfortunately there are a number of SVGs on the page so we'd also need to change all the class names :/ - and it's ugly!
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 24.3.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 37.9 20.1" style="enable-background:new 0 0 37.9 20.1;" xml:space="preserve">
<style type="text/css">
    .st0{fill:none;stroke:{{entry.myCustomFieldValue }};stroke-width:2;}
</style>
<g transform="translate(0 0.526)">
    <line class="st0" x1="0" y1="9.8" x2="36.5" y2="9.8"/>
    <g transform="translate(31.688 1)">
        <path class="st0" d="M-1-1l2.8,4.5l3.6,5.8"/>
        <path class="st0" d="M-1,18l2.4-3.8l0,0l4-6.4"/>
    </g>
</g>
</svg>


texts: I need to log flash messages from craft.session.getFlashes to a error log file from a particular twig template in Craft 2. Is there a way to do it ?