texts: Getting error: "Matrix do not have a method or closure named..."

texts:
I just playing first time with Matrix and can't figure whats wrong with this code, here's error code:

Craft\MatrixBlockModel and its behaviors do not have a method or closure named "naglowekPowitanie".

Matrix field config:

{% for block in entry.homepage %}
        {% if block.type == "powitanie" %}

{{ block.naglowekPowitanie }}

{{ block.trescPowitanie }}

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

{{ block.wstepNaglowek }}

{{ block.wstepTresc }}

{{ block.wstepPrzycisk }}

        {% endif %}
{% endfor %}


texts: Allow logged in user to change his own user group using front end form

texts:
I'd like to allow a user to change his user group via front end form.  I tried passing the groupId as the destination group, but it doesn't seem to work.

This is what I was passing:

<input type="hidden" name="action" value="users/save-user">
<input type="hidden" name="userId" value="{{ currentUser.id }}">
<input type="hidden" name="groupId" value="2">

I came across this post and am thinking that it's not possible to do without a plugin.


texts: How to link to controller actions in a Craft 3 plugin?

texts:
I cannot find any documentation that specifies how to link to controller actions which return a rendered template in CP.

Let's say I have a plugin called waffles and my namespace is Very\Waffles. I have a controller named SyrupController and it's residing in Controllers directory (note the capitalized directory name). So the namespace for it would be Very\Waffles\Controllers.
An action actionPour() - how can I register a route that would call this action if I land on the /admin/waffles URL?
I've walked through the steps with a debugger and It's trying to check if a SyrupController exists but how can it, if only Very\Waffles\Controllers\SyrupController exists? Thus it fails to register that route and fails.

Any help much appreciated!
Here's some code:

    Event::on(
        UrlManager::class,
        UrlManager::EVENT_REGISTER_CP_URL_RULES,
        function (RegisterUrlRulesEvent $event) {
            $event->rules['waffles'] = 'waffles/syrup/pour';
        }
    );

It shouldn't be possible to link to a controller by using this string, so I'm guessing an array that specifies the SyrupController::class, but there's no documentation about it.

Thanks!


texts: Audio file won't play using resourceUrl inside plugin

texts:
Essentially I'm moving a static HTML site into Craft. I've created a new plugin for the site and have gotten a good chunk of it working however I'm having an issue where audio files won't play.

The site is supposed to have music auto-playing and looping (it's a site for kids before you start judging me), and it works correctly on the static site, however nothing plays in my Craft instance and when I go to the direct URL for the audio file it won't play in browser either but doesn't give me a 404. If I "Save As" it does then download correctly.

Code is very simple:

<audio autoplay loop>
        <source src="{{ resourceUrl('somesite/audio/some_theme_full.ogg') }}" type="audio/ogg">
        <source src="{{ resourceUrl('somesite/audio/some_theme_full.mp3') }}" type="audio/mpeg">
</audio>

The src generates correctly as e.g http://site.local/cpresources/somesite/audio/some_theme_full.mp3?d=1513706441.

Any help would be wonderful!


texts: Build a Property Management System with Craft CMS?

texts:
Is Craft mature enough to build a robust rental property management system like http://www.appfolio.com/features or https://www.tenantcloud.com?

If so, are there any existing plugins that can handle any of the complex features? I will need to build or contract out the rest.

Required Features:

site visitors can search for rental units (on Map too)
tenants can pay rent online
tenants can make maintenance requests online
landlords can look at their accounts (income, expenses, past due, etc)
landlords, agents or admins can add new properties to the system
landlords or agents can book showings
automated notifications/emails (rent due, maintenance complete, etc)
lease document signing (DocuSign API or?)
calendar to schedule maintenance
e-commerce and accounting integration (possibly Quickbooks and banks API)

I've also been researching using ExpressionEngine or using an existing service like the ones mentioned above or even open source, but I really want to use Craft or even EE if possible for flexibility now and in the future.


texts:
I've been playing around with Craft 3.0 and am just about to develop a site using it. First thing I see when testing my frontpage template is "Internal server error", styled as a Craft error box.

So my question is simple, where is the log file for Craft 3.0? So I can see exactly what might be causing this?


texts: More than one field for a fieldtype plugin

texts:
I can have many 'settings' fields for a fieldType and they're saved as a serialized string in the database.

Is it possible to have more than one field for the fieldType itself? It looks like there's only one column in craft_content. So I'm not sure you can.

Is the preferred way to create your own table and store multiple field data there? And would that be using prepValueFromPost()?


texts: Making a dynamic {{ siteUrl }} for local mobile testing

texts:
I'm developing a site using a mobile first approach, connecting the phone via USB and using Safari's Web Inspector on iOS8.

On my local machine, the url for all CSS, JS and href links is http://localhost:8888/ (running MAMP) but on the phone it's my IP or http://00.00.00.00:8888/

Right now, this issue is breaking the entire site when testing on a device. All links are broken.

How can I make the Craft variable {{ siteUrl }}... well variable?


texts: Accessing global set's field gives object that couldn't be converted to string

texts:
I've been using globals many times but this is my first time encounter with such problem. Let's go from the bottom. I have two global sets with handles tax and company. The Tax set have only one plain text field taxRate which can be accessed like documentation says {{ tax.taxRate }}.

The Company set have more plain text fields and one table field.
Odd thing happens when I try to access any plain text field the same way. Example: {{ company.businessName }}.

I've tried to see what I get outputted using dump() function of that field and the output is quiet broader than the dump output of {{ tax.taxRate }}.

{{ dump(tax.taxRate) }}` -> string(2) "20"

{{ dump(company.businessName) }}` -> object(Craft\ElementCriteriaModel)#942 (17) {
["strictAttributes":protected]=&gt;
bool(false)
["_elementType":"Craft\ElementCriteriaModel":private]=&gt;
object(Craft\EntryElementType)#372 (7) {
["componentType":protected]=&gt;
string(11) "ElementType"
["_sourcesByContext":"Craft\BaseElementType":private]=&gt;
NULL
["_classHandle":"Craft\BaseComponentType":private]=&gt;
NULL ... and another dozens lines of it

I can access it using craft.globals.getSetByHandle('company') but I don't understand why I'm getting object returned in the set Company and string returned in the set Tax using the same fetch approach?


texts: Loop through all entry types, separate each group type by line rule (hr)

texts:
I'm looking for shorter way of doing this:

dog dog dog

––––––––––––––––––––––––––

cat cat cat

––––––––––––––––––––––––––

hamster hamster hamster

Currently, I have to run 3 independent loops to group pet types together, and insert a line rule between them.

How can I group pet types together and separate using a line rule?

      {% for pet in entries %}
            {% if pet.kind == 'dog' %}
                {% include '_partials/animalOrgChart' with {
                  title: pet.title,
                  subTitle: pet.jobTitle,
                  img: pet.headshot|length ? pet.headshot[0],
                  url: pet.url,
                  portrait: true
                } %}
            {% endif %}
      {% endfor %}

          {% for pet in entries %}
                {% if pet.kind == 'cat' %}
                    {% include '_partials/animalOrgChart' with {
                      title: pet.title,
                      subTitle: pet.jobTitle,
                      img: pet.headshot|length ? pet.headshot[0],
                      url: pet.url,
                      portrait: true
                    } %}
                {% endif %}
          {% endfor %}

          {% for pet in entries %}
                {% if pet.kind == 'hamster' %}
                    {% include '_partials/animalOrgChart' with {
                      title: pet.title,
                      subTitle: pet.jobTitle,
                      img: pet.headshot|length ? pet.headshot[0],
                      url: pet.url,
                      portrait: true
                    } %}
                {% endif %}
          {% endfor %}


texts: How to make next/prev links for entries circular/endless

texts:
I've got a basic portfolio website which has "prev project" and "next project" buttons on each entry detail page. I'd like for when you reach the last project for the "next project" button to simply link back to the first instead of simply not appearing at all.

Any idea how this could be done? Thanks so much in advance.

 {% if nextEntry %}Prev Project{% endif %}
 {% if prevEntry %}Next Project{% endif %}


texts: Commerce: How do I use an adjustor for line items?

texts:
I have built a plugin that, TL;DR subtracts credits. Everything is working great - until I actually need to change the price.

I just flat-out don't understand it.

This is how I am looping through to check a user's credits using the commerce_discounts.onBeforeMatchLineItem event. You can see where I was using the discount $event->performAction = false method to stop the discount from being applied. But, I need the ability to split the line items so-to-speak.

Example: qty of 5 of the same product; 3 are free, 2 are full price.

// $entry is the entry that keeps track how many credits are left.
if ((int)$entry->events > 0) {
    $i = (int)$entry->events;

    while ($i > 0) {
        error_log('doing stuff...');
        $entry->setContentFromPost([
            'events' => ((int)$entry->events > 0) ? ((int)$entry->events - (int)$i) : 0
            ]);

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

        $i--;

        if ($i == 0) {
            error_log('OUT OF CREDITS');
            // $event->performAction = false;
        }
    error_log((craft()->config->get('devMode')) ? 'CREDITS LEFT: ' . (int)$i : '');
    }
} else {
    error_log((craft()->config->get('devMode')) ? 'Uh-oh user is out of event credits..' : '');
   $event->performAction = false;
}

I have an adjustor set up...it's basically from this thread.

What I don't understand is where to actually put the adjustor.

Adjustor.php

$myAdjuster->amount = -5.0;  // How do I make the amount be 100%?
$myAdjuster->orderId = $order->id;
    // Is this is where i need to loop through the line items and do the credit deductions?

$myAdjuster->optionsJson = ['lineItemsAffected' => null];

Do I do all of the looping and such within the adjustor? Instead of a dollar amount, I would like 100% off until my credits are zero. Then the user pays full price.

My apologies for such a large question. Any guidance is greatly appreciated!


texts: Plugins and application information is detailed in the system report. Is it possible to get my module to list itself there? And if not, is there somewhere else in the CMS to see modules that a registered and working?


texts: How to display payment gateway error message only

texts:
I am trying to display the error message coming from the payment gateway ONLY.
I know I can use

{% set message = craft.app.session.getFlash('error') %}
{{ message|length ? message }}

but commerce returns to me a vague error like this

  Unable to update cart.

If anything happens to the cart, even if it is not the payment. I don't know what the error is, nor does the customer. So is there a way to catch payment errors of the cart only?


texts: After calling the controller method error from template. Craft CMS 3

texts:
https://prnt.sc/qqs50o

I use the base plugin template from plugin factory.


texts: Laravel Homestead installation nightmare

texts:
I'm running Vagrant/Virtual Box on a Windows 10 host.

I originally installed Craft on a Vagrant Scotch Box (https://box.scotch.io/). The admin panel was running a little slow so I tried installing in on a Laravel Homestead box after reading that many developers were using this solution.

I had many problems getting this to work, and when I did get it working the performance problems were worse than with my original installation.

First problem was the missing mcrypt extension in PHP 7. If you Google for a solution, you will see this:

sudo apt-get install php7.1-mcrypt

This command, although it runs ok does not result in the extension actually being installed. phpinfo shows that the extension is still not available.

I tried enabling Apache using the Homestead Yaml settings to see if that made any difference. It did not.

After doing an update and an upgrade in the Ubuntu shell, I was finally able to get the mcrypt extension running with a slightly different command:

sudo apt-get install php-mcrypt

After this I was able to run the Craft installer, but the site was running even slower, CSS files for the admin panel were intermittently failing to load, and database requests were extremely slow.

I started seeing weird MySQL errors, which were apparently a result of an incompatibility with the latest version of MySQL. This problem was resolved by adding the following to the my.cnf file in Ubuntu:

sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

This change did not improve the performance issues however.

I reverted back to Nginx to see if that would fix the problem. It did not. I then destroyed the vagrant box and started again with a brand new box.

This time I was not able to get the mcrpyt extension running at all, using either form of the Ubuntu package installer commands. It kept hanging at one of the "processing triggers" steps.

Homestead works great for Laravel and the performance is snappy, but for me getting it to play nice with Craft has been a disaster.

I am going to stay with Scotch Box for now, which runs on PHP 5.6 & MySQL 5.0.

Note: The "nfs" setting is enabled for both of these vagrant boxes, and vagrant-winnfsd (1.3.1) is installed.

I would be interested to know if anybody else had a similar experience and managed to get everything working?


texts: Craft Commerce returned orders stock and refund handling

texts:
Is there a simple way to handle returned or partially returned orders in Craft Commerce?
I'm building a site for a shop that has to deal with a lot of returned orders (woman's dresses).

A very common situation would be:
- A customer orders a product in 3 different sizes
- The customer returns 2 of those sizes and keeps the correct size

What would be a good way to handle this in Craft Commerce?

Since all the items in the shop have a limited stock it's a lot of manual work to go to every individual single item and change the stock quantity for every returned item. Is the possible to re-add the returns items to the stock in an easier way?

Is it possible to partially refund and order?

Also, the total revenue overview on the dashboard displays the total amount of all orders and doesn't keep track of refunded items. Can this be changed?


texts: Searching for Multiple Categories and Tags

texts:
I've been pulling my head for the past day on how to filter products with multiple categories.

After a long search, I found and implemented on my project, Advanced Search with tags and categories
It worked on single selection, but when I modified it for multiple categories selection I was not getting any result.

How can I pass through multiple values with Sort options? Here's what I have so far.

Any ideas?

Filter

<form action="" method="get">
<input type="search" name="query" placeholder="Search Products" style="width: 100%;">

<select name="brand[]" multiple>
    <option value="" selected>All Brands</option>
    {% set brands = craft.categories.group('brand') %}
    {% for supplier in brands %}
        <option value="{{ supplier.slug }}">{{ supplier.title }}</option>
    {% endfor %}
</select>

<select name="size[]" multiple>
    <option value="" selected>All Sizes</option>
    {% set sizes = craft.categories.group('size') %}
    {% for product in sizes %}
        <option value="{{ product.slug }}">{{ product.title }}</option>
    {% endfor %}
</select>

<select name="tag[]" multiple>
    <option value="">All Applications</option>
    {% set tags = craft.tags %}
    {% for delivery in tags %}
        <option value="{{ delivery.slug }}">{{ delivery.title }}</option>
    {% endfor %}
</select>

    <input type="submit" value="Apply">

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

{% set brandCat = brand ? craft.categories.group('brand').slug(brand).all() %}
{% set sizeCat = size ? craft.categories.group('size').slug(size).all() %}
{% set tagCat = craft.tags.slug(tag).all() %}

{% set brandParam = brandCat ? {targetElement: ['and']|merge(brandCat)} %}
{% set sizeParam = sizeCat ? {targetElement:['and']|merge(sizeCat) } %}
{% set tagParam = tagCat ? {targetElement: ['and']|merge(tagCat)} %}

{% set relationParams = [brandParam, sizeParam, tagParam]|filter %}

{% set productResults = craft.products({
    type: 'buildingMaterials',
    relatedTo: relationParams ? ['and']|merge(relationParams) : null,
    search: query
}) %}

Sort Options

% set sortOptions = [
    {
        label: 'Newest',
        value: 'postDate desc'
    },
    {
        label: 'Highest Rates',
        value: 'score desc'
    },
    {
        label: 'Price Low-High',
        value: 'defaultPrice'
    },
    {
        label: 'Price High-Low',
        value: 'defaultPrice desc'
    },
] %}

<select class="selectpicker show-tick form-control" data-name="Sort" id="sortQuery"
        name="Sort" title="Sort By:">
    {% for sortOption in sortOptions %}
        <option value="{{ sortOption.value }}" {{ sortOption.value == selectedSortOption ? 'selected' }}>
            {{ sortOption.label }}
        </option>
    {% endfor %}
</select>

{% set orderJs %}
    $(function(){
    $('#sortQuery').on("change", function(e){
    // Get the value from the select
    var filter = $(this).val();
    location.href = location.origin + location.pathname + '?order=' + filter;
    });
    })
{% endset %}
    {% js orderJs %}

Get Entries

{% paginate productResults.orderBy(selectedSortOption).limit(12).with([
    'productImageGallery:image',
    'url:url',
    'title',
    'type:type',
    'defaultPrice',
    'productSummary|stiptags'
]) as pageInfo, products %}

{% for product in products %}
...
{% endfor %}

Pagination

{% if pageInfo.prevUrl %}

{% endif %}


texts:
I have some csv files uploaded as assets and now I need to fopen() them from my plugin.

I have an AssetFileModel but I have not been able to work out how to construct a full path to the file.

I can access the filename like: $asset->filename which gives me my_csv_file.csv but this is not enough for fopen() to find it.

How can I get the absolute path to the asset file?

Or at least a path that I can use with fopen() to find the file?


texts: How to dynamically set an include template

texts:
I have a series of structure items, each with a product id, based on this id I would like to load in an additional template.

Something like this:

{% set embedAsset = entry.productId %}
{% include "embedAsset" %}

Any ideas?


texts:
We need to setup following URL:

DOMAIN/{lang}/{family}/offers/{slug}

e.g.:

example.com/en/Larsen/offers/example

What do we need to configure our section URL? Have anyone an idea?


texts:
If I'm enabling a user to post to Craft using the front-end entry form, is there a way that I can sanitize the title of a post?

I'm looking to apply AP formatting to titles.

I know Stephen has a plugin Entitle that does this but I'd rather have it on the initial submission.

This is a JS app so I can't do it on the Twig side.


texts: Get data of user after login (but not with craft()->userSession->getUser())

texts: Can I directly get the data of the user that I just logged in with craft()->userSession->login($username, $password) ? (not from a method that uses the SESSION like craft()->userSession->getUser() though)


texts: Not receiving emails from contact us and job application plugin to all email addresses on our domain

texts:
Our web developers have setup and installed Craft on a VPS for a new website. When we fill out the contact us or Job application email recipient details; the emails never reach our email addresses, they also don't reach our messagelabs mail filter.
If I add another email address or a gmail account the emails are received just fine. I'm drawing a blank as to what the fault can be.

On MX Lookup blacklist check our domain and public IP are all clear. I've configured an A record to the IP of the VPS on our hosted DNS service. The VPS support have tested emailing us from the VPS (not the CMS) and emails come through.

Are there logs for Craft, is there a way I can see what's going on here.

Any help would be greatly appreciated.

D


texts: Is there any way to tweak the way search score is calculated? For example, I would like words in the title field to be scored higher than the same terms in other fields.


texts: SEOmatic plugin override global title in individual template

texts:
I have problem whereby I can't override a single page's SEO by using a field, because the page has too many table rows in the database, due to being very field heavy. Don't ask.

So I'd like to manually override the global <title> that SEOmatic produces in the individual template page. But haven't been able to get it to work from the docs, as I'm just producing a second title tag.

Can someone help please?


texts: How to add/link an entry to an object using PHP?

texts:
I'm building a plugin to add users to the system with set properties (like company) and permissions. The user form works with an "Entries" field and works with connected source section entries and works fine. Now when I receive the objects in my SiteAdministrator_UserService i'm trying to link the passed in companyId to the custom Entries field. Like this:

$lNewUser = new UserModel();
$lNewUser->status = UserStatus::Pending;
$lNewUser->firstName = $aUser->firstname;
$lNewUser->username = $aUser->username;
$lNewUser->lastName = $aUser->lastname;
$lNewUser->email = $aUser->emailaddress;

$lCompany = craft()->entries->getEntryById($aUser->companyId);
$lNewUser->getContent()->setAttributes(array(
        'companiesDropdown' => $lCompany,
    ));

return craft()->users->saveUser($lNewUser);

$lCompany holds the entry of the company, that works fine. Now how do I link the $lCompany to the first entry in the custom Entries (companiesDropdown handle) field?

Just to clarify. All the above has nothing to do with an actual dropdown field.
Thanks in advance


texts:
Can anyone help direct me to a plugin or way of anonymously liking articles?

I have used the Like plugin by Duct (https://dukt.net/craft/like) but unfortunately it must be associated to a user account to save the entry.


texts: How can I add in new Locales to the locale list?

texts:
I have a site that has a few different countries that speak the same language but want to have them as different Locales.

Mexico (english)
Mexico (spanish)
USA (english)
USA (spanish)
Peru (english)
Peru (spanish)

These might all share some content but the manager of each region might want to change the content for their own region.

How can I add in new Locales in the locale list in Craft?


texts:
How can I add an anchor element in my content. Both the id tag and name attribute are removed from the a tag by the WYSIWYG editor.

For example:

My anchor with a name attribute

My anchor with an id attribute

is replaced by:

My anchor with a name attribute

My anchor with an id attribute


texts: How can I change the size of an individual pin?

texts:
I tried this code, but getting 'unexpected token errors". Probably something to do using incorrect syntax.

{% js %}
    var markerId = 'smartmap-mapcanvas-1.{{ entry.id }}.addressInformation';
    smartMap.marker[markerId].setOptions({
        'icon':       '{{ icon }}';
        'scaledSize:' 'new google.maps.Size(32,32)'
    });
{% endjs %}

The error in the console

var markerId = 'smartmap-mapcanvas-1.550.addressInformation';
smartMap.marker[markerId].setOptions({
    'icon':       '//d1ado4imyxw3fk.cloudfront.net/html/pin-otto-12.png';
    'scaledSize:' 'new google.maps.Size(32,32)'
})


texts: Individual persistent property per item in stock

texts:
This is more advanced: We want to sell activation keys for digital products. We know that in Craft a variant has a stock. So every single item "in" the stock needs a unique activation key. When we sell one item of the stock we sell a activation key. Of course, an activation key can only be sold once. For each product we will have a limited number of activation keys, so this will be reflected by the stock number itself.

We know that this feature requires some customization. Question is: is this achievable in an easy or hard way via Craft Commerce? How would an elegant approach look like?


texts: Changing some letters in entry's uri before save it

texts: I need to replace some characters in my entry's URI because we have some letters which do not exist in English like "ş" or "ç". It is a problem for SEO and we have to change each time manually. I tried something with entries.onBeforeSaveEntry but I couldn't solve the problem. I'm confused with getting URI and set the new URI. Any suggestion?


texts: Display entries including all locales for XML sitemap

texts:
I’m trying to build an XML sitemap that contains all entries including those in a different locale. I thought the localeEnabled(false) would allow entries for all locales to be displayed, however, the following doesn’t seem to work:

{% set pages = craft.entries.section('pages').status('live').localeEnabled(false) %}

If is assign a locale:

{% set pages = craft.entries.section('pages').status('live').locale('de') %}

then the entry is displayed.

I have tried using .locale(null) and .localeEnabled(null) without success.

Any ideas?


texts: Verbb Navigation Plugin Assistance needed

texts:
Good morning and thank you in advance. I have one Verbb navigation called main. Underneath that, I have three nodes (see image). Under those nodes are regular links. I want my template to pull only the links from a specific node (Business Environment) under the main navigation, how would I go about doing that?

I know this is the code to get all nav:
{% set nodes = craft.navigation.nodes('main').all() %} but how would I access just Business Environment?


texts:
I having a problem when trying to upload gif animations. It seems that the animation element doesn't work after they have been uploaded.

I looked at the Craft changelog and it mentioned something about support for gifs through ImageMagick. The site is on MediaTemple so when I used their ImageMagick install instructions it throws up an error.

  Internal Server Error

  curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set

I'm not sure if it is an ImageMagick thing or not but it is crucial to the function of the site. Its probably very simple.

Please help...

Thanks


texts: How can count and then order by the # of entries assigned to a category; and then limit to only the top 3?

texts:
**How can I modify this to orderBy the # of entries and then limit to the top 3? **

{% for categoryName in craft.categories.group('markets') %}
    {% set numofEntries = craft.entries.section('posts').relatedTo(categoryName).total() %}

    {{ categoryName.title }} ({{numofEntries}})
{% endfor %}


texts: How do you customize what value a Custom FieldType returns to a template

texts:
Is it possible to control what gets output in the template a custom fieldtype?

For example im working on a eventbrite plugin and it saves the id in the database but I want the field in the template to return a fully formatted register button.

Right now im doing this with a craft variable that i'm passing the id and returns the html for the button into but feels like there might be a simpler way?

Related to that right now i have to add | raw to the variable output

so its

{{ craft.eventBrite.registerButton(entry.eventbriteId) | raw }}

is there a way to prevent the escaping of whats being returned without the extra filter in the template?


texts: Image transform in inline background css not being generated

texts:
In my backend I have a radio button field with 2 options for the client:
Normal and cover. When selecting normal, the uploaded image is put into an  tag in the HTML and an image transform is applied. This works well as it should.

When selecting cover however, the uploaded image is added to a background-image inline CSS style. But the applied image transform is not generated for this. When I change the uploaded image to "normal", let it generate a transform and then put it back to "cover" only than it is shown as a background image.

So image transform doesn't seem to trigger in this code:

Does anyone know why this is not working?


texts: I have an entry with an asset field that has up to 3 assets in it. If I want to load just the second asset in my template code, what's the syntax for this? (can't find any references/examples)


texts:
Ok what i'm trying to achieve is a set of links which have "search parameters" attached to them. Which would be a "category" and an "option.field".

Then when these links are clicked they display search results according to the parameters.

Not sure even where to start with something like this, could it be achieved with data attributes?

Is it even possible? Or have would I have to jerry-rig a form to do this via radio buttons?

Thanks for any help you can give.


texts: Is it possible to search an entry for specific table content

texts:
Considering the way table field content is saved to the database, could I search entries for content in a specific column?

So, say I have a table field containing X column, I would only want to search for an ID, located in column 3. Did anyone ever successfully try this?


texts: Craft 3 Plugin Development: Add CSS and JS File to Frontend Templates

texts:
How do I add js and css files to frontend page loads via a plugin? I did reference this issue:
Can a plugin add JS or CSS to the control panel?

but that is for Craft 2.

Reading the docs here:
https://docs.craftcms.com/v3/changes-in-craft-3.html#template-tags
and here
https://docs.craftcms.com/v3/extend/asset-bundles.html

show that Craft 3 is much different. I've looked through several Craft 3 plugins that do load scripts and styles on the frontend but each seems to handle this in very different ways. Is there a straight-forward standard that should be used if a plugin is loaded and needs to add resources to frontend page loads?

On the Asset Bundles doc page, it seems you can link directly to the asset in the plugin init but a comment further down the page suggests that you need to load the assets into the template:

"With that in place, all that is left is to register the asset bundle wherever its JS/CSS files are needed."

or I may be understanding this incorrectly.
Can I accomplish what I'm trying just by placing:

$this->sourcePath = '@ns/prefix/resources';
    $this->depends = [
        CpAsset::class,
    ];

    $this->js = [
        'custom-scripts.js',
    ];

    $this->css = [
        'custom-styles.css',
    ];

within the init function? Is this enough to get those files onto the frontend loads or do I need something else and something to tell them not to load onto backend pages?

Thank you for any help. Most of my plugin knowledge is based on reverse engineering plugins and in this area I'm still confused.


texts: Is it possible to use an existing field into a matrix?

texts:
I'm trying to reuse a dropdown field inside of a matrix. I've already created a field which has hundreds of dropdown values. I want to be able to select from this dropdown field for each item of a matrix. So instead of having to re create this field for each matrix block, is there a way I can copy/paste a field to a matrix field?

Thanks in advance!


texts: Nesting level too deep - recursive dependency?

texts:
I've got a page with a couple of levels of loops. It takes a section of speakers, groups them by state, and then loops through the states, and then loops through speakers in that state. It's not too complex so I wouldn't expect to see an error like "nesting too deep".

Here's (a reduction of) the code:

{% set speakersByState = speakers|group(s => s.state.one().slug) %}
{% for state, speakers in speakersByState %}

    {% for speaker in speakers|sort %}

{{ speaker.title }}

    {% endfor %}

{% endfor %}


texts:
The website I'm working on has different sections and each section different types of entries. I would like the types of entries to be shown in the URL. I have followed this tutorial to do so.

In a site example.com where we have:

A Section called: My Section
With Entry Types: Example Entry Type, Another Entry type.

Utilizing the model from the tutorial, we could structure the URL for My Section as follows:

/my-section/{type}/{slug}

Which would give us URLs like these:

example.com/my-section/exampleEntryType/new-entry-1
example.com/my-section/exampleEntryType/new-entry-2
example.com/my-section/anotherEntryType/new-entry-3
example.com/my-section/anotherEntryType/new-entry-4

Notice that the entry types are the only part of the URL camelCased. This is  because Entry Types can only be configured to have a Name, and a Handle; and handles can NOT have dashes. This interferes with keeping URLs consistent as the rest of the site uses dashes instead of spaces

The problem I am trying to solve is: how do we get the Entry Types to stay consistent with the rest of the site?

Does anyone have any suggestion on how to deal with this? Is this a problem that should be addressed in Craft? Should I be taking another approach for this?

I had considered using categories but the way the system is setup, entry types seem more appropriate.


texts: Can I change which 'Format' options are available in my Rich Text field?

texts:
I want to update my Rich Text field so only H1, H2 and H3 are the available options in the 'Format' selector.

Is this possible?


texts: Display entries linked from Matrix field according to the entries' structure and a light switch in the Matrix

texts:
In a channel (market), I have a Matrix field (market_products) with a Stucture-based Entries field (products) and a Lightswitch field (active/inactive). For each market, I need to create an ordered list of products, following the Structure hierarchy of the original products channel, and including a link according to the active/inactive light switch.

I can create a list of products styled according the the lightswitch, but ordered by the order in the Matrix field:

{% set allProducts in entry.market_products %}

{% for each in allProducts.theProduct %}
    {% set theSwitch = allProducts.active %}

    {% if theSwitch == "1" %}

{{ each.title }}

    {% else %}

{{ each.title }}

    {% endif %}
{% endfor %}

or a list of related products ordered by the product structure, but not styled according to the lightswitch:

{% set allProducts = craft.entries.section('products').relatedTo({
    sourceElement: entry.id,
    field: 'market_products.theProduct'
}) %}

{% nav productList in allProducts %}

        {{ productList.title }}
        {% ifchildren %}

            {% children %}

        {% endifchildren %}

{% endnav %}

But how do I create an array of products, ordered by the products' structure AND filtered according to the lightswitch?


texts: Set execution order of plugins listening to same event

texts:
I have 2 separate plugins that listen to same event.

Now I want to make sure Plugin B starts its action only after Plugin A has finished its job.

Is there a way in Craft CMS to set priority / execution order for plugins that listen to same event?


texts: Best practice on how to hand over variables with links?

texts:
You sometime want to pass specific info from one page to another.

How do you do that with twig and are there explicit Craft methods to do this?
Can you do this without exposing the variable in the URL?


texts: How to check if a field exists on a section

texts:
When you remove a field from Craft, the data itself doesn’t disappear. So removing i.e. an intro field from a section, if that intro field is still used in the template, that content will be output still on an entry.

Presumably this is intentional more than a bug so that Craft doesn’t have to go and re-save all of the entries in that section, which would probably cause the webserver to catch on fire (therefore I’m not going to write a plugin to hook into the save entry hook to clear it).

Is there a way to check in twig if a field is on a given section? The “if x defined and x|length” check passes because this data exists against the entry, even if the fields isn’t on the section.

I’m using a template for multiple sections that share a similar set of fields for a preview, and don’t want to replicate 99% identical templates.


texts: Does Craft have a server-side queuing system?

texts:
I am wondering if Craft/Yii has some sort of built in queuing system for apps that need to do additional processing that could hang up the UI or make the user wait unnecessarily. I am looking for something similar to Laravel Queues. Does Craft have something similar built in? If not, I think queues would make a great addition to the API.

http://laravel.com/docs/queues


texts: Twig combined conditionals to set variable

texts:
I am trying to check for the existence of a text field and an asset field and set an icon variable depending on the result.
I don't seem to be having much luck with defined, length and empty combinations.

Here's my code so far:

{% if (story.videoStoryUrl is defined) and (not story.storyImage | length) %}
    {% set icon = "video" %}
{% elseif (story.videoStoryUrl is empty) and (not story.storyImage | length) %}
    {% set icon = "text" %}
{% else %}
    {% set icon = "image" %}
{% endif %}

Any help appreciated :)


texts:
I have a search results page that doesn't show all matching results. The result entries that do show appear to older entries that have smaller ID numbers, although I'm not sure if that has anything to do with the issue.
In my case, I have a people channel. Each person (entry) in the channel has a related entry called relatedOffices (associated with a locations structure section). Although the entries for "John", "Jim", and "Jerry" all have "Dallas" selected in the relatedOffices field, only "John" and "Jim" show in the results.
I've been able to deduce the issue down to the queryParam search string. If the search query string is just relatedOffices:Dallas, all three entries show. But if the search query string is AND relatedOffices:Dallas, only two of the entries show.
The addition of AND seems to change the results, but I'm not sure why. I'm hoping to keep the AND in the string as well because I'm using multiple parameters in my search.
I tried rebuilding the index (php craft resave/entries --update-search-index ), but that doesn't seem to resolve the issue.
Craft CMS 3.5.8 is what I'm running.
Here's my query string and query param set up:
{# 1. Getting parameters from URL  #}
{% set keywordParam = craft.app.request.getParam('q')%}
{% set nameParam = craft.app.request.getParam('name')%}
{% set industryParam = craft.app.request.getParam('industry')%}
{% set locParam = craft.app.request.getParam('loc')%}

{# 2.Building query string #}
{%- set queryString -%}
    {% spaceless %}
        {{- keywordParam ? "#{keywordParam} AND " -}}
        {{- nameParam ? "#{macros.paramString(nameParam, 'title')}" -}}
        {{- industryParam ? " AND #{macros.paramString(industryParam, 'industriesRelated')}" -}}
        {{- locParam ? " AND #{macros.paramString(locParam, 'relatedOffices')}" -}}
    {% endspaceless %}
{%- endset -%}

{# 2B. Escape queryString output and set default to be ' ' so that if there's no params, ' ' outputs which leads to no results #}
    {% set queryString = queryString|escape|default(' ') %}

{# 3. Set queryParams #}
{% set queryParams = {
    section:    'people',
    limit:      15,
    search:     (queryString)
} %}


texts: Obtaining SEO metadata for a specific entry under Sprout SEO 3

texts:
Under Sprout SEO 2 I am able to obtain the SEO metadata for a specific entry as follows:

{% do craft.sproutSeo.meta({
    id: entry.id,
    title: entry.title,
    description: entry.body|striptags|slice(0, 160)
}) %}
{{ craft.sproutSeo.getOptimizedMeta().basic.title }}
{{ craft.sproutSeo.getOptimizedMeta().basic.description }}

Here I am using the entry's title and body fields as fallback SEO metadata if none is specified on the entry. This is all documented for Sprout SEO 2.

How do I achieve this under Sprout SEO 3? The closest I can get is as follows:

{% do craft.sproutSeo.meta({
    id: entry.id
}) %}
{% sproutseo 'optimize' %}
{{ metadata.meta.search.title }}
{{ metadata.meta.search.description }}

Although this requires disabling automatic metadata rendering, which I require elsewhere, and enabling the custom metadata variable. It also omits the fallback SEO metadata as this now overrides the entry's metadata.


texts: Are there any Craft specific migration tools that extend Yii's built-in functionality?

texts:
We're working on developing a proper deployment system for projects built on Craft, and wondering if there are any Craft specific tools built-in that can assist with generating database migrations, other than those included with Yii itself?

I have more questions, but we'll start here.


texts: Automatically subscribe users to MailChimp list?

texts: I would like to automatically subscribe all newly registered users to a MailChimp mailing list.


texts: How to deal with client input your site?

texts:
Our client wants a poll on the website.
How can I deal with client input and update the entry?
I found the Entry-Form example, but this doesn't work.

The title field is the question and the admin can add answers with a matrix field. Within the matrix fields there are 2 fields: answer and totalVotes

This is my code:

<form class="poll__questions" method="post" action="" accept-charset="UTF-8">
    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="{{ craft.request.getPath }}?success=√">
    <input type="hidden" name="sectionId" value="38">
    <input type="hidden" name="entryId" value="{{ pollentry.id }}">
    <input type="hidden" name="enabled" value="1">

    {{% for answer in pollentry.answers %}

<input type="radio" name="fields[answers][{{ answer.id }}][fields][totalVotes]" value="{{ answer.totalVotes + 1 }}"> {{ answer.answer }}

    {% endfor %}}

    <button type="submit" class="button button--third">Vote</button>
</form>

Does anybody know why this doesn't work. It submits the form without visible errors, but it doens't update the entry.


texts:
I am having trouble getting images by name. craft.assets.first() function in assets gives the proper output of one image.

But when I try craft.assets.filename('flag.jpg'), craft shows the following error:

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

Same with other functions of assets. Please help me solve this error.

Thank You.


texts: Carry over asset field content to other locales

texts:
I have a site with English and French locales. One of the fields we have assigned to our entries is an asset field.  Currently when an admin adds a new entry, all the English content will carry over to the French locale except for the file selected in that asset field.  Ideally, I'd like for the English asset field contents to carry over to the French asset field and only change if the admin changes it in the French locale.

I have tried a variety of settings but haven't had any luck.  Any direction would be appreciated!


texts: I have a series of matrix blocks that use a ton of the same fields and was hoping I could simply duplicate them in the database and update the context and id of the fields. It'd be a LOT faster this way however i'm unsure of the UID column, how/when that is created and if i should leave it blank, or if that column existing means i'm going to have to it all manually


texts: How do you display entries in a specific (custom) order?

texts: I want to display entries in a specific custom order in Craft. For example entry Id 1, then Id 5, then Id 3.  How can I do that?


texts: Conditional if statement for Matrix dropdown option

texts:
Ok, so I've tidied up the code a bit and using option.selected instead of option to see if the option is selected. But, it isn't behaving how I'd expect it:

{% for telephone in user.profilePhone.type('details') %}

      {% if telephone.type == 'details' %}
        {% for option in telephone.icon.options %}
            {% if option.selected == 'mobile' %}

            {% elseif option.selected == 'home' %}

            {% else %}

            {% endif %}
        {% endfor %}
        {% if telephone.country %}{{ telephone.country }}{% endif %}
        {{ telephone.number }}
      {% endif %}

{% endfor %}

So this is how I read it:

Loop through all Block Types details

As I understood from the docs, there is no need to be specific if there's only one Block Type (regardless of max blocks setting). The extra if conditional seems redundant?
I also understood that a for loop would act as a conditional anyway, so it would return false if no Blocks existed?

Loop through the icon dropdown options

Whichever one is selected, display it's corresponding icon.

But what it actually outputs is this:

So it's outputting all of the available options, not just the selected one (and not even the correct icons). I've managed (with separate if statements for just 'home' and 'mobile' to get this:

But it's still outputting all options declared in the if statement, instead of the desired single icon. Here are the dropdown options:

I'm new to programming, so perhaps I'm getting muddled up with things, but it seems like it should only output the icon I want, not the entire dropdown list (I realise I may need another conditional for if 'other' or 'work' is selected)

Perhaps the issue is you can't check in the for loop for just the selected option with an if condition. Something like:

{% for option in telephone.icon.options if option.selected %}


texts: Uploaded assets using ftp, asset not displaying

texts:
I uploaded and un-tar'ed a bunch of folders containing images under one of our local asset source folder.  After triggering the "Update Asset Indexes" tool, and waiting for its completion, my asset table is still blank.  Under "Assets", I can see all the new sub-folders but all are empty.  I checked the file and folder permissions on disk, all are ok.

Looking into the database, the "craft_assetindexdata" show all the file path, but the "recordId" column indicate "NULL".  Is there something else I need to trigger for this process to complete?

Using Craft Pro 2.3.2629

Thanks for your help.


texts: Populating craft database from non-craft data

texts: Is it possible to populate the Craft content database table with entries from a non-craft database (which isn't a live database, it's a local copy). I've set up my channels etc for the incoming data which corresponds to the data from my other db.


texts: How can I embed an iframe on my site? I tried pasting the iframe code in the HTML section and it didn't appear.


texts: Using Dynamic values in the Reply To field in Sprout Forms Notifications

texts:
I'm looking to have a Dynamic 'Reply To' for a notification when an entry is saved from a form submissions.

I'm using the below which is what the field is named in my form, but it seems it's not allowed?

{email}


texts:
I'm trying to process multiple elements in a custom element action, and then redirect the CP user to a url.

How would I do that?


texts: Craft license and develop a website locally?

texts:
Is there any problem with buying a Craft Client account, working on the website locally (on my pc), and when it´s done move it to the server?

Is this permitted by the license?


texts: convert_encoding is screwing up Spanish-language characters

texts:
Standard "when article has no summary, output the first 200 characters of the body minus HTML" logic going on here. We're implementing some Spanish-language features for the first time and, while special characters are stored fine in the database (utf_unicode_ci collation) and they output fine on the front end when convert_encoding isn't applied, they come out garbled when convert_encoding is applied.

My code is:

{{ item.articleBodySpanish.type('bodyText')[0].bodyText|striptags|convert_encoding('UTF-8', 'HTML-ENTITIES')|slice(0, 200)|default('Lee mas') }}...

I have an entry where the database contains this for articleBodySpanish:

Empuja sus puños contra los postes y sigue insistiendo en que ve a los fantasmas.&nbsp;Empuja sus puños contra los postes y sigue insistiendo en que ve a los fantasmas.

With the code above, the output I get is as follows:

Empuja sus puÃ±os contra los postes y sigue insistiendo en que ve a los fantasmas. Empuja sus puÃ±os contra los postes y sigue insistiendo en que ve a los fantasmas.

If I remove the |convert_encoding('UTF-8', 'HTML-ENTITIES') the output becomes this, so I can't even just take it out to moot the issue:

Empuja sus puños contra los postes y sigue insistiendo en que ve a los fantasmas.&nbsp;Empuja sus puños contra los postes y sigue insistiendo en que ve a los fantasmas.

What can I do here?


texts: Confused by template and URI settings for multi-lingual sites

texts:
I have 2 x sites with base URLs set to @web/en/ and @web/de/

For client entries in a "Clients" section, I have a template at templates/clients/_entry.twig which I want to use for both sites.

What should the Entry URI Format be set to in the Clients section... eg should it be clients/{slug} for both sites? Or should the base url be included in these dynamically somehow?

(New to localisation so please excuse me if I'm doing this totally wrong!)

UPDATE: if I set the URI to clients/{slug} and view en/clients/clientname I get this error...

  Warning: chdir(): No such file or directory (errno 2) in
  /Users/jamesgreig/.composer/vendor/laravel/valet/server.php on line
  145

  Warning:
  require(/Users/jamesgreig/Repos/hoskins-craft/web/en/index.php):
  failed to open stream: No such file or directory in
  /Users/jamesgreig/.composer/vendor/laravel/valet/server.php on line
  147

  Fatal error: require(): Failed opening required
  '/Users/jamesgreig/Repos/hoskins-craft/web/en/index.php'
  (include_path='.:/usr/local/Cellar/php@7.1/7.1.16/share/pear') in
  /Users/jamesgreig/.composer/vendor/laravel/valet/server.php on line
  147


texts:
I've written a short macro to get the first image inside a matrix field.

{% macro firstImage(entry) %}

    {% set image = 'hello' %}

    {% if entry.sliderMatrix.total() %}
        {% set block = entry.sliderMatrix|first %}
        {% set image = block.image|first %}
    {% endif %}

    {{ image.url }}

{% endmacro %}

The code throws this error: Impossible to access an attribute ("url") on a string variable ("hello")

{{ image.url }} inside the if statement works fine.

{{ image }} outside the if statement works too.

Is there anything I don't know or it's even a bug?


texts:
On my _entry page, I'm trying to get the SmartMap plugin to generate a dynamic map, but it gets stuck on 'Loading Map'

Using this as the code:

{{ craft.smartMap.map(entry.theEventAddress) }}

and the console tells me:

  Uncaught SyntaxError: Unexpected token ,

The documentation is a bit vague on this, and it doesn't really tell you how to fix JavaScript errors. Also, I have API keys in the settings.

EDIT

Here's the output as requested. Using the latest version of the plugin. (2.3.1)

<script type="text/javascript">
/*<![CDATA[*/
if (logSmartMap) {console.log("[smartmap-mapcanvas-1] Drawing map...");}
smartMap.createMap("smartmap-mapcanvas-1", {"center":smartMap.coords(-48.876667,-123.393333),"scrollwheel":false});
if (logSmartMap) {console.log("[smartmap-mapcanvas-1.2497.theEventAddress] Drawing marker...");}
smartMap.createMarker("smartmap-mapcanvas-1.2497.theEventAddress", {"mapId":"smartmap-mapcanvas-1","map":smartMap.map["smartmap-mapcanvas-1"],"position":smartMap.coords(,)});
if (logSmartMap) {console.log("[smartmap-mapcanvas-1] Fitting bounds...");}
smartMap.fitBounds("smartmap-mapcanvas-1");
/*]]>*/
</script>

This is the problem line:

smartMap.createMarker("smartmap-mapcanvas-1.2497.theEventAddress", {"mapId":"smartmap-mapcanvas-1","map":smartMap.map["smartmap-mapcanvas-1"],"position":smartMap.coords(,)});


texts: Commerce Plugin Unintentionally Rewriting Past Orders - Commerce Bug or Something Else?

texts:
We are experiencing very unexpected behaviour with a very simple plugin we wrote and are stymied as to whether this is revealing a bug in Commerce or whether we have completed missed something.

Here is what we're doing in conceptual terms:

We need to offer different prices for users based on their country (just US and CAD right now). The Commerce base currency has been set to CAD and we have added a custom field for products to hold a US price. So each product has a CAD price using Commerce's base currency and a US price using a custom field.

We check the user's country and based on whether it is Canada or the US, our plugin uses onPopulateLineItem and onBeforeSaveOrder to update the price and currency appropriately:

class FlatPricingPlugin extends BasePlugin
{
    public function init()
    {
        parent::init();

        // If there is no log here, cp login will fail.  This line is
        // not nessesary if dev mode is turned on.  This is probably a
        // server specific issue.
        FlatPricingPlugin::log(
            'This is a required log line. See FlatPricingPlugin.php',
            LogLevel::Info, true);

        // Use the american price if currency is set to USD
        craft()->on('commerce_lineItems.onPopulateLineItem', function($event){
            $line = $event->params['lineItem'];
            $currency_key = 'currencyAbbreviation';
            $currency = craft()->httpSession->get($currency_key);
            if($currency == 'USD'){
                $price = $line->purchasable->product->productPriceUSD;
                $line['price'] = $price;
            }
        });

        // Set the currency and payment currency to the chosen currency
        craft()->on('commerce_orders.onBeforeSaveOrder', function($event){
            $order = $event->params['order'];
            $currency_key = 'currencyAbbreviation';
            $currency = craft()->httpSession->get($currency_key);
            FlatPricingPlugin::log("$currency -- {$order->itemSubtotal}, {$order->itemTotal}, {$order->totalPrice}, {$order->totalPaid}");
            if ($currency == 'USD'){
                $order->paymentMethodId = 2;
                $order->currency = $currency;
                $order->paymentCurrency = $currency;
            }else{
                $order->paymentMethodId = 1;
                $order->currency = $currency;
                $order->paymentCurrency = $currency;
            }
        });

    }
}

This works but we have run into a reproducible scenario where placing an order overwrites the currency of previous orders. The scenario involves placing an order from one country and then, for the same user, placing an order when they are in the other country. In this case, the old order (or orders) have their currencies changed to match the new country.

We have tested this on a vanilla install of Craft and Commerce with only this one plugin. Here is a link to a ZIP with a DB dump, our plugin and a readme with full setup and reproduce instructions.


texts: asset.first().getUrl('transform') not working for s3 asset - Craft CMS 2.6.2980

texts:
I can load the s3 image fine using the s3 base path and the craft cms filename that is saved in the craft cms database:

renders

However if I want to access the same image without the s3 base path (e.g. in order to use an image transform), I get a null.

renders

Any help would be appreciated!


texts:
I just installed the Craft 3 RC on MAMP - the install process executed without error and I can see all of the Craft files in the directory I specified and the .env file was updated with database info. However, when I try to run setup it throws an error ( The requested URL /cr3.dev/admin was not found on this server. ). I then deleted the entire directory and ran the Composer install again, but same issue when I try to run the Craft install process.

The MAMP server is working fine - an existing Craft 2 install works perfectly and just to be sure I created a new test directory with a single index.html file and that worked as well.

I realize this is not much info, but hoping someone has some ideas to guide me along!


texts: Commerce Order Model in Gateway Event Plugin Hook

texts:
I am trying to add some logic that can stop an order transaction from happening depending on values stored in the Order Model. Due to how my client wants the purchase page setup, I need to be able to do last-minute validating through the commerce/payments/pay action, which I can intervene before it happens using the onBeforeGatewayRequestSend event.

Below is a simplified version of what I'm trying to do. The issue I am having is accessing the Order Model, It looks like it isn't available in the $event parameter - which is why the below doesn't work.

craft()->on('commerce_payments.onBeforeGatewayRequestSend', function($event) {

    // This doesn't work. No 'order' param available.
    $order = $event->params['order'];

    /* logic using $order,
    -- set $is_valid (boolean) */;

    if(!$is_valid) {

       $transaction = $event->params['transaction'];
       $transaction->message = "This order is not yet complete.";
       $event->performAction = false;
       return $event;

    }

});

Is it at all possible to get the order model inside of this hook? Or is this just not the right place to be doing this?


texts: Can I change TEXT to MEDIUMTEXT/LONGTEXT in database?

texts:
I have a text field in my database in which I'm going to index the contents of a PDF file. Right now the database column for that field is defined as "TEXT" but I need more space since my PDF files can be quite large.

Can I change this column in the database to MEDIUMTEXT or LONGTEXT or will this be a problem with Craft somehow?


texts: I have matrix field set up, is that possible to output Name in Field Settings (refer to the handle: aggressiveBehavior)? Thanks


texts: 'Not authorized to access this resource' when logged in user clicks download link

texts: A user has received this message 'Not authorized to access this resource' when logged in and attempting to download a file by a link. The file was a .zip. I've tested this, but could not replicate the error. Could it be because the user's session had ended?


texts: Display entries that meet multiple tag params

texts:
how would I go about setting up a route and twig template to filter by multiple tags?

Example URL scheme: example.com/tags/tag1/tag2/tag3

where tag1, tag2 and tag3 are tags defined in a tag field inside an entry. The resulting entries list should only output entries with tag1 AND tag2 AND tag3. tag2 and tag3 should be optional. I want to avoid the use of get params such as ?tag=tag1,tag2,tag3.

The ultimate goal is chain multiple tags to get finer results, similar to pinboard.in tag chaining.

Example:https://pinboard.in/t:javascript/t:css/t:webdev
will return entries with javascript AND css AND webdev

My route looks as follows

URI: tags/tag-token/tag-taken2/tag-token3

and my twig template looks like

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

{% if craft.request.getSegment(2) !='' %}

Entries tagged with “{{ tag.title }}”

{% if entries | length %}

        {% for entry in entries %}

{{ entry.getLink() }}..

        {% endfor %}

{% else %}

No entries could be found with that tag.

{% endif %}
{% endif %}

{% if craft.request.getSegment(3) !='' %}
{% set tag2entries = craft.entries.relatedTo('and',
    { element: entry, field: 'tags' },
    { element: entries, field: 'tags' }
) %}
{% set tag2entries = craft.entries.relatedTo(tag2-token) %}

Entries tagged with “{{ tag.title }} and {{ tag-token2}}”

{% if tag2entries | length %}

        {% for entry in tag2entries %}

{{ entry.getLink() }}..

        {% endfor %}

{% else %}

No entries could be found with those tags.

{% endif %}
{% endif %}

{% if craft.request.getSegment(4) !='' %}
{% set tag3entries = craft.entries.relatedTo(tag3-token) %}

Entries tagged with “{{ tag.title }} and {{ tag-token2}} and {{tag-token3}}”

{% if tag3entries | length %}

        {% for entry in tag3entries %}

{{ entry.getLink() }}..

        {% endfor %}

{% else %}

No entries could be found with those tags.

{% endif %}
{% endif %}

I'm am not sure how to go about using the relatedTo() function to filter entries based on those 3 tag parameters in the URL.

Any insight on how to go about this?


texts: Non-admins can't create new entries with front-end form (ajax)

texts:
I'm hitting an issue where signed-in non-admin users can't create a new entry with a front-end entry form (but can edit existing ones). Everything works except for this single instance:

✓ Admin creates and edits entries from non-ajax front-end form (Works!)

✓ Admin creates and edits entries from ajax front-end form (Works!)

✓ Non-admin edits their entries from a front-end form (Works!)

✗ Non-admin creates new entry from a front-end form (Doesn't work)

Craft is returning: "User is not permitted to perform this action"

Tried all of these with and without CSRF on. This is the user group permissions on the section it's submitting to:

Using: Craft 3.1.21.1 (with multi-site)

Edit: Original post stated that it was only a problem with ajax forms, but turns out it's all forms


texts:
the plugin I'm currently working on has to store user inputs which might contain 4 byte unicode characters like emojis. MySQL is not able to handle this with a utf-8 charset. It works if the charset of my tables is set to utf8mb4 and if I add 'charset' => 'utf8mb4' to config/db.php. Since the file config/db.php does not belong to my plugin, but to the installation of Craft itself, I'd like to not modify it.

Alternatively, I can convert the inputs with StringHelper::encodeMb4() but then I would have to do that at every place where something from the outside enters my tables.

Is there any pragmatic way of handling this?

Greetings Jus


texts: How to add year and month to Entry URL Format

texts:
I'd like to make the Entry URL format of a channel look like this: /news/2015/06/my-slug-here

What would I need to enter into the Entry URL Format field in order to do this?

The closest I could manage was this:

news/{postDate|date("Y")}/{slug}

But that only outputs this: /news/2015/my-slug-here

Thanks for any help.


texts: Possible memory leak - GeneratePendingTransforms/ImageMagick

texts:
Wondering if anyone else has had issues with memory and a large amount of image transforms.

I seems like perhaps memory is not being freed up between transforms. When GeneratePendingTransforms is running, that process skyrockets my CPU and memory, and just keeps climbing until it is done.

Possibly related: https://stackoverflow.com/questions/9993085/php-imagick-memory-leak/12835966#12835966


texts: How do I list entries from a single author?

texts:
I'm returning the username as the second segment /blog/username and then setting the username var to craft.request.segment(2).

I'm looking to list a group of entries by that author (username). I've tried:

{% set blogPosts = craft.entries.section('blog').relatedTo(username) %}

I've also tried this:

{% set blogPosts = craft.entries.section('blog').relatedTo({ targetElement: username, field: 'author' })%}

Anyone have a way to list through entries related by author?


texts: Category slug is getting numbers appended to it

texts:
I have a category Australia and have been experimenting with boboldehampsink import plugin.

After deleting categories and starting over the category Australia now has a slug called 'australia-6'. I just want 'australia' but i cant get rid of the  hypen and 6.

I notice the content table has lots of entries for australia but no slugs so I'm wondering about the db schema for craftcms and how come i have got a stuck slug so quickly?


texts: Is the 'find and replace' feature (found in the control panel settings screen) documented?

texts: I see the feature, but would like to read about what and where it finds before replacing.


texts:
Craft Commerce newbie question....

How do I display the image asset for a custom variant field?

I'd like to display the associated image of a product variant in the cart.


texts: Order Entries in a Section by Category Titles

texts:
I currently have entries from a section output simply using a variable like:

{% set beer = craft.entries.section('beverages') %}

All of the beer entries have brands assigned to them using the category field.  How can I display the beer entries by brand? I use that beer variable throughout my templates for entry counts, filters, etc. I'd like to try and keep that in tact if possible.

I tried to use this but it seems to do more than what I need: http://craftcookbook.net/recipes/330.  I also tried the groupBy plugin but had no success in getting that to output anything.


texts:
How do I add additional attributes values while registering a CSS/JS file?

I want to add a media attribute to one of the CSS links

Example code:

{% do view.registerCssFile(siteUrl ~ 'css/print.css', [ ['media' => 'print'] ]) %}

The above code produces an Unexpected token "operator" error.


texts: Error reporting Freeform submission jumps to top of page despite auto form anchor

texts:
I'm using Freeform 1.7.2 and since version 1.6.2 a form anchor is automatically added:

  Added form anchor to be automatically generated so inline error returns can focus down to form, if it's lower down on page.

Yet, the submission still jumps to the top of the page if there is an error. I asked a similar question before, but this was before the name anchor was added. Shouldn't this now work by itself?

Here's my super simple code:

{{ craft.freeform.form("formName", {
   instructionsBelowField: true,
   useRequiredAttribute: true,
}).render() }}


texts: Craft 3 User Registration form errors not showing for custom fields

texts:
I've built a front end user registration form and everything is working well with it except that it's not showing errors for my custom fields. They're set as required in the CP, but the form submits even if they aren't filled in. When the standard required fields aren't filled in the for returns an error but none for the custom fields.

I understand first and last name can't be required. In the example below my custom required fields are participantPhone and participantCity.

<form method="post" accept-charset="UTF-8">

      {{ csrfInput() }}
      <input type="hidden" name="action" value="users/save-user">
      {{ redirectInput('sign-up-ty') }}

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

            {% for error in errors %}

{{ error }}

            {% endfor %}

        {% endif %}
      {% endmacro %}

      {% from _self import errorList %}

      <input id="username" class="form-control" type="text" name="username" {%- if user is defined %} value="{{ user.username }}"{% endif -%} placeholder="username">

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

      <input id="firstName" class="form-control" type="text" name="firstName" {%- if user is defined %} value="{{ user.firstName }}"{% endif -%} placeholder="first name">

      <input id="lastName" class="form-control" type="text" name="lastName" {%- if user is defined %} value="{{ user.lastName }}"{% endif -%} placeholder="last name">

      <input id="email" class="form-control" type="text" name="email"{%- if user is defined %} value="{{ user.email }}"{% endif %} placeholder="email">

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

      <input id="password" class="form-control" type="password" name="password" placeholder="password">

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

      <input id="participantPhone" class="form-control" type="text" name="fields[participantPhone]" {%- if user is defined %} value="{{ user.participantPhone }}"{% endif -%} placeholder="phone">

      {% if user is defined %}
        {{ errorList(user.getErrors('participantPhone')) }}
      {% endif %}

      <input id="participantCity" class="form-control" type="text" name="fields[participantCity]" {%- if user is defined %} value="{{ user.participantCity }}"{% endif -%} placeholder="city">

      {% if user is defined %}
        {{ errorList(user.getErrors('participantCity')) }}
      {% endif %}

      <input id="register-button" class="btn btn-outline-primary" type="submit" value="Register">

  </form>


texts: Adding additional custom fields to Contact Form Plugin from Pixel & Tonic

texts:
I'm working with the P&T contact form plugin:
https://github.com/pixelandtonic/ContactForm

And I can't figure out how to add additional fields to my email, where do I add the additional field to the email template?

Thanks is advance.

MORE INFO:

Error Message:

Internal Server Error
Property "Craft\ContactFormModel.company" is not defined.

HTML Email Form:

$email->body = "Your Name: ".$message->fromName."\n\nCompany:\n\n".$message->company."Email Address: ".$message->fromEmail."\n\nPhone Number: ".$message->phone."\n\nRequests: ".$message->message;


texts: Missing New Entry button/dropdown when overriding the Entries Control Panel page

texts:
I have developed a module which overrides the entries page in the admin control panel as we need some custom fuctionality on that page. It's mostly working, however when I set the element type in the modules index.twig to the modules element type, the 'New entry' button and the dropdown of entry types disappears in the admin panel. If I change the element type in the custom modules index.twig to craft\elements\Entry, the New entry button and dropdown shows. My custom modules element type entry class extends the craft\elements\Entry, so I'm not sure why the button disappears.
What am I missing?


texts: How do you return an instance of a variable class from within a different variable class?

texts:
I have a plugin with the structure something like:

variables
 - PluginVariable.php
 - PluginAnotherVariable.php

Inside PluginVariable.php I have something like:

<?php
namespace Craft;

class PluginVariable
{
   public function foo($parameter)
   {
       $result = craft()->plugin_results->get($parameter);
        return new PluginAnotherVariable($result);
   }
}

Now when I do {{ craft.plugin.foo('something') }} I just get Fatal error: Class 'Craft\PluginAnotherVariable' not found.

I've checked that the filenames and classnames are identical and the namespacing etc so the class most certainly exists but I can't get this to work, has anyone had a similar issue with this and what could be causing it? Thanks.


texts: Track User selected items to send for Inquiry through Form. Better Craft Way?

texts:
I'm new to Craft and wanted to ask if there is a better/easier/more elegant "Craft" way to do something.
On an old site that I'm transferring to Craft, I have a simple bit of Javascript that allows any visitor (not signed in, no user accounts) to select products they are interested in as they browse, and when they are done they can email that list of products, through a form, to a Sales person for more information, etc.
This is NOT an ecommerce site, just a site with a product catalog, so I'm not using CraftCommerce, just regular Craft.
I'm fine doing it the "old way", but since I'm new to Craft I thought there may be something better that I'm overlooking or not aware of.


texts: descendantOf() parameter, entryModel or ID?

texts:
I'm confused about what to pass as a parameter in the descendantOf() function.
I'm developing a website and passing an entry ID as a string (I also tested it as an integer) and everything went fine, untill now. Suddenly, when I try to use it with new template code, that doesn't work anymore. It does however still work in my template I wrote last week.

The docs say that the parameter has to be an EntryModel:

  descendantOf #

  Only fetch categories that are a descendant of a given category.
  Accepts a CategoryModel object.

In this thread on SE, someone says it can be an Entry ID.

  descendantOf accepts either an EntryModel object or an entry’s ID.

However, if I use the next code (category is not a category group, I'm using a structure for it) where currentRegionId is an entryId as a string or integer:

{% for productCategory in product.productCategory.descendantOf(currentRegionId).order("title asc").find() %}

This works. But according to the docs, it shouldn't work, because I'm passing an ID and not an EntryModel.

It also works when I pass that ID while using eager loading:

{% set mainCategories = craft.entries({
    section:            'productCategories',
    level:              2,
    descendantOf:       currentRegionId,
    limit:              null,
    with:               ['productCategoryIcon']
}) %}

However, if I try the next piece of code in another template:

{% for category in entry.applyToCategories if category.descendantOf(currentRegionId) %}

I get this error:

  Argument 1 passed to Craft\BaseElementModel::isDescendantOf() must be
  an instance of Craft\BaseElementModel, integer given

If I pass an EntryModel it does work as expected and according with the docs:

{% for category in entry.applyToCategories if category.descendantOf(craft.entries.id(currentRegionId).first()) %}

So what's going on? Is it something with the way I fetch my entries?


texts: Craft Commerce: How do I handle quantity based discounts on a product level?

texts:
I'm curious what the best way to handle quantity discounts would be on a product/variant level. For example:

The base price of a variant is $3 each, but if you buy 10-19 they're $2 each, and if you buy more than 20 they're $1 each.

A different variant of the same product could have a base price of $10 each, but if you buy 20-49 they're $8 each, and if you buy over 50 they're $6 each.

Thoughts?

EDIT 2 (added file paths)

Based on the comments by Luke and Andris below, I've implemented an adjuster to handle this. I created a table field with the handle quantityPricing with 3 columns: minQuantity, maxQuantity, price. I then applied this field to the variants on a product.

This way a user can create as many prices for quantity ranges as they want. I then create the adjuster, checking the line items via the following:

craft/plugins/myplugin/Adjusters/Myplugin_Adjustername.php

<?php

namespace Commerce\Adjusters;
use Craft\Commerce_LineItemModel;
use Craft\Commerce_OrderAdjustmentModel;
use Craft\Commerce_OrderModel;

class Myplugin_Adjustername implements Commerce_AdjusterInterface {
public function adjust(Commerce_OrderModel &$order, array $lineItems = [])
{

    if (empty($lineItems))
    {
        return [];
    }

    $updated  = [];
    $amount   = 0;
    $adjuster = new Commerce_OrderAdjustmentModel();

    $adjuster->type        = 'Discount';
    $adjuster->name        = 'Quantity Pricing';
    $adjuster->description = 'The overall price of the cart has been adjsuted based on the number of items you are purchasing.';
    $adjuster->orderId     = $order->id;

    foreach ($lineItems as $lineItem)
    {
        $purchasable = $lineItem->purchasable;
        if (!empty($purchasable->quantityPricing))
        {
            $updated[]     = $lineItem->id;
            $updatedAmount = 0;
            foreach ($purchasable->quantityPricing as $qp)
            {
                if (
                    ($lineItem->qty >= $qp['minQuantity'] && $lineItem->qty <= $qp['maxQuantity'])
                 ||
                    ($lineItem->qty >= $qp['minQuantity'] && empty($qp['maxQuantity']))
                )
                {
                    $lineItem->discount = ($qp['price'] - $lineItem->price) * $lineItem->qty;
                    $updatedAmount      = $lineItem->discount;
                }
            }
            $amount += $updatedAmount;
        }
    }

    $adjuster->amount      = $amount;
    $adjuster->optionsJson = ['lineItemsAffected' => $updated];

    $adjuster->included = false;

    if (empty($updated))
    {
        return[];
    }

    return [$adjuster];
}
}

I was also seemingly able to do this using onPopulateLineItem but based on the advice below changed it. My code for that looked like this:

    craft()->on('commerce_lineItems.onPopulateLineItem', function($event){

            $purchasable = $event->params['purchasable'];
            $lineItem    = $event->params['lineItem'];

            // This method checks for quantity pricing and updates
            // line items costs depending on what it finds.
            if (!empty($purchasable->quantityPricing))
            {
                foreach ($purchasable->quantityPricing as $qp)
                {
                    if (
                        ($lineItem->qty >= $qp['minQuantity'] && $lineItem->qty <= $qp['maxQuantity'])
                     ||
                        ($lineItem->qty >= $qp['minQuantity'] && empty($qp['maxQuantity']))
                    )
                    {
                        $lineItem->price = (float) $qp['price'];
                    }
                }
            }
        });

As mentioned in the comments below, I'm not exactly sure why an Adjuster is the better route to go, because both seem to work.

Please don't hesitate to mention if I did something ridiculously stupid somewhere. It certainly wouldn't be the first time.


texts: entries.saveEntry not triggered by ResaveElements task

texts:
I've got a plugin that does a thing when an entry is resaved. It works great. However I need it to fire for every single entry to build some data.

craft()->on('entries.saveEntry', function(Event $event) {
    // Do the thing
});

Why does running a ResaveElements task not fire this yet saving an entry does? Updating a section to cause all of the entries in that section to update doesn't either.

Is there a way I can bulk trigger this to fire outside of me having to write my own script to manually do it.

Thanks!


texts: How to exclude a page from the navigation tree

texts:
I am looking for a way to exclude certain pages from the navigation. I know it must be quite easy, but nothing seems to work for me at the moment.

So I've setup a lightswitch field "exclude from navigation" (cf_hideFromNav)

Problem is that I want the navigation to start only from a certain slug:

{% set topEntry = craft.entries.section('pages').depth(1).slug('club').first() %}
{% set descendants = topEntry.getDescendants()  %}

    {% nav entry in descendants %}

            {{ entry.title }}
            {% ifchildren %}
{% children %}
{% endifchildren %}

    {% endnav %}

how could I incorporate the cf_hideFromNav in this equation?

any help appreciated!
cheers
stefan


texts:
Client has created /exhibitors but wishes it to point to /exhibitors/partners

Can that be done using routes or should we be looking at htaccess rules?


texts:
I'm setting up an FAQ page using a matrix. Each Matrix block contains a question and an answer field. Each Q+A needs to be outputted within a section on the same page such as General, Payments...

I've figured the best way to do this is using categories to assign the Q+As section, limiting each Q+A to one category. I'd then need to output all Q+As for each section with it's category as a header.

Desired Output:

General

Question field output

Answer field output

Question field output

Answer field output

Payments

Question field output

Answer field output

....

I'm fairly new to craft so perhaps I'm overcomplicating it by assigning it to a category, it seems like it's the easiest way to add new Q+As and for them to appear within the right section.

How would I go about outputting this? I've set up a Category Group called 'faqCategories'

Here's my matrix setup:


texts: Output error of the current password correctly

texts:
In the Setting of an account on front-end I've added the possibility to change the password. Please enter your current password, then the new

<form id="userform" class="" method="post" accept-charset="UTF-8">

    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="">
    <input type="hidden" name="userId" value="{{ user.id }}">

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    <input id="password" type="password" autocomplete="off" name="password" class="input-list password" value="">
    <input id="newPassword" type="password" autocomplete="off" name="newPassword" class="input-list password" value="">

    {% if account is defined %}
        {{ errorList(account.getErrors('password')) }} //Current password
        {{ errorList(account.getErrors('password')) }}
        {{ errorList(account.getErrors('newPassword')) }} //New password
        {{ errorList(account.getErrors('newPassword')) }}
    {% endif %}

    <input type="submit" value="Save" class="input-submit">
</form>

Mistakes new password displayed and the error of the current password is not displayed, for example if it is wrong page just reboot and the data will not be saved. How to be


texts:
I am currently working on a plugin that uses a service worker which gets registered  on the front-end by some javascript code and the problem is that the service worker scope is restricted to /cpresources/610c42da/ as the Asset Manager only serves the file from there.

Here's the code which I currently use to integrate with the front-end:

Craft::$app->getView()
                   ->hook('cachecraft', function () {
                       // Pass the service worker url to the site
                       Craft::$app->getView()
                                  ->registerScript(
                                      'const CACHECRAFT_SERVICE_WORKER = "' .
                                      Craft::$app->assetManager->getPublishedUrl('@skayo/cachecraft/assetbundles/cachecraft/dist/js/service-worker.js', true) .
                                      '";',
                                      1,
                                      [],
                                      'cachecraft_service_worker'
                                  );

                       // Register asset bundle
                       Craft::$app->getView()
                                  ->registerAssetBundle(CacheCraftAsset::class);
                   });

So what I need is to serve my service worker from the root (https://example.com/service-worker.js) of the website.
Is that possible somehow?
Another possible way is to serve the file normally at https://example.com/cpresources/610c42da/service-worker.js BUT with a Service-Worker-Allowed HTTP Header.
But I don't know how to do that either...

Thanks in advance for any help!


texts:
I have a matrix field shaped as follows:

MatrixField

Block ( just 1 blocktype )

Field1
Field2
Field3
Field4
FieldN

I want to loop through all the fields inside a block, check if the field is set and other stuff. How can I do it?


texts: Plugin Settings Color Input Javascript Event Listeners

texts: Is it possible to attach JavaScript event listeners to the colour input field in a plugin's settings page, so that when a user selects a colour with the picker I can run an AJAX request?


texts: Plugin only saving one column in database

texts:
I'm having trouble saving some data into the database with my plugin. I am able to save content only if an index is defined on that column, but only if unique=>true is set, which causes some problems because I need repeated values in column b. My function that runs after plugin install works, as I am able to save all the correct content in column A. Data is saved in column b if I set a unique index on it, otherwise the column fills with Null. Any help is greatly appreciated!

Model:

namespace Craft;

class Plugin_MyModel extends BaseModel
{
    public $a = "";
    public $b = "";

    protected function defineAttributes()
    {
        return array(
            'a' => AttributeType::String,
            'b' => AttributeType::String,
        );
    }
}

Record:

<?php

namespace Craft;

class Plugin_MyRecord extends BaseRecord
{
    public function getTableName()
    {
        return 'my_table';
    }

    protected function defineAttributes()
    {
        return array(
            'a'     => AttributeType::String,
            'b' => AttributeType::String,
        );
    }

    public function defineIndexes()
    {
        return array(
            array('columns' => array('a'), 'unique' => true),
        );
    }
}

Service that gets data from API call and attempts to save in DB:

<?php

namespace Craft;

class Plugin_MyService extends BaseApplicationComponent
{

    protected $myRecord;

    public function __construct($myRecord = null)
    {
        $this->myRecord = $myRecord;
        if(is_null($this->myRecord))
        {
            $this->myRecord = Plugin_MyRecord::model();
        }
    }

    public function saveItem(Plugin_MyModel &$model)
    {
        if ($id = $model->getAttribute('id')) {
            if (null === ($record = $this->myRecord->findByPk($id))) {
                throw new Exception(Craft::t('Can\'t find item with ID "{id}"', array('id' => $id)));
            }
        } else {
            $record = $this->myRecord->create();
        }

        $record->setAttributes($model->getAttributes());
        if ($record->save()) {
            // update id on model (for new records)
            $model->setAttribute('id', $record->getAttribute('id'));

            return true;
        } else {
            $model->addErrors($record->getErrors());

            return false;
        }
    }

    public function loadAllItems()
    {
        $items = $this->api();

        foreach($items['Items'] AS $item)
        {
            $new_item = new Plugin_MyModel();
            $new_item->a = $item['a'];
            $new_item->b = $item['b'];
            $this->saveItem($new_item);
        }
    }

    private function api(){
        //Returns API Data
    }
}


texts:
Can any help simplify this js/twig code? The code links to some tabs that show floorplans of the property being sold. The specified aria-controls refers to a supertable field called floorLevel that has the loop.index included, so for example if I put [aria-controls='{{ row.floorLevel }}{{ loop.index }}'] it would output those names. I got it working so that when the user clicks on the tab it also changes the separate information about the measurements, but I couldn’t find of a less manual way of doing it, but I’m sure there must be an easier way?

{% includejs %}
{% for row in entry.floorplans.limit(1) %}
$( "[aria-controls='groundFloor1']" ).on( "click", function() {
  $( "#dimsTarget1" ).addClass( "is-active" );
  $( "#dimsTarget2" ).removeClass( "is-active" );
  $( "#dimsTarget3" ).removeClass( "is-active" );
  $( "#dimsTarget4" ).removeClass( "is-active" );
  $( "#dimsTarget5" ).removeClass( "is-active" );
});
{% endfor %}
{% for row in entry.floorplans.limit(1) %}
$( "[aria-controls='firstFloor2']" ).on( "click", function() {
  $( "#dimsTarget2" ).addClass( "is-active" );
  $( "#dimsTarget1" ).removeClass( "is-active" );
  $( "#dimsTarget3" ).removeClass( "is-active" );
  $( "#dimsTarget4" ).removeClass( "is-active" );
  $( "#dimsTarget5" ).removeClass( "is-active" );
});
{% endfor %}
{% for row in entry.floorplans.limit(1) %}
$( "[aria-controls='secondFloor3']" ).on( "click", function() {
  $( "#dimsTarget3" ).addClass( "is-active" );
  $( "#dimsTarget1" ).removeClass( "is-active" );
  $( "#dimsTarget2" ).removeClass( "is-active" );
  $( "#dimsTarget4" ).removeClass( "is-active" );
  $( "#dimsTarget5" ).removeClass( "is-active" );
});
{% endfor %}
{% for row in entry.floorplans.limit(1) %}
$( "[aria-controls='thirdFloor4']" ).on( "click", function() {
  $( "#dimsTarget4" ).addClass( "is-active" );
  $( "#dimsTarget1" ).removeClass( "is-active" );
  $( "#dimsTarget2" ).removeClass( "is-active" );
  $( "#dimsTarget3" ).removeClass( "is-active" );
  $( "#dimsTarget5" ).removeClass( "is-active" );
});
{% endfor %}
{% for row in entry.floorplans.limit(1) %}
$( "[aria-controls='basement5']" ).on( "click", function() {
  $( "#dimsTarget5" ).addClass( "is-active" );
  $( "#dimsTarget1" ).removeClass( "is-active" );
  $( "#dimsTarget2" ).removeClass( "is-active" );
  $( "#dimsTarget3" ).removeClass( "is-active" );
  $( "#dimsTarget4" ).removeClass( "is-active" );
});
{% endfor %}
{% endincludejs %}


texts: Craft 3, Freeform form not submitting file upload

texts:
I have a simple form with a file upload field in built with the latest version of Craft 3 and Freeform and I haven't been able to get the file upload to the field to work. When you submit the form with all fields completed and a file selected, you get a submission error saying "Error! Please review the form and try submitting again". Here is my template code, any idea what's wrong?

{# -- Freeform Form --#}
{% set form = craft.freeform.form("contact") %}

{{ form.renderTag({returnUrl: "/contact/thanks"}) }}

{% if form.hasErrors %}

        {{ "Error! Please review the form and try submitting again."|t('freeform') }}

{% endif %}

{% set fullName = form.get("fullName") %}
{% set emailAddress = form.get("emailAddress") %}
{% set phone = form.get("phone") %}
{% set resume = form.get("resume") %}

    <input type="text" name="{{ fullName.handle }}" id="{{ fullName.value }}" placeholder="Full Name*" autocomplete="off" class="text"/>
    {{ fullName.renderErrors() }}

    <input type="email" name="{{ emailAddress.handle }}" id="{{ emailAddress.handle }}" placeholder="Email Address*" autocomplete="off" class="text">
    {{ form.get("emailAddress").renderErrors() }}

    <input type="text" name="{{ phone.handle }}" id="{{ phone.handle }}" placeholder="Phone" autocomplete="off" class="text">

    {% if form.get("phone").hasErrors %}This field is required!{% endif %}

    Attachment

     Attach Resume *
    <input type="file" class="form-control-file" name="resume[]" id="resume"/>

    * Required
    <button type="submit" class="button">Send</button>

{{ form.renderClosingTag }}

{# -- End Freeform Form --#}


texts:
I'm using Craft 3.6.4.1 and I need to delete a whole tranche of users from the database (that has derived from another Craft instance).
I've been deleting by hand via the CMS but note that loads of user related rows remain in the database:

The CMS is reporting only the 4 users which I want to retain, but craft_users still has 10,706 rows in it.

From which tables should I clean out rows that pertain to users I want to delete?
I note the additional following tables which seem relevant in ways I'm unsure of:
craft_usergroups_users
craft_userpermissions
craft_userpermissions_usergroups
craft_userpermissions_users
craft_userpreferences


texts: User photos not showing after replacing photo

texts:
I recently updated some of the photos for a user group. I'm using the default user photo field.

I'm displaying the user photos on the front-end of my site and the images were displaying just fine. After replacing the images the image tag on the front-end of my site is showing a broken image. If I view the image tag src it points to the old image filename, not the updated file's filename.

I have cleared Craft's cache.

How I can make getPhotoUrl() use the new filename?


texts: Order tags by count - e.g. Top 10 Tags Used

texts: I would like to have a Top 10 Tags list in descending order. I'm able to list and limit 10 tags used, but the order parameters are limited to name, group, and date essentially.


texts: Anonymous access to controller action fails

texts:
I have this controller, and I've set $allowAnonymous to true, but I'm still getting redirect to CP login:

class SitemapController extends BaseController
{
    protected $allowAnonymous = true;

    public function actionXml()
    {
        ...
        $this->renderTemplate('sitemap/list.xml', array(
            'entries' => $entries,
            'sections' => $enabledSections
        ));
    }

}

Is there anything I'm missing?


texts: How can I install modules with Composer?

texts:
Installing a Craft 3 plugin via Composer is pretty simple. You require the package, update Composer, and install it via the CMS.

My circumstances require that our company use a private Module on all projects. But installing the package via Composer always puts the Module into the default vendor directory.

So how can I install a module into the modules folder?


texts: List Orders with datePaid is within last 14 days using the Element API plugin

texts:
I want to list the orders with datePaid is within last 14 days. But I cannot workout the correct criteria, and I don't know if isPaid works correctly as well:

'criteria' => [
    'dateUpdated' => '>=' . date('Y-m-d'.' 00:00:00', strtotime("-14 days")),
    'isPaid' => '1',
],


texts: Feedme Skip Entry if No Matching Elements on Field

texts:
Is there a way on Feedme to not import an entry if it doesn't have a match on a specific field?

e.g. If there is no entry that it matches up to, don't import it.

Here's the current code I have:
Event::on(Process::class, Process::EVENT_STEP_BEFORE_ELEMENT_SAVE, function (FeedProcessEvent $event) {
    $myField=$event->feedData['myfieldname'];
    if ($myField == null){
        $event->element->isValid=false;
    }
});

The above processes the data getting loaded in. Here's code for processing data after it's parsed.
Event::on(Fields::class, Fields::EVENT_AFTER_PARSE_FIELD, function(FieldEvent $event) {
    if ($event->fieldHandle['merchants'] == null) {
    $event->isValid=false;
    }
});


texts: How can I search for a user id in a custom field in my entries loop?

texts:
In my template I have the user id variable pulled out of the URL and then I want to search through my entries for posts where that user id is included in a custom field with a users field type as well as the default "author" field.

Here's what I've got working for the author field, and I just want to include my custom "coAuthors" field type as well...

With a url like "/author/joyce"

{% set username = craft.request.segment(2) %}
{% set author = craft.users.username(username).first() %}
{% set entries = craft.entries.section('blog').authorId(author.id) %}

That works great, but how can I also include entries where that author id is set in the coAuthors custom field?

I can't even seem to find it separately. This turns up nothing

{% set entries = craft.entries.section('blog').search('coAuthors.username:author.id') %}


texts: Imported entries showing wrong post date

texts:
Anyone familiar with InstaBlog plugin? I need to import some entries (not Wordpress) and everything works fine except the published date for all entries is showing today's date. When I view the entries in the control panel, the post date for each entry is correct, but is displaying the wrong date on front end. The InstaBlog template uses this to display the dates

{{ blog.postDate.format('F d, Y') }}

Has anyone encountered this?


texts: How can I merge entry values to create a select dropdown

texts:
For the life of me I can't seem to find an answer for this question, so here goes!

I have a field called jobCounty in a section called jobs.

The jobCounty is selected in the CP from a drop down list I've created of english county names.

There are about 30 entries each with most with different county names, but some repeat the same county name.

I want to create a form select, with options that are populated by the jobCounty names that have been selected, but avoid repeats. Ideally in alphabetical order.

This question seems to feel like it might be answering the same question but for for a different purpose.

Related entries from a dynamic dropdown

Any help much appreciated

Stephen


texts: I've setup a dev site on a subdomain alongside the production site and modified the config.php and db.php files on both installs for a multi-environment config. Since I only need to work on plugins and template files on the 'dev' site, would it be crazy to have the 'dev' site use the same mysql database as the live site? What would be the downfall in doing this?