texts: Help with correct syntax regarding multisort please

texts:
Hi hoping for a quick resolution on this as a lot of scripting relies upon it. I have an array:

{% set furniture = [
     {
         'name': 'chair',
         'price': '100'
     },
     {
         'name': 'bench',
         'price': '500'
     }
   ]
%}

and I'm trying to sort it by price:

{% set sorted = furniture|multisort(['price'],['SORT_DESC'],['SORT_REGULAR']) %}

but all I get is this error:

array_multisort(): Argument #2 is expected to be an array or a sort flag.

I've also tried:

{% set rides = furniture|multisort(furniture['price'],['SORT_DESC'],['SORT_REGULAR']) %}

but then I get the error:

Key "price" for array with keys "0, 1" does not exist.

I've kind of run out of ideas as to how to tackle it. Thanks.


texts: Retrieving Entries by Category & Exclude by Tag

texts:
I have an endpoint that I want to retrieve entries by a category, but then exclude entry ids if they have a certain tag. It seems to me that the relatedTo param overrides the id param that says not in include a set of ids. In general when using the ElementCriteriaModel is there a way to accomplish this?

'api/custom-endpoint.json' => function() {

    $tagSlugs = array('tag-one', 'tag-two');
    $tagIds = Tag::find()->group('tagGroup')->slug($tagSlugs)->ids();
    $categoryId = Category::find()->group('categoryGroup')->slug('category-slug')->ids();
    $excludeIds = Entry::find()->relatedTo($tagIds)->ids();

    return [
        'serializer' => 'jsonFeed',
        'elementType' => craft\elements\Entry::class,
        'criteria' => [
            'section' => 'blog',
            'id' => 'not ' . implode($excludeIds),
            'relatedTo' => [
                'targetElement' => $categoryId,
                'field' => 'categories'
            ],
        ],
        'transformer' => function(craft\elements\Entry $entry) {
            return [
                'title' => $entry->title,
                'url' => $entry->url,
            ];
        },
        'pretty' => true,
    ];
}


texts:
Is it not possible to define multiple conditions in an if statement?

{% if foo == 'x' || foo == 'y' %}

I tried this and got an error:

  Unexpected token "punctuation" of value "|" ("name" expected)


texts: Multiple (dev) sites running locally; session seemingly randomly times out

texts:
I've got multiple sites running on XAMPP (I'm on Windows 10). Each has its own domain (eg. dev.example.local, dev.otherexample.local, etc).
When I try to have more than one site CP page open in the same browser, I tend to randomly encounter session timeout modal windows.
Craft 2 had the overridePhpSessionLocation which I suspect might help, but I can't find the equivalent in Craft 3.
Any suggestions?


texts:
can someone explain how I can install the license of a plugin in my installation?

concretelly I have the craftql license key in https://id.craftcms.com/licenses/plugins and I want to setup that into my installation.


texts: How can I set shipping address same as billing?

texts:
By default all users fill out shipping information first, and then can select "Use same address for billing".

Because 95% of items I am selling are digital, 9 out of 10 sales will be digital and have no shipping.

What I would like to do is ask for a billing address, and then user the <input type="hidden" name="sameAddress" value="1"> to set the shipping address.

This is what I have now which works...

shop/checkout/addresses

    {% include 'shop/_includes/addresses/fieldset' with {
        title: "Billing Information"|t,
        class: 'ShippingAddress',
        name: 'shippingAddress'
    } %}

    {% include 'shop/_includes/addresses/fieldset' with {
        title: "Shipping Information"|t,
        class: 'BillingAddress hidden',
        name: 'billingAddress'
    } %}

...

{% if freeShipping %}
    <input type="hidden" name="sameAddress" value="1">
{% else %}
    <input type="hidden" name="sameAddress" value="0">

    <input type="checkbox" name="sameAddress" id="sameAddress" checked="checked"> Use same address for shipping

{% endif %}

As you can see I'm still setting the shipping first, To the user it just looks like I am asking for billing first. This works until I have something that requires shipping. If a user un-checks "Use same address", then I show what looks like the Shipping Address. But in reality, it's the billing address they are changing.

TL;DR

By default, shipping drives billing. I would like billing to drive shipping.

Thank you for any suggestions!


texts: is it posible to have dynamic Title for my article image grid?

texts:
I have an image grid for my articles, and its sorted by the type of articles. So all the articles of a certain type is all put in the same item grid, but I want to sort it after the brand aswell by having my image grid sort under a logo of the brand. So if I have 2 different brands of 1 type of article, I want 2 image grids on the same page, neatly sorted under their respective logo.

This is what I have so far:

    {% for entry in entry.children %}
    {% if entry.type=="lift" and entry.liftMerke=="nifty" %}

        {% for entry in entry.children %}
        {% if entry.type=="lift" and entry.liftMerke=="nifty" %}

                {% set bilde = entry.bilde.one() %}
                {% if bilde %}

                {% endif %}

{{ entry.title }}

Arbeidshøyde: {{ entry.arbeidshoyde }}

{{ entry.title }} | {{ entry.arbeidshoyde }}

       {% endif %}
       {% endfor %}

    {% endif %}
    {% endfor %}

So this gives me just a whole bunch of logos whitch is not what I want. Is there something I can do to make it search through the entry.children articles, and do something only once(print logo) if something is true for either one of the articles? Really appreciate any help!

EDIT:

So I have been playing around with this abit now, but I cant really get it to work. I forgott to mention something inportant in my post aswell, I am using craft3 beta.

So I am abit unsure if the errors I am encountering are me not really understanding what I am doing or if it is related to differences between craft 2 and 3.

I created a catogory group(liftmerker) and two catogories(denka, nifty). I added a image field(image field is called "bilde") to the catogories where I uploaded the logos.

This is what the code looks like at the monent:

    {% set entries = entry.children | group( 'entryCategory.one().title' ) %}
    {% set brands = craft.categories.group( 'liftmerker' ).titles %}
    {% for brand in brands %}
        {% set brandEntries = entries[ '' ~ category ] | default( [] ) %}
        {% if brandEntries | length %}

            {% for entry in brandEntries %}
                ...
            {% endfor %}

        {% endif %}

    {% endfor %}

This gives me an error that I dont really understand:

TypeError
Argument 1 passed to craft\web\twig\Extension::groupFilter() must be of the type array, object given, called in /home/vagrant/Code/Gantic/Gantic3/storage/runtime/compiled_templates/c3/c383e9d48f1c478076ea5c1b97037f5aa9b4242fb3b6dcb877a0488b0b8b32b7.php on line 114

Any suggestions for what I can do different or what line in the code is causing the error?


texts: How to get the original entered password value on registration form error?

texts:
I want to customize the user-registration-form with error/success-states.
If, for example, the user enters a wrong email, but correct username and password, it would be nice to set the value of the password input field back to the original entered password - like the username-field does.

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

In matter of UX, this does not really works good, because it's the hashed version of the password. The origin was much shorter. So the user could be a bit surprised...
Not setting the value, but set the state to success with an empty field is not much better.

Is it possible, to set the origin entered password as the value?
If, does this work on resend the form?
Any other ideas are welcome.

Tnx


texts:
I'd like my form to return to the same page with a param ?success.

The page slug is dynamic though so will change depending on what form you are on.

/dynamic-url?success

{% set entrySlug = craft.request.lastSegment %}

                                    {{ craft.freeform.form("landingPage", {
                                        id: "form-landing",
                                        useRequiredAttribute: true,
                                        returnUrl: "{{ entrySlug }}?success"
                                    }).render() }}

Obviously if i just use returnUrl: "?success" it takes me back to the homepage.

The idea of this is so I can trigger facebook events upon form completion, so open to any better approaches.

Thanks


texts: Adding a new site returns 503 Service Unavailable

texts:
I successfully installed Craft locally and my primary site is up and running, but when I add a new site with it's own base URL I cannot access it due to a HTTP 503 error.

I've tried various combinations of environment variables and aliases for the URL, and for now I just added the base URL directly in the CP (anotherdomain.locahost).

I also played around with various vhosts settings in XAMPP (Win 10) to no avail. It seems to me that the vhost is properly configured.

Here is my stack trace, any help would be much appreciated.

2020-01-21 15:07:49 [-][-][-][trace][yii\web\Application::handleRequest] Route requested: 'templates/render'
2020-01-21 15:07:49 [-][-][-][trace][yii\base\Controller::runAction] Route to run: templates/render
2020-01-21 15:07:49 [-][-][-][error][yii\web\HttpException:503] craft\web\ServiceUnavailableHttpException in D:\Web\dev\folder\vendor\craftcms\cms\src\web\Controller.php:163
Stack trace:
#0 D:\Web\dev\folder\vendor\craftcms\cms\src\controllers\TemplatesController.php(72): craft\web\Controller->beforeAction(Object(yii\base\InlineAction))
#1 D:\Web\dev\folder\vendor\yiisoft\yii2\base\Controller.php(155): craft\controllers\TemplatesController->beforeAction(Object(yii\base\InlineAction))
#2 D:\Web\dev\folder\vendor\craftcms\cms\src\web\Controller.php(187): yii\base\Controller->runAction('render', Array)
#3 D:\Web\dev\folder\vendor\yiisoft\yii2\base\Module.php(528): craft\web\Controller->runAction('render', Array)
#4 D:\Web\dev\folder\vendor\craftcms\cms\src\web\Application.php(299): yii\base\Module->runAction('templates/rende...', Array)
#5 D:\Web\dev\folder\vendor\yiisoft\yii2\web\Application.php(103): craft\web\Application->runAction('templates/rende...', Array)
#6 D:\Web\dev\folder\vendor\craftcms\cms\src\web\Application.php(284): yii\web\Application->handleRequest(Object(craft\web\Request))
#7 D:\Web\dev\folder\vendor\yiisoft\yii2\base\Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#8 D:\Web\dev\folder\web\index.php(21): yii\base\Application->run()
#9 {main}


texts:
I installed the plugin for Apple News (https://github.com/pixelandtonic/AppleNews) but did not understand the configuration instructions.

I created a file at craft/config/applenews.php with the following:

<?php

return [
'channels' => [
    [
        'class'     => 'applenewschannels.MyNewsChannel',
        'channelId' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'apiKeyId'  => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'apiSecret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    ],
  ],
];

I created a craft/applenewschannels folder and added MyNewsChannel.php and MyNewsArticle.php but the “Apple News Channels” pane has not appeared on the edit entry page. What am I missing?


texts: Access environment information in template

texts:
Is there a way to check what environment craft is running on - ie, dev or not dev - via the template.

For example:

{%if env is 'dev'%}
    hello dev
{% else %}
   hello world
{% endif %}


texts: Create Manual Order for another customer

texts:
Is there any way for an admin to use the Manual gateway and create an order for another customer in the system? Or is the only option for the admin to Log In as User feature and go through the checkout process that way?

I'm thinking of either a plugin or front-end templates protected by {% if currentUser.can('accessCp') %} where the admin can select customers from a drop-down, select a product from another drop-down, then checkout using the Manual Gateway.

My situation is I have a labor request product. My client sells digital PowerPoint files of church hymnal songs. A customer can purchase a "Song Request" if the customer needs a song that my client has not created yet. So the sale is on the request. But once the product is made available, I need a way to give that product to the customer.

I don't think there is anyway to edit an order, so is there anyway to manually create a new order? Maybe there is a way I can use guest checkout with the customer email address, but still stay logged in as the admin?

However, this note from the sample shop\checkout\index.html template seems to indicate that you can't manually set the email address to someone else if you are already logged in, yourself.

  {#
              Setting the guest email address on the guest customer and order.
              This will have no affect if the user is currently logged in as the cart uses the currentUsers email address.
              #}

Is there any way to edit the Order Options after a product has been purchased? If I could assign during the checkout {{ item.options.ProductId}} = 0, then after the product is uploaded, I could just edit that Option to match the new product (or variant) id and query that for the customer on their account page.


texts: Updating old setup (3.0.41.1) to 3.1.0 various errors every time

texts:
I'm unfortunately dealing with a very old system that hasn't been updated in a long time. I've been able to update it up to 3.0.41.1 but once I attempt to go any further I get tons of different errors. They primarily seem to be migrations. I keep having to do a restore of the DB I'm working with over and over to try to sort this out but I'm not sure what else to be looking for.

Any recommendations? (besides updating things at the right time?)

UPDATE 1:

When attempting to update from the web interface (which i think attempts to go straight to 3.4.5) I consistently get the following error:

Composer output: Package "craftcms/vue-asset" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for craftcms/cms 3.4.5 -> satisfiable by craftcms/cms[3.4.5].
- craftcms/cms 3.4.5 requires twig/twig ~2.12.0 -> satisfiable by twig/twig[v2.12.3, v2.12.2, v2.12.1, v2.12.0] but these conflict with your requirements or minimum-stability.
Problem 2
- spicyweb/craft-embedded-assets 2.0.12 requires craftcms/cms ^3.0.0 -> satisfiable by craftcms/cms[3.4.5].
- spicyweb/craft-embedded-assets 2.0.12 requires craftcms/cms ^3.0.0 -> satisfiable by craftcms/cms[3.4.5].
- spicyweb/craft-embedded-assets 2.0.12 requires craftcms/cms ^3.0.0 -> satisfiable by craftcms/cms[3.4.5].
- craftcms/cms 3.4.5 requires twig/twig ~2.12.0 -> satisfiable by twig/twig[v2.12.3, v2.12.2, v2.12.1, v2.12.0] but these conflict with your requirements or minimum-stability.
- Installation request for spicyweb/craft-embedded-assets 2.0.12 -> satisfiable by spicyweb/craft-embedded-assets[2.0.12].

Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.


texts: Export from Craft 3.4 to Craft 3.0 using Feedback

texts:
I have a very strange situation.

A production site is running Craft3.0 - there is no easy way to get this site up to Craft3.4. This is not possible at present because of the server and upgrading PHP.

I have used FeedMe locally on Craft3.4 to import a few thousand entries into the site.

Now I have these entries on my local machine running Craft3.4, and I need them placing onto the live site which is Craft3.

Exporting that tables that I think are needed results in multiple copies of the entries being created. E.g. 5 of the same news articles all with the same slug.

I am exporting and then importing the following tables...

craft_assets (because of images on the entries)
craft_categories
craft_content
craft_elements
craft_elements_sites
craft_entries
craft_relations
craft_userpermissions
craft_userpermissions_usergroups
craft_userpermissions_users
craft_userpermissions_users
craft_users (because of authors)

Am I missing a table?

Am I confusing Craft3 by adding a certain table?

Is this impossible because of the differences between Craft3 and 3.4? I have looked at the tables and they are identical so I am unsure why it is getting itself into such a state.

I realise this is a very odd and suboptimal situation - but I am stuck with this at present with no way to upgrade the server and the PHP version.


texts: Updating Craft 3 from ver. 3.0.28 10/23/2018

texts:
I have to update Craft 3 from ver. 3.0.28 10/23/2018, but i got this message:
You’ve reached a breakpoint! More updates will become available after you install Craft CMS 3.0.40.

How can i fix this problem?
Updating from the Terminal is no available with my version.
https://docs.craftcms.com/v3/updating.html


texts:
I would like to restrict entries to specific users on the frontend via a User Field called userSelector. It should be possible to have more than 1 user. I understand groups might work, but I feel like it's easier to just select the user(s) directly on the entry.
I know the code below won't work, but hopefully, it shows my intentions a bit more.
{% set users = entry.userSelector.all() %}
{% if currentUser.email == users.email %}
    Show the page
{% else %}
    Permission Denied
{% endif %}

Very open to other suggestions.


texts: Setting Imager crop position dynamically

texts:
I have a simple dropdown attached to each asset that allows the user to select the desired crop position (in %, so '0% 0%' , '0% 50%' , and so on).

In my twig template I have this inside a for loop

{% set entryImage = entry.pageHeader.first() %}
{% set imageCrop = entryImage.cropPosition %}

  {% set transformedImages = craft.imager.transformImage(entryImage, [
        { width: 1680, jpegQuality: 75 },
        { width: 1080, jpegQuality: 75 },
        { width: 680, jpegQuality: 70 },
        { width: 480, jpegQuality: 70 }
      ], { ratio: 21/9, position: 'entryImage.cropPosition' }) %}

As you can see, I've set the crop position inside the imageCrop variable and when I print it to screen the correct value is there.

But how the hell do I get the value that is set inside that imageCrop variable into my transformedImages array? I keep getting errors like: Undefined offset: 1.


texts: Forward users to the right template according to the current active site's language

texts:
I am using Craft 2 and trying to forward users to the right template according to the current active site's language when they reset their password. The problem is that the reset URL that Craft creates and sends the user's email only forwards it to the primary site.

To be more clear, if the user changed site language to Germany and sends for a reset password request, the URL sent to his email sends him to the primary site, which is the French  one.

I added the setPasswordPath in the config file as such:

'setPasswordPath' => array(
    'de' => 'de/passwordreset'
    'fr' => 'passwordreset',
),

But still not working. What am I doing wrong?


texts: .getUrl() outputting {{ siteUrl }} in address

texts:
I haven't used Craft in a while now and I have just revisited it, I'm trying to output an image URL from a global matrix field like so:

{% for block in globalName.matrixField %}

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

        {% set image = block.blockType1.first() %}

        link

    {% endif %}

{% endfor %}

But it keeps outputting as: {{ siteUrl }}/resources/images/my-image.jpg (instead of actually outputting the website URL).

Am I missing something?


texts: How do you rename a tag globally in the Craft Control Panel?

texts:
Is there a way to rename a tag, globally, within the Craft CP?

If not directly, would the Find and Replace tool include tags?


texts: Incorrect content/mime-type on S3 SVG upload

texts:
I've setup an S3 asset source for images and it's working well for everything but SVGs.

SVGs are uploaded with the default content-type of binary/octet-stream where the correct content-type would be image/svg+xml.

Am I doing something wrong or is this a bug?


texts: Commerce: notification emails to multiple custom recipients fails

texts:
Notification emails keep failing to send if I have multiple addresses set. I've tried comma separated with and without a space after, both fail the same way.

The error in the craft.log:

Email error: Invalid address: (addAnAddress to): blah@stuff.com,things@stuff.com

The error in the commerce.log:

[Forced] Email “New Order - Admin” could not be sent for order “a713f1d”. Errors:


texts:
I've inherited an existing website created using CraftCMS and hosted on Fortrabbit.

I'm fairly new to CraftCMS but anxious to get started on a couple of updates. The site currently exists on Fortrabbit. I have SSH and SFTP access and can see the files and have a fresh version of CraftCMS locally installed but unsure how to bring in the files. I'm aware it's built on the server so just not sure what parts I need to bring locally.

I have already grabbed and imported the DB to the MySQL content but just need this last step.

Many thanks.


texts: Craft 2 new locale and dealing with root-relative links

texts:
Hi I am adding new locale which is jp and I have a huge problem with href tag.
Our paragraph field have href links using relative link like this:
 page a

When I hover to the link. It show "example.com/page_a" instead of "example.com/jp/page_a".
Our siteUrl was set up correctly which is shows example.com/jp.
Is anyone face this issue before and how to handle it.


texts:
Sometimes my clients site is down and it shows one of the following errors (black text on white screen):

[error] [system.db.CDbCommand] CDbCommand::fetchAll() fout: SQLSTATE[HY000]: General error: 1 Can't create/write to file '/tmp/#sql_135b_0.MYI'

CDbCommand faalde tijdens het uitvoeren van volgend SQL statement: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'krycer_be_craft.t' doesn't exist

They are the same errors that are shown in the log files (with a bunch of other stuff).
The wierd thing is, it doesn't happen all the time. Nothing changed on the site scince a few weeks also. A few weeks ago I restored a database back-up, but everything worked fine untill now.

Does anyone has an idea? I updated to the latest version and cleared the cache, maybe it'll help but I would like to know the reason behind these errors.


texts: Need a little help with basic understanding of how categories work

texts:
I am trying to figure out how I can put categories to use, and I need some help.

I have created a category group called "group1", and 2 catogories inside called "cat1" and "cat2". and I have added the catogorie field to some articles in a structure so that I have a few linked to both cat1 and cat2.

My goal simply to make a forloop listing the catogorie title of both cat1 and cat2, and create an UL with the entry.title of the entries in each catogorie.

This is my code:

{% for cat in craft.categories.group('group1') %}

{{ cat.title }}

    {% for entry in craft.entries.section('structure').level(3).relatedTo(cat) %}

{{ entry.title }}

    {% endfor %}
{% endfor %}

This gives me the two catogorie titles, but no entry titles. I dont think I understand how to use the related to group part. Would really appreaciate some help figuring this one out.


texts:
Just adding hreflang tags to the head on all pages of my multi-locale site...

{% for locale in craft.i18n.getSiteLocales() %}
    <link rel="alternate" href="{{ entry.url }}" hreflang="{{ locale }}">
{% endfor %}

Nearly there, but obviously this outputs my list of locales with the entry url for the current locale only. What I need is to output the entry url for each locale. Anyone done this before?


texts: Method for creating Category Group landing pages

texts:
I have a selection of category groups as follows:

Suitability
Colour
Finish
etc

They all have many categories within them. I have set up some routes for /suitability etc to show the user a /shop/category.twig template for the category group landing pages.

But my issue I'm having is getting the context of the page based on the slug.

I have read a very old SE post that kind of offers a solution, but it's only useful for getting the name. I need to build on this to get the group. But it doesn't look like there's a way to 'get' a category group.

I may be wrong and missed something but I've only found ways to obtain category group info based on context of a category itself as follows:

{# get the category group slug #}
{% set slug = craft.app.request.segment(1) %}

{# get the first category within this group and output the groups' name #}
{% set catGroupName = craft.categories.group(slug).first.group %}

Any advice on a much neater way to obtain a category group would be handy. Thanks


texts: Craft 3: When querying for Matrix blocks in a plugin, how do you sort by a custom field?

texts:
My goal is to order an element query of Matrix blocks by a custom field. Any thoughts?

namespace modules\mymodule\services;

use Craft;
use yii\base\Component;
use craft\elements\MatrixBlock;

class MyService extends Component
{
    public function myFunction()
    {
        $blocks = MatrixBlock::find()
            ->type('myBlockType')
            ->orderBy(???)
            ->all();
    }
}

Edit to show working Example

(This is showing how I used this to sort by a custom date field)

$blocks = MatrixBlock::find()
    ->type('blockType')
    ->fieldId($fieldId)
    ->where(['>', 'content.field_blockType_fieldHandle', new \yii\db\Expression('NOW()')])
    ->orderBy(['content.field_blockType_fieldHandle' => SORT_ASC])
    ->all();


texts: How to update a matrix field for an entry with craft()->db->createCommand()?

texts:
Is it possible to update a matrix field for a know entry id and a known matrixfield id with craft()->db->createCommand().

The matrixfield has 3 fields as follows:

time (already set - category field set as times i.e. 09:00:00)
session (entries field)
booked (lightswitch)

What I want to do is this:

UPDATE (tablename??) SET matrixfield.session = knownEntry, matrixfield.booked = 1 where matrixfieldId = knownMatrixfieldId

The reason for doing it with craft()->db->createCommand() is it will be fired within the onSaveEntry event as per my previous post

I've done a lot of head scratching and searching on this one but I'm coming up blank.


texts: Sprout Forms: Localized version of form with translated labels?

texts:
Does  the Sprout Forms plugin tap into the internationalization feature of Craft Pro, i.e. does it support adding localized versions of existing forms, similar to translated section entries?

What I'm looking for is creating forms where all field names and values are identical between language variants, but labels and notifications may differ per locale. (This is opposed to setting up multiple forms that are not tied together and write to separate tables in the back-end.)

In the docs, all I can find is a reference to translated error messages, which are the smallest of my concerns. — That same approach might work for the main conent of the form as well, but it could not be managed via the plugin's control panel.


texts: How can I display the Discount Value onSale of Products

texts:
I am trying to display the Discount Value (%) of Products with the onSale Tag. What works for now is to display only the Products which are onSale. But I can't figure out which value stores the Discount Value.

{% set products = craft.commerce.products.find() %} {% for product in products %}

    {% if product.defaultVariant.onSale == true %}

Sale!

{{ amount.saleAmount }}/h6>

off

    {% endif %}


texts: How to find pros to take on maintenance/improvement of pre-existing sites built with Craft?

texts:
I know of the Craft Professionals page on Straight Up Craft, but I'm curious if there is a more targeted way to find Craft pros who are willing and able to take on maintenance of pre-existing Craft sites.

This Q/A site seems obviously wrong for that. Are there other places to post requests or find a list of potential partners?

I hope this question is considered on-topic. Thanks!


texts: Class not found error when running unit test on a plugin service

texts:
I am writing a plugin and want to unit test my services.  I am following the example given here: https://github.com/amacneil/cocktailrecipes. The problem is when I run my application, I get a

PHP Fatal Error: Class 'TournamentData_IndividualService' not found.

Here is the problem portion of the test code:

<?php
namespace Craft;

use \Mockery as m;
use PHPUnit_Framework_TestCase;

class TournamentData_IndividualServiceTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->ingredientRecord = m::mock('Craft\TournamentData_IndividualRecord');
        $this->service = new TournamentData_IndividualService($this->ingredientRecord);
    }
}

Here is my service code:

<?php
namespace Craft;

class TournamentData_IndividualService extends BaseApplicationComponent
{
    protected $individualRecord;

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

One more note, just in case this has the answer to what I'm looking for, I have taken a look at https://github.com/selvinortiz/craft.loath, but I wasn't able to follow what its setup code was accomplishing.

Any help is greatly appreciated!


texts: How to replicate a Craft installation as a starting point

texts:
I want to create a basic Craft installation that I can use as my starting point. I don't want to just start with the Craft download, because there is a lot of common setup I don't want to repeat every time.

My problem is making sure I properly pay Pixel & Tonic for a new license each time I need one.


texts:
the var menutype is set to {{ menutype }}

{% for block in menutype.menuGlobal %}

I'm trying to pass the result of {{ menutype }} into the for loop to return a dynamic menu, but the loop doesn't run. Hardcoding the string works, so the loop is fine, just appears not to recognise the variable output in the for statement.


texts:
When using a plugin such as Social Provider https://verbb.io/craft-plugins/social-poster/docs/providers/facebook and setting up LinkedIn/Twitter/Facebook do you have your clients login and follow the instructions so everything is under their account?

Or do you do it yourself?

Not sure what the best practice is here


texts: In Craft 3, (how) can I disable a category on a per site basis?

texts: In the CP, is it possible to disable Category X for site A, and not for Site B? And if so, how?


texts: Freeform - Grouping fields from the form builder

texts:
I'm using Freeform for a fairly large form. I'm trying to use a combination of the form builder (Composer) feature and custom HTML and I'm not sure it's possible! I'll give you the scenario and you can tell me if I need to write it all without the Composer.

I want the desired layout I have in the form builder but I need to wrap some field rows (in a <fieldset> or <div> so I can hide them (so I can show them when certain radios are checked).

I don't see how I can add this to the middle of the {% for row in form %} loop as there will be 10+ rows that need wrapping, including custom HTML field for the legend. i.e. there is no grouping mechanism I can check against that I can see.

I'd love to hear any suggestions so I can still leverage some of the form builder :)

Many thanks.


texts: How to handle license when duplicating entire website

texts:
I have two seperate clients on different domains but I'm developing very similar websites for each. If I duplicate the entire site and upload to new domain what is the best way of handling the license key for the duplicated site.

I'm assuming if I transfer the license, using the control panel message, then the other website's license will break.

Any help would be appreciated.

(edit: I want to pay for the license on the duplicated system without losing any data.)


texts: Can I limit the available styles from the rich text field?

texts:
I want my client to have the ability to do things like bold, italicize, and hyperlink text, but I would rather them not be able to use some of the other rich text field abilities.
I see from this question that it may be possible using a 'redactor' plugin? Where is the best place to find information on this?
Is it possible for some Rich Text Fields to have more styling capabilities than others?


texts: fileCache seems to expire even though I have it set to 0

texts:
I am using the fileCache command in a custom plugin. I've set it to never expire so that I can provide a special link to our client to force a refresh.

Problem is, the cache seems to be killing itself off. On one day I can see record of it regenerating three separate times, so it is

$craft->fileCache->add($cacheKey, $dataToAddToCache, $cacheExpire);
$craft->fileCache->add('my-hardcoded-key', 'string of data', 0);

So basically I am doing this.

if (NEED_TO_REGEN) {
   $craft->fileCache->delete($cacheKey);
}
$a_cacheVal = $craft->fileCache->get($cacheKey);
if (empty($a_cacheVal)) {
    //use the cached data
} else {
   $craft->fileCache->add($cacheKey, $dataToAddToCache, $cacheExpire);
}

Does admin modification of resources affect fileCache at all (updating an entry wouldn't kill of my plugin fileCache would it?) The admins is not doing a full Clear Cache inside settings or anything. So why would this particular cache be regenerating frequently (multiple times per day in some case)?


texts:
I want to output all entries which match with a given year from a custom date field. The year is a string I get from slug. I am using Craft 3.5.16. What did I do wrong?
{% set catYear = craft.app.request.segment(-1) %}

{% set firstDayOfYear = now | date_modify('1 January ' ~ catYear) %}
{% set lastDayOfYear = now | date_modify('31 December ' ~ catYear) %}

{% set params = {
  section : 'termine',
  datumTermin : 'and, >= ' ~ firstDayOfYear|date ~ ', <= ' ~ lastDayOfYear|date
} %}

{% set beitrage = craft.entries(params).all %}


texts: 500 error on installation since version 2.3

texts:
I have tried everything to install Craft on my server, and I have not been able to do it. I have done this a few times before without any issues, but since version 2.3 was released, I can't access the admin panel to start the installation.

I have followed all the steps in the documentation, I have created new DB, new domains.... nothing! I get a 500 error every time I want to access the admin area.

What am I missing?

2014/12/15 19:21:19 [error] [exception.Craft\HttpException.404] exception     'Craft\HttpException' in       /home/content/33/10789233/html/links/craft/app/etc/web/WebApp.php:737
Stack trace:
#0 /home/content/33/10789233/html/links/craft/app/etc/web/WebApp.php(176): Craft\WebApp->_processInstallRequest()
#1 /home/content/33/10789233/html/links/craft/app/framework/base/CApplication.php(180): Craft\WebApp->processRequest()
#2 /home/content/33/10789233/html/links/craft/app/index.php(62): CApplication->run()
#3 /home/content/33/10789233/html/links/public/index.php(19):      require_once('/home/content/3...')
#4 {main}
REQUEST_URI=/
---
2014/12/15 19:21:19 [error] [application]
2014/12/15 19:21:21 [error] [application] Unable to determine if a script name         redirect is in place on the server: Server error response
[status code] 500
[reason phrase] Internal Server Error
[url] http://website.com/testScriptNameRedirect


texts: Filter entries on a page based on related entry

texts:
This is blowing my mind!

I have a Section with handle practiceAreas.
I have a Section with handle barristers with approximately 100
entries.
barristers has an Entries fieldType called specialisms which is linked to the practiceAreas Section.

On the Barristers page I initially list ALL of the barristers entries, but I need to add a filter which lists the practiceAreas so when I user selects a specific Practice entry the page refreshes to show only the Barristers related to that particular practice.

I'm guessing this is done by adding an entry ID parameter to the URL when the user selects a Practice and then only pulling back the Barristers related to that ID when the page refreshes?

I don't know where to even start with this :/

Thanks for any help.


texts: Redirect URL variables with ContactForm plugin

texts:
When I use this code (taken straight from the readme)

 <input type="hidden" name="redirect" value="contact/thanks?from={fromName}">

The emails sends fine and I get redirected to the page as expected however the url in the title bar is exactly that:

http://ontherocks.dev/contact/thanks?from={fromName}

and this line also straight from the readme:

Thanks for sending that in, {{ craft.request.getQuery('from') }}!

renders as:

Thanks for sending that in, {fromName},

No idea what I'm doing wrong, problem something glaringly simple.
Anyone care to shed some light on the correct way to do this?


texts:
I've been looking through the forum, it seems there's a few methods to retrieve a tags page but I'm looking for the most efficient method (both speed- and template-wise).

Using tag.name with tag token (routes), which utilises the original article template for rendering.
Using tag.slug
Using tag.title and search()

I think #2 is the simplest and prettiest solution, but it's relatively undocumented as far as I can tell. Also, I'm using two tag groups and, although I've mentioned to my client to not add duplicate tags (e.g. { 'group 1': 'stress' } { 'group 2': 'Stress' } I'm interested to know the following:

Is #2 the most optimised solution?
Can it be used with a tag token route?
Will duplicate tags accross tag groups cause conflicts?

In my tests using #1 (the urls are ugly in my opinion), Depression seems to return no results, perhaps because there is already a depression tag in another tag group.

Ideally, I want one place for all tags, without having to create two different routes for both tag groups.


texts: Convert string to date format that can be used in a craft.entries tag

texts:
I've got a date string from the url in this format: "2021-06-01" (year-month-day) and I want to find entries that have a date in the year and month from that string. The date is a date field in Craft.
{% set entries = entries.startsOn(craft.app.request.getParam('departure')|date("Y-m")) %}

That does not work!
Any ideas gratefully received!


texts: How to make a code/settings for accessing the one database from 2 different html files with {slug}

texts:
I create a code for TV show database, but I have a big problem.
Please see the image
I want to access one entry(post) with some data from some templates.
But I don't know how to create any code or settings in the sections area.

Any advice or give me the url if there is another topic?

image


texts: Plugins: Is there any events and/or calendar plugin in the making?

texts:
I'm in desperate need of a plugin that lets:

Users create calendar events or (even better) lets you import those from Outlook or GCal.
Visitors participate in an event and (after submitting a form) get a calendar request through e-mail

Does anyone know of any plugin(s) in the making, or should I start building my own?


texts:
I'm having a bit of difficulty having 2 different matrix blocks show on one page, and they both have Entries fields. As soon as I put {% set entry for my first Matrix, the second Matrix disappears.

{% for block in entry.sideMenu %}
 {% if block.type == "sideMenuItem" %}
    {% set entry = block.sideLink.first() %}
      {% if entry %}
         {{ block.sideTitle }}
      {% endif %}
 {% endif %}
{% endfor %}


texts: Is there a way I can programmatically download the latest version of Craft?

texts:
If you have a base install script that you use to quickly turn out a new base install for Craft, it would be very useful for that script to be able to download the latest version of Craft when doing it’s new site setup logic.

What’s the best way to do that?


texts: Set a lineItem option from within a plugin?

texts:
I’m trying to set a specific lineItem option. Here is the gist of my attempt:

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

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

    if (something == true) {
        $lineItem->options['optionKey'] = 'newValue';
    }

});

This returns an error:

  Indirect modification of overloaded property…

What’s the correct way to do this?


texts: User activation success page localization problem

texts:
I have a website with Craft CMS 2 and this site has 2 diffrent languages.

There is no problem with sending e-mail for account activation for each language but when a user tries to activate his/her account via e-mail for my second language which is English they see English mail template but link directs them to my first and default language which is Turkish.

Same problem with the "Forgot my password" link. I tried to add array to activateAccountSuccessPath for each local like siteUrl but could not take any solution. Always directs to tr locale after activation from English mail template.


texts:
When I update any plugins ( and I mean any not specific) the vendor package vlucas (Php DotEnv) is removed and the site subsequently breaks complaining it cannot find the DOT env file. Manual update via composer update doesn't work/resolve

It seems the only remedy for this is to manually add from production site the vlucas package and the vendor/composer package

Is there something broken in these packages?


texts: How do I set the user password when using saveUser service method?

texts:
I am saving users from an external source and able to create them in the Craft db as users. However, each user's password is set to null despite setting it on the user model prior to saving it. Is there a way to handle setting passwords during user creation? I am not requiring email verification.

foreach ($docs as $doc) {

    $user = new UserModel;

    $user->firstName    = $doc->FName;
    $user->lastName     = $doc->LName;
    $user->password     = '123456';
    $user->email        = $doc->Email;
    $user->username     = $doc->Email;

    $wasSaved = craft()->users->saveUser($user);

    if ($wasSaved) {
        $was_assigned = craft()->userGroups->assignUserToGroups($user->id, array(1));
    } else {
        printf("couldn't save: %s", $user->email);
    }

}


texts:
I need to create a quick, and small plugin for a client, and am having trouble with the official Craft plugin tutorial.

Here is my base plugin code:

<?php
namespace Craft;

class MailchimpedPlugin extends BasePlugin
{
    function getName()
    {
         return Craft::t('Mailchimped');
    }

    function getVersion()
    {
        return '1.0';
    }

    protected function defineSettings() {
        return array(
            // Very confused about what goes here.
        );
    }

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

}

And here is my settings page code w/ screenshot of what it looks like on the front end:

{% import '_includes/forms' as forms %}

  {{ forms.textField({
    label: "API Key"|t,
    id: 'apiKey',
    name: 'apiKey',
    placeholder: "XXXXXXXXXXXX",
    required: true
  }) }}

  {{ forms.textField({
    label: "List ID"|t,
    id: 'listId',
    name: 'listId',
    placeholder: "d0ffd45cbd",
    required: true
  }) }}

Help

    How To Find Your API Key

    How To Find Your List ID

Basically, all I want to know how to do, is to get the api key and list id field to save and be persisted after the user presses the save button.

I tried reading through the plugin tutorial, and looked at the sample plugin Github page, but honestly, it has to much functionality for a beginner, and is just confusing me even more.

Ideally, the accepted answer will have some code outlining how I would go about this. P.S. I am not looking for an existing plugin, as I want to to do this myself. My company(A studio) uses CraftCMS for their clients websites, so I want to know how to create custom plugins in the future.


texts:
I have two entry types that I want to show in a sorted list (by postDate, with paginating).

{
  entries(
    type: ["entryType1", "entryType2"],
    orderBy: "postDate desc",
    limit: 5,
    offset: 0
  ) {
    id
    title
    postDate
    typeHandle
  }
}

This already works. Now the second post type entryType2 should have an optional Lightswitch showInList, where the editor can decide if the entry should appear in the list.

{
  entries(
    type: ["entryType1", "entryType2"],
    orderBy: "postDate desc",
    showInList: 1,
    limit: 5,
    offset: 0
  ) {
    id
    title
    postDate
    typeHandle
  }
}

Unfortunately with the adapted querying I only get the entries of the type with the Lightswitch field declared. When setting showInList: null I get all entries of both entry types, but its ignoring if showInList is true/false for any entry of the second post type.
I tested different QueryArguments but its seems they all have no effect.

Every QueryArgument is handled as if true

Tested:

showInList: 1 → shows only entries of entryType2 with
showInList set to true, ignores entryType2
showInList: ['not 1'] → I thought this would give all entries of entryType2 with showInList set to false but it behaves the same as showInList: 1
showInList: null → shows entries of both types but ignores the showInList field

is there something like showInList: ['1 or undefined'] or any other QueryArgument that would give me the expected result?

Tested in CraftCMS 3.4.17.1 with full schema


texts:
As you can see from the image below, the icons are missing from redactor I. Has anybody else had this issue? Running dev tools in chrome shows no errors.

Bold, for example has the following css selector:

.re-bold:before {
  content: "\e618";
}

I see that the @font-face src is base64 encoded right into the CSS file, so the issue can't be because of a missing font file for the icons can it?

Here is the bold link inspected in dev tools:

As you see there is no mention of .re-icon in the markup, but the only declaration of the font-family: 'RedactorFont' is for the .re-icon selector class. So adding .re-button::before to the selector that declares the font results in this:

...Close but not quite right. I shouldn't be editing these files, but am just doing so to help diagnose this. Presumably this redactor.css file shouldn't be referenced... it should be redactori.css?


texts: Do I need the web.config file in the craft root directory?

texts:
I'm working off of a linux machine (Apache) I don't use the web.config that's found in /public/web.config. I will use the .htaccess file.

I am curious if I can remove the web.config file from /craft/ since I am not in a windows environment. I have been removing it, but not sure if that's exactly a great idea...


texts:
I was wondering if it is possible to create a SEO Title Source in SEOmatic where the page title is output and then the parent/section page title e.g.:

{entry.title} | {{ entry.parent.title }} | Company Name

(The entry.title works but am not sure if its possible to get a parents page title)

Thanks
Malcolm


texts: How to prepend user input data to a filename uploaded through Sprout Forms

texts:
I have a contact form where users have to fill in a name field and upload a file.  I want to add the name the user filled in to the beginning of the filename, eg: firstname-lastname_filename.pdf.  I am using Sprout Forms for Craft 3, both the most up to date versions.
Is this something I can do with original Sprout Forms functionality, or will I have to write a custom module or plugin to inject this code?  Essentially, what I understand is I will have to find the code in Sprout Forms where the file is uploaded, and inject the code to add the special user submitted name data.


texts:
I have the following -

{% set press = craft.entries.section('press').first() %}

{{ press.title }}

If I change the section title in the Sections area of the back end from something like "Press" to "Testimonials" - I still see Press when I call press.title. The section is set to a single.

I've tried clearing cache in the back end which doesn't seem to do the trick. Any advice?


texts: I hooked up into the content.saveContent event. I want to save the entry content into a different application. Is there a way to retrieve the content as a Json (Or something more friendly). I think do $event->params['content']->title is now the best option.


texts: How do you delete assets from a frontend form?

texts:
I am creating a proof of concept for a client in Craft where the client's customers can manage projects from the frontend of a Craft install.

I have a frontend form working correctly for creating a new project and uploading files attached to it... however the missing piece to the puzzle for full management is being able to delete a project entry and also being able to manage the media attached to the project entry.

Is it possible to let a frontend user manage assets, in particular deleting assets from their username folder?


texts: Get future multi-day event entries with custom date field

texts:
I have an event section with custom fields for eventDate and eventEndDate.

I'm listing upcoming events in my template using:

{% for event in craft.entries.section('events').eventDate('>='~now).limit(3).order('eventDate ASC') %}

This works fine for single day events. But multi-day events disappear after the first day, when I want them to be listed until the event is over. I can't do .eventEndDate('>='~now) because the Event End Date field is left blank for single day events. Is there a way to add an OR to my query to get events with future eventDates OR events with future eventEndDates?


texts: How to clear a third-party cache when Craft updates its own template caches

texts:
We're experimenting with using Fastly for full-site caching of a Craft site. Everything is working great so far, with the exception that Fastly obviously has no way to know when a URL's cache has been invalidated.

We were thinking that the easiest way to make this work would be to use Craft's built-in caching and create a simple plugin that listens for Craft to invalidate a URL's cache (such as when updating an Entry referenced by that cache) and call out to Fastly to clear its cache for the same URL.

Unfortunately, as far as I can tell, Craft doesn't provide an Event for when it updates its own caches. Am I missing something? Any tips on how to go about this?


texts: modifyEntrySources hook, comparing two field values

texts:
Is it possible with the modifyEntrySources hook to query a field value against another fields value? Example:

Two fields are present on the entry section this hook targets

fieldParentId
fieldId

I want to be able to query in the entry source definition if the fieldParentId is the same as the fieldId to return only those records in the entry list within Craft that match this. I'm not sure this is possible, or if there is a special syntax required within the criteria array to do it?


texts: Change page elements based on geolocation

texts:
We would like to geolocate visitor IP addresses, and for US-based addresses render a portion of the page to display state-specific options. I actually have the PHP working well to pull the 2-letter state value from a Geocoding API, but am wondering the best way to plug that into Craft PRO.

I'm assuming the logic should look something like this in the end:

Check user for geo-cookie.
If not present, geolocate the user with their 2-letter abbreviation and set the geo-cookie.
If present, read the geo-cookie.
With that value in hand, render page elements accordingly, using the 2-letter abbreviation as a filter. If the user has no 2-letter value (perhaps an international user), present some fall-back "default" content in those areas of the page. (And yes, I am well aware that these services aren't 100% accurate but some providers are fairly close and we can live with that.)

I have found Khalwat's cookie plugin for Craft, which looks like it should suit nicely. But as a newbie to both Craft and Twig, how do I now bring it all together?

OR should we just adapt Craft PRO's localization options for this instead, since it's built in? And if so, how would we pass the 2-letter value along to use that?


texts: Problem updating to latest version of Sprout SEO

texts:
I updated Sprout SEO on our development site, but get the following error when trying to view the site:

Craft\TemplatesService and its behaviors do not have a method or closure named "setTemplatesPath".

I can access the Control Panel, but navigating within the Sprout SEO tab gets me the following error:

Unexpected token "punctuation" of value "?".

We are not on the latest version of Craft (Pro 2.5.2754) for a few reasons - not ideal, I know. Can anyone let me know where I should look to resolve this, or if it's a compatibility issue?


texts: I did a fresh craft 3 installation in a local enviroment, but the plugin store does not load, telling me to check back later.


texts: How does Craft know when to generate an Image Transform

texts:
I created an image transform called teamImage. My template code is below.

I want this transform to be created when I upload an image within a Team entry.

Team has it's own asset folder.

My questions is how does craft know when to create this transform and where in the directory does it create it?

{% for asset in entry.teamImage %}

{% endfor %}


texts: Duplicate an existing Order as a new Cart in Commerce

texts:
Orders can not be edited in Commerce. Makes sense.

What we want to do however is make it very easy for someone to re-order a previous order. So for example they've had an order that contains "two pairs of socks, two pairs of pants, toothpaste, and soap" but they need all of that again as a new order.

Rather than manually having to do so, we want to offer a "re-order" button.

Given that an order is just a cart that's been marked complete, we're thinking it should just clone the order into a new cart, so they can review it and make any amends they need to, then just continue as normal with the checkout process.

I can not figure out how to do this though. Getting the Order is simple enough, and there's an existing cart set up too. But how would I punt that old Order into the new cart?


texts: Getting mixed results with key word searches

texts:
I am having a hard time understanding why some keywords in fields that are marked as "Use this field’s values as search keywords" are not showing in the results but others are. For example, I have a field in one entry that contains words like "batman, superman, spiderman". When I search for some of those terms, it shows the entry is shown. Now on a separate entry, the same field but with these keywords "mickey, donald, goofy". When I search those terms, no results are displayed.
How is it possible that one entry's keywords yield results, but the other entry's keywords do not?


texts: Recommended Structure - One Site with Pages With Totally Different Layouts?

texts:
I've got a site with one base URL that is run on one Craft instance. The site is for a yearly event and each year the header / footer / body page elements / design are different. However, we want to keep all previous years pages in existence with the look and feel of that year so people can look at that page exactly as it existed in that year. URL structure would be something like example.com (current year), example.com/2017, example.com/2018, etc.

However, there are some of consistent codebase elements that I would like to have as easily editable for each unique year. For example, SEO elements like meta descriptions and social media descriptions should be unique for each year, while still being easily updatable using the same field across individual year entries.

What I'm debating is the best way to set this up in Craft to balance site speed and overall manageability. A few options I'm thinking about:

Do a different entry and layout for each year and then reuse the individual fields that need to be editable across all pages in the different templates.
Do one base template and then use conditional logic that swaps in the CSS, header structure, footer structure, etc. for each year. Would also somehow need to have multiple matrix fields available in this to add unique content structure for each year. Concerned about lots of database queries for this one and impact on site speed.
Some sort of hybrid approach leveraging different entry types across template(s) but not exactly sure what that would look like.

Other suggestions on approach or thoughts about which option is better? Thanks!


texts: Sprout Forms - An unknown error occurred when trying to view entries in CP

texts:
I've installed Sprout Forms and created a contact form. I'm using displayForm to display the contact form.

The front end appears it's working as it should. Validation works and the success message works when submitting.

The issues are I'm not receiving any email notifications (I have defined my email under Notifications > Email Recipients) and I am unable to view entries under the Sprout Forms control panel. When I click on the Sprout Forms tab, I get an orange prompt that flashes "An unknown error occurred" then disappears.

An odd but promising clue is in the admin, when I click on Sprout Forms then Forms, my contact form is showing the total entries that I've been submitting.

I have tested that PHP Mail works. Does anyone have any clue as to what could be causing this?


texts:
I wondered if it is possible to use one specific template for just one structure.

So let me make this clear. I have a structure called "Onze Diensten" (Our Services) and inside are child structures that are the actual services that the website offers. These child structures use a template that I assigned to them through structure so that works perfectly.
But what I want now is that the actual "Onze Diensten" gets it's own individual template which would show all the services on one page.

How do I do that?
Thank you for taking the time reading my question.

What I hoped would be the solution is using routes. By adding a route that when you visit onze-diensten/ it would load up the template onze-diensten/onze-diensten/ (Which is the path to the template I want to use).

But it seems to completely ignore the route at all.


texts:
Is there a way to set parameters from front-end user input?

Let's say I have a page that displays a list of entries. On that page, I have a form select called paidStatus with options notReceived, received, and paid; and another form select called order with options asc and desc.

Then, in my template code, I want to grab the list of entries:

{% for entry in craft.entries.section('sectionName').order('postDate post.order').find() if entry.paidStatus == post.paidStatus %}

with order and entryStatus being populated from the submitted form selects. That way I can change the criteria used to generate the list of entries on the fly.


texts:
I have a template intended for administrators (separate from the Craft control panel) where I'd like to generate tokenized preview links for unpublished posts (the same URL you get when you click on the "View" button from an entry page within the control panel). These links are intended for administrators to share with third parties so they can preview a page before it's published. Here's the Twig I have so far (which isn't working):
Preview

What am I missing?


texts: HTML code button missing from Rich Text "standard" view after 2.5 upgrade

texts:
After recently upgrading to Craft 2.5.x the HTML code view button is now missing from the "standard" Rich Text view, which means I can no longer edit all the custom HTML code I've added to those fields.

Do I have to create a custom Redactor config file to get HTML code view back, or should it still be included in the Standard config?


texts:
I have some logic in a template where I want to count the number of items that have a lightswitch set to yes, and a radio button set to another value, currently I'm doing this via a series of {% set %} variables for loops and if statments, I just wondered if anyone know of a more efficient method to resolve this issue, or if this is the simplest implementation within Craft.

{% set normalNominations = 0 %}
{% set specialNominations = 0 %}
{% set normalWin = 0 %}
{% set specialWin = 0 %}

{% for items in entry.matrixloop %}
    {% if items.type == "awardBody" %}

    {% elseif items.type == "awardType" %}
        {% if items.oscar %}
            {% if items.awardGained == "Win" %}
                {% set specialWin = specialWin + 1 %}
            {% elseif items.awardGained == "Nomination" %}
                {% set specialNominations = specialNominations + 1 %}
            {% endif %}
        {% else %}
            {% if items.awardGained == "Win" %}
                {% set normalWin = normalWin + 1 %}
            {% elseif items.awardGained == "Nomination" %}
                {% set normalNominations = normalNominations + 1 %}
            {% endif %}
        {% endif %}
    {% endif %}
{% endfor %}

{# Debug Information #}
{#
<p> Special win: {{ specialWin }} </p>
<p> Special Nominations: {{ specialNominations }} </p>

<p> Normal Win: {{ normalWin }} </p>
<p> Normal Nomination: {{ normalNominations }} </p>

{{ entry.matrixloop | length }}

#}

Thanks in advance for your help with this, I'm pretty new to Craft so want to make sure I'm being efficient in my templates and not writing rubbish.

Ta

Dave


texts: How do I add a second section name to this logic?

texts:
I need to add a second section name to this code:

craft.entries.section('not homePage')

I can't figure out the correct formatting. I've tried:

craft.entries.section('not homePage,clientPage')
craft.entries.section('not homePage, not clientPage')

How do I add a second limiter?


texts: How to show flash message for Commerce order when changing status on listing page?

texts:
If I change an order's status to "Cancelled" (my custom order status I created), I want to ensure that the CP editors provide a "Cancellation Reason" from a dropdown field in the order.  I've set up a custom validator to do this but it doesn't get recognized in Commerce's flash message.

In my plugin, I'm adding a custom rule to Order elements like:

use my\plugin\validators\CancellationReasonValidator;
use craft\events\DefineRulesEvent;
use craft\commerce\elements\Order;
use yii\base\Event;

Event::on(
    Order::class,
    Order::EVENT_DEFINE_RULES,
    static function(DefineRulesEvent $event) {
        /* @var Order $order */
        $event->rules[] = [['cancellationReason'], CancellationReasonValidator::class];
    });

My validator looks like:

use Craft;
use craft\commerce\elements\Order;
use yii\validators\Validator;

class CancellationReasonValidator extends Validator
{
    public function validateAttribute($model, $attribute)
    {
        $cancellationReasonField = $model->$attribute;

        /* @var Order $model */
        if (   $model->isCompleted
            && $model->getOrderStatus()->handle === 'cancelled'
            && ! $cancellationReasonField->value) {

            $this->addError($model, $attribute, Craft::t(
                'site',
                'A cancellation reason is required for {orderNumber}',
                ['orderNumber' => $model->shortNumber]
            ));

        }
    }
}

If I edit an order, change the status to "Cancelled", and click the red update button, the validation works:

However, if I do this from the orders listing view, where I try to update an order's status like in the screenshot below, there is no flash message displayed to the user that the order couldn't save.

I understand there's a lot of asynchronous JS happening here, but how do I tap into showing some sort of message to my CP editors, preferably one that mentions the order's shortNumber?


texts:
When saving an entry, Craft will sit endlessly waiting for the page to load. I've seen this behaviour intermittently in the past - but not for months. It's doing it again now though.

Seems to me to be related to PHP or Apache in some way. I can restart Apache and Craft will then work fine on the first save, but edit and save again and it'll sit spinning forever. The 'hung' save does actually work, you can see changes reflected by checking the front-end in a different browser. However, while the save 'redirect' is hung, you can't browse any of the website, back-end or front, from the browser you were using to edit the entry.

This is only happening on our staging server, not our local machines, though both run the same website and same database.

Staging is Debian Jessie, on PHP 5.6.17-0+deb8u1 and Apache/2.4.10 (Debian). Our local machines are Macs running PHP 5.5.31 and Apache/2.4.16 (Unix).

I haven't found a cause or solution, and there doesn't seem to be anything of use in the craft.log either (though I'm not sure what to look for).

(This post is a follow-on from Craft hangs when updating entry, which never seemed to be answered definitively).


texts: How do I traverse relationships when populating models from queries?

texts:
I have three models / records - Journals, Issues, and Articles. Articles each BELONG_TO an Issue. Issues each BELONG_TO a journal. Issues have a date on which they've been published, and I am trying to find the most recent issue (by cover date) for a given journal.

I have the following code in a method in the IssueService:

$criteria = craft()->elements->getCriteria('Articles_Issue');
$criteria->journalId = $journal->id;
$criteria->limit = 1;

$query = craft()->elements->buildElementsQuery($criteria);
$query->order('issues.coverDate desc');

$issue = Articles_IssueModel::populateModel($query->queryRow());

This all works well and good and I am returned the appropriate Article_IssueModel. However, when trying to access $issue->articles, I get zero back. Normally when I load the issue through craft()->elements->findByElementId($issue->id);, the articles in the relationship are available.

Editing the code I pasted above to include the following (after populating issue model):

$criteria = craft()->elements->getCriteria('Articles_Article');
$criteria->issueId = $issue->id;
$art = $criteria->findAll();
print_r(count($issue->articles));
print_r(count($art));

prints 0, followed by 2.

So it seems to me that calling BaseModel::populateModel is not enough to load the model's relationships. I recognize that I am (possibly?) skipping a step in not instantiating any Records, but if I change the issue loading code to the following:

$issueRecord = Articles_IssueRecord::model();
$issueRecord->populateRecord($query->queryRow());
$issue = Articles_IssueModel::populateModel($issueRecord);

I still get zero articles when accessed via $issue->articles. Is there a way to get the issue to load its related articles without manually loading them via ElementsService?

Please note, I am building many other service calls and views using this plugin, and I have double checked that foreign keys are being populated and the relationships defined on the records are working properly. Also, I can post additional code if I've missed something.


texts: Is is possible to allow auto-updates for a plugin?

texts:
I’ve been developing my first Craft plugin and I think it would be really cool to be able to offer auto-updating for it, is there a way to hook into the update page you would use to update Craft? or is this something that could happen in the future?

I understand you could probably achieve this manually, I’ve seen a couple of plugins do this but then on later updates some remove this functionality, is this not a good idea to try and do? is it worth looking into how Craft does this in the core files and try to tap into that or would that be a big no no…

The way I was thinking of achieving this manually myself is:

Deploy a base version on my own server
Create a service that talks(Guzzle?) to the server to check the users version against the server version
Look into the methods that Craft uses to copy and back up
files and use those methods to update the plugin if needed

Any pointers or info would be appreciated,

Thanks!


texts: How to create any code from google spreadsheet like {.label} by Craft CMS

texts:
ex) original HTML source code

<link rel="exhibit/data" type="application/jsonp" href="https://spreadsheets.google.com/feeds/list/~~~~/od6/public/basic?alt=json-in-script" ex:converter="googleSpreadsheets" />

~~~~~

    Aired:

    Genre:

You can see .label, .start, and .genrem but on Craft CMS they are errors.

How do I create code with no errors?

Error message is,

Internal Server Error

Unexpected token "punctuation" of value ".".

*The error message displays like this on my PC's XAMPP
craft/templates/index,html

Thanks in advance!

ref image on google spreadsheet,


texts: How to store value of checkboxes without predefining them in the SproutForm plugin

texts:
I'm using a block matrix to display items of a to-do list.

Each item has a checkbox input. Number of items can vary.

I'm trying to use SproutForms to save the state of the checkbox. This would need to record the currentUser and the to-do list ID.

I've made a form within the SproutForms plugin to include a checkbox and a  to-do list ID, but how can I associate the checkbox on the to-do list item with the checkbox on the SproutForm form?

If I were to use displayField to show the checkbox from the SproutForm, I'd have to make a checkbox for every to-do list item within the SproutForm plugin.

I hope that makes sense! Thanks for any help.


texts: Call a public function within a FieldType file, from a variables files

texts:
I have a plugin called "myPlugin", this has a variables file. Within there, I have a something like this:

public function helloWorld() { return "Hello World"; }

Also within this plugin, I've created a new fieldtype. From the "getInputHtml" function, I'd like to call the "helloWorld()" function.

How can I do this? This was my initial trail of thought:

$testing = craft()->myPlugin->helloWorld();

or

$testing = craft()->myPlugin->myPluginVariable->helloWorld();


texts: Craft CMS 3 storage doesn't exist or isn't writable by PHP

texts:
I am going to do an internship in February where they work with Craft CMS and thus I am going to learn it at home with XAMPP ( localhost). However I've installed it and now it will simply give me the following error:

  D:\xampp\htdocs/storage doesn't exist or isn't writable by PHP. Please fix that.

I have tried to remove the "read-only ". Everything is on full control through the security tab. I got no clue how to "allow" this to write.


texts:
I wanted to create a php which allow admin to upload their pictures in any resolution and image file type, but it has to display into a bootstrap carousel with fixed size.
Does anyone has the similar script I can have a look?

It might needed to do the following;
Upload image into a specific location, convert image type into jpg, specific resolution, and be able to read by bootstrap carousel. My head is about to broke thinking of this script :(


texts:
So I have three light switches on my blog: 'featured', 'required reading' and 'skills'.

I got the featured section to work with this code:

{% for entry in craft.entries
    .section(['etiquette', 'style','culture','reviews'])
    .where('featured' == 1)
    .orderBy('id desc')
    .limit(4)
    .all()
%}

but when I went to do the reading section I used this code:

{% for entry in craft.entries
    .section([
        'etiquette',
        'style',
        'culture'
    ])
    .where('requiredReading' == 1)
    .orderBy('id desc')
    .limit(12)
    .all()
%}

but i get all the stories with reading and featured switches on. I checked the database and the required reading field is 0. How can I get just the required reading or can you not use more than one lightswitch?


texts: Limit amount of entries a user can create based on their user group

texts:
Is there a way to enforce a limit to the amount of entries a user can create based on their user group

I’ve been digging around a little and can’t seem to find anything that would allow this, I’ve looked at adding my own permissions but I don’t think that’s right as I need/want the value to be a number, not a ‘can the user add x amount’ kinda deal.

Something like:

{% set entries = craft.entries.section(‘listing’).authorId(user.id) %}

{% if entries.count >= userGroup.entryLimit %}
    No more entries for you!
{% else %}
    More entries for you!
{% endif %}

Is the only way to do this by creating a custom plugin?

Thank you!


texts: Accessing admin panel after deploying local MAMP

texts:
I've moved my site from a local install to my server. I'm pretty new at this, so hopefully I've followed the right course:

What I did:

Edited db.php to reflect the changes
Edited index.php to point at the craft folder
Had to change the siteUrl in craft_info because it would only show the Craft 404 page (siteUrl was still on localhost)

I can see the correct rendered pages now, but as soon as I type /admin or /index.php/admin or /index.php?p=admin I get an Apache 404 error on the /admin/login url

So what should i do now?


texts: What are the Pros and Cons to each image transform technique?

texts:
In Craft you can do two types of image transforms:

1. Control Panel Transforms:

Via: Settings → Assets → Image Transforms

2. Inline Transforms in your Templates

I’m currently using 100% inline transforms as they can be version controlled and seem to work better across different dev environments.

Are there any benefits of using Control Panel Transforms over using Inline Template Transforms in your Templates?


texts: Craft 3 Plugin Controller - returnJson() replacement?

texts:
In Craft2, when making an ajax request to a plugin controller action, you would use the returnJson() method which is part of the BaseController class - which your plugin controllers extend.

This sets some headers, echo's the response and kills any further processing.

public function actionDoStuff() {

    $response = (object)[
        "message" => "Look at me! I'm JSON!"
    ];

    $this->returnJson($response);
}

In Craft 3/Yii 2 I'm having trouble finding the equivalent.


texts: How to add recipient drop-down selection field with the Contact Form plugin?

texts: There is a guide on GitHub page how to add additional fields, but how to add recipient selection?


texts: Craft CLI RC1 Connectivity Issues with MAMP Pro

texts:
I've been trying to run the new Craft CLI for the last couple of versions without any success. I figured maybe since we weren't at RC1 yet that it wasn't fully working. After seeing Ryan's video about it at https://mijingo.com/lessons/craft-3-command-line/ I realized that wasn't the case (and with RC1 being released today).

I am using MAMP Pro (like Ryan does in his video), but I have it using the standard MySQL port at 3306. I also have PHP 7.1 installed at the terminal through homebrew and pdo_mysql is a compiled in module. I am also using RC1.

Interestingly, if I use localhost I get a completely different message than if I use 127.0.0.1. But regardless, both still fail.

Which database driver are you using? [mysql,pgsql,?]: mysql
Database server name or IP address: [localhost] localhost
Database port: [3306] 3306
Database username: [root] root
Database password:
Database name: craft3
Database table prefix:
Testing database credentials... failed: SQLSTATE[HY000] [2002] No such file or directory

Which database driver are you using? [mysql,pgsql,?]: mysql
Database server name or IP address: [localhost] 127.0.0.1
Database port: [3306] 3306
Database username: [root] root
Database password:
Database name: [craft3] craft3
Database table prefix:
Testing database credentials... failed: SQLSTATE[HY000] [2002] Connection refused

If I create the database manually and put the credentials into my .env file everything connects just fine without any issue. Is there something else I should be considering?


texts: CraftCMS Redactor is adding  tags to viewable source code... but then removes them when saving

texts:
We are in the midst of a migration from WordPress to Craft.  Much of the content contains line breaks, which are converted to <p> tags in Redactor (as seen in Redactor's view source plugin).

But when the entry is saved (or previewed, as seen in the attached image), those <p> tags are stripped back out and never make it to the database.

Is there a config setting to "retain the automatically applied formatting from redactor when the entry is saved"? (we want to keep these styles that were temporarily added in by redactor)


texts: I have a single. I want to set the uri to section/single. For example academy/sign-up. I have created a single and have a template file named sign-up.html in the right location (within academy folder). I get a 404 when requesting site.com/academy/sign-up. Removing academy from address works. Can I use the nested uri or do all singles need to sit at the top level?


texts: It seems /login is a reserved route - is that correct?

texts:
When I hit /login in a browser, I am redirected to the home page (this is on a vanilla install without any entries or routes set up).

Is this a reserved route?
Can I change that so I can use it for my own route?
If it's reserved, what other routes are there that we should know about?


texts: Define a dynamic 'basePath' environmental variable without the locale

texts:
So in my general config file I've defined an environmental variable called basePath (as per the Environment-Specific Variables documentation). I'm using the getcwd() function to get the working directory.

return array(
    '*' => array(
        'environmentVariables' => array(
            'basePath' => getcwd(),
        )
    ),
);

I'm using this for a few reasons:

I work in an environment where many people can be working on the same project at the same time. So their local basePath is always different.
My different siteUrls for my setup use trailing locales in the url: 'siteUrl' => array( 'en' => 'http://www.website.com/', 'fi' => 'http://www.website.com/fi/' ). So when it comes to targeting environment-specific locales, things get messy.
$_SERVER['DOCUMENT_ROOT'] is ok locally, but fails on a live server.

So my problem is when using getcwd(), the locale is included in path. Is there a way to trim this out dynamically?

Or is there a way to strip out the current locale from this path on-the-fly? rtrim(getcwd(),"fi")

Maybe there is a more reliable way to get the working directory?


texts: Programatically setting dropdown options in a matrix

texts:
I'm building a Matrix field from within a module's migration.
I can get all fields setup correctly except the options of either a Dropdown or Checkboxes field.
$field = new \craft\fields\Matrix([
    'groupId' => 1,
    'name' => $fieldSettings['name'],
    'handle' => $fieldSettings['handle']
])

$blocks = [
    'new1' => [
        'name' => 'Heading',
        'handle' => 'heading',
        'fields' => [
            'new1' => [
                'type' => \craft\fields\Dropdown::class,
                'name' => 'Heading',
                'handle' => 'pageContentHeading',
                'options' => [
                     ['label' => 'H1', 'value' => 'h1', 'default' => 1],
                     ['label' => 'H2', 'value' => 'h2', 'default' => ''],
                     ['label' => 'H3', 'value' => 'h3', 'default' => '']
                 ]
             ]
         ]
     ]
]

$field->setBlockTypes($blocks);

try {
    Craft::$app->getFields()->saveField($field);
} catch (\Throwable $e) {
    echo $e->getMessage();
}

This creates the dropdown field, but doesn't set the options. Am I missing something obvious?


texts: How to auto obfuscate email addresses in rich text field

texts:
I'm used to this feature in ExpressionEngine either natively or via the Auto Linker plugin, where you just wrap it around all the text fields. I've seen the Sprout Encode Email addon but that doesn't search through text and apply it.
I don't mind if it doesn't create a mailto link, I just want to obfuscate every email address that appears in any of the text fields in a template.


texts: Custom field type not accessible in usermodel

texts:
I have altered the Craft usermodel using some standard field types (like an entry field type) and an customfieldtype (extended from the EntriesFieldType). The only thing I have altered in the child fieldtype is some validation rules and the prepValue method. I dont get any errors saving this new field type but when I try to access it eg:

    $lCurrentUser = craft()->userSession->getUser();
    $lCompanyIdUser1 = $lCurrentUser->companiesDropdown[0]->id;
    $lCompanyIdUser2 = $lCurrentUser->companyUser[0]->id;

companiesDropdown is a standard "Craft" Entries fieldtype
companyUser is the custom fieldType

the error is get is :
Undefined property: Craft\UserModel::$companyUser (i've tripple checked the handle name)

Please advise,

Thanks in advance.

(ps I'm running Craft 2.2)


texts: setRouteVariables doesn't return errors to the template

texts:
So I've been breaking my head trying to figure this out. I'm working on a contact form plugin. Basically I'm coping exact same code craft uses to create form "fields". I have validation working like it should. And I have 2 required fields that should return error messages. But when I try to:

craft()->urlManager->setRouteVariables(array(
  'field' => $field
));

And in the template file {{ field }}, I get.. Variable "field" does not exist

I can't seem to get the value to populate on the form nor display the errors because of this. Anyone had problems like this before?

Here's my files:
https://gist.github.com/owldesign/e01b49fdb1da3ef23ef2

Sorry for weird file delivery.. this comment won't let me post more than 2 links.

Please let me know if you guys need more from me?
Thanks.

Edit: Repo https://github.com/owldesign/FormBuilder


texts: Why do some entries generate a template error on get next or previous post when others do not?

texts:
I have setup chevrons to links to the previous and next posts.  It seems to work for all but a handful of posts.  Those posts generate the following template error:

  Impossible to access an attribute ("url") on a null variable

            {% set prev = entry.getPrev( 'posts' ) %}
            {% set next = entry.getNext( 'posts' ) %}

        {{ entry.postDate | date('F d, Y') }}

The specific line the template error references is

There are previous entries to access.

Thanks


texts: Previous/Next button to next item in Matrix

texts:
I've made a projects structure with inside a couple of projects. On the homepage people can fill in a matrix with either a project or a textblock.

I'm capable of looping through the detail pages in the order that they've been made in the Projects section. I can't however make them loop in the order the client orders his Matrix. I'm capable of finding the current detail page I'm on by using relatedTo(entry) however I'm uncapable of using getPrev / getNext.

{% set source = craft.entries.id(2).first().projectList.type('project').entries.relatedTo(entry) %}

{% for collection in source %}

{% for project in collection.projectEntry %}

    <p>{{project}}</p>

{% endfor %}

{% endfor %}

This returns the current project I'm visiting. Even when using getPrev(entry) or getPrev(source) in there it keeps on returning my current project instead of the prev/next


texts: Email notifications with attachment when uploading files to s3

texts:
I'm attempting to create email notifications with attachments when using Sprout Forms and S3 assets.

Given Sprout Forms 2.1.5 & Craft Pro 2.5.2760

And a form with an Asset field

And default upload location in an S3 bucket

And enable notifications set to true

And enable file attachments set to true

When a user submits a form, no email is sent and the following error is logged in sproutforms.log

Craft\S3AssetSourceType and its behaviors do not have a method or closure named "getBasePath".

Looking into the docs, S3AssetSourceType does NOT have a method named getBasePath, but localAssetSourceType does.

My question is, does sproutforms support notification emails with attachments when using S3?


texts: Paginate events without setting expiry date

texts:
Is there a way to paginate events entries without setting an expiry date for each entry? So I currently have:

{% paginate craft.entries.section('eventsEntry').limit(3).orderBy('eventDate') as pageInfo, upcomingEvents %}

{% for event in upcomingEvents if event.eventDate >= now %}
...
{% endfor %}

But this will include past events in the loop but not show them when output. Which results in empty 'slots' on the first page.


texts: Is there a way to query for a list of values belonging to a specific field in a queryset?

texts:
For instance, if I wanted an array of all the titles belonging to a subset of entries that I wish to query. The way I know how to do this currently is like so:
  {% set titleList = [] %}
  {% articleQuery = craft.entries().section('articles') %}
  {% for article in articleQuery.all() %}
    {% set titleList = titleList|merge([article.title]) %}
  {% endfor %}

The other way I can think of to do this operation is with the map twig filter, but I'm wondering if there is a way to query for such a field-value list straight away and avoid spending computational time on iterations.


texts: How to create single lines from a plain text field with line breaks

texts:
Building on this question here: Create line breaks from text field

What approach would be best for breaking a multi line plain text field into multiple single lines to be used as:

{{ textfield.lineOne }}
{{ textfield.lineTwo }}
{{ textfield.lineThree }}

At the moment, my approach is to use a Matrix for the user to be able to add individual lines, but I'd much rather I was able to present the client with a multiline text field and rework them in the template.


texts: How can I get an entries author custom field?

texts:
I have a custom field for a user which is an asset, it has the users larger profile photo.

In an entry template I can get their profile photo using:

{{ entry.author.getPhotoUrl }}

But I want to get the custom field.

Something like:

{{ entry.author.authorImage }}

I am sure I am missing something very simple?


texts:
I can't find anything in the Craft 3 docs that explains templating for a structure entry. What I want to do is show level 1 entries with their associated level 2 entries in a simple list type organization.

I was able to do that with Craft 2 by using {% set subItems = entry.children %} where entry was set to level 1 entries, but that does not work.

I can't figure out how to associate levels with parents/children. Am I missing something in the docs? Thanks for any help!


texts: Showing A Flash Message On Admin Entries Listing (Craft 3)

texts:
I've written a plugin that imports a CSV and creates entries from that for a client. I'm wanting to redirect them to the entries listing page after (i.e. /admin/entries/tvListings) and show a flash message saying "X TV listings imported.".

So this is a 2 parter:

How do you set flash data in Craft 3.
Is there a default flash key that'll show as soon as I land on the entries listing page?

Thanks.


texts: Plugin development: how can I check if user has the permissions to delete only his own assets?

texts:
I have a front-end form where logged users can upload and delete their personal files.

These users have the strict minimum permissions required to interact with this form. They can only Create, Publish and Delete their own entries in the section where the form create these entries.

In order to be able to delete these files from Craft (and not from only the field they're linked in this entry), I have created this custom action in a module:

<?php

namespace modules\mymodule\controllers;

use Craft;
use craft\web\Controller;
use craft\elements\Asset;

class DefaultController extends Controller
{

    public function actionDeleteAsset()
    {
        $this->requireAcceptsJson();
        $this->requireLogin();

        $currentUser = Craft::$app->getUser()->getIdentity();
        if (!$currentUser) {
            return $this->asErrorJson(Craft::t('app', 'Only a logged in user can delete an asset.'));
        } else {
            $request = Craft::$app->getRequest();
            $assetId = $request->getParam('assetId', '');
            $asset = Craft::$app->getAssets()->getAssetById($assetId);

            if (!empty($asset)) {
                if (!Craft::$app->getUser()->checkPermission('deleteFilesAndFoldersInVolume:' . $asset->volumeId)) {
                    return $this->asErrorJson(Craft::t('app', 'You don\'t have permission to delete this asset.'));
                } else {
                    Craft::$app->getElements()->deleteElementById($asset->id, Asset::class);
                    return $this->asJson([
                        'success' => true
                    ]);
                }
            } else {
                return $this->asErrorJson(Craft::t('app', 'This asset does not exists or has already been deleted.'));
            }
        }
    }

}

The problem is that Craft::$app->getUser()->checkPermission('deleteFilesAndFoldersInVolume:' . $asset->volumeId)is not entirely appropriate:

I need to add Volume permissions (View volume + Remove files and
folders) to these users to allow them to delete their assets from the
front-end form ;
By adding these permissions, they have access to
other users' assets, which is a security problem ;

So how can I check if user has the permissions to delete only his own assets? In other words, this user can only interact with the assets he has uploaded.


texts: Target first and last items and append if greater than 2

texts:
I am trying to loop through a list of categories to add some text to the page. If it is the last item I want to replace the ',' with the words 'and' but only adda a ',' if there are more than 2 categories.

{% set categories = craft.categories.group('products') %}
{% for category in categories %}
    {{ loop.last ? 'and ' }}{{ category.title }}{{ loop.index > 2 ? ', ' }}
{% endfor %}

if there is only category it would output:
hello

So if there are two categories it would output:
hello and world

if there are 3 or more it would output:
hello, world and space

My current code looks like this. but isn't quite working correctly.
Anyone able to help? or point in the right direction?

Thanks.


texts:
I can grab a top/bottom level ancestor with something like entry.ancestors.first/last.title.

But, say I'm at level 6, is it possible to grab an ancestor at a particular level, like entry.ancestors.level(3).title? Or would you have to grab all the ancestors and loop through them to accomplish this?

New to deep structures and just want to confirm I'm not missing something that would allow me to sidestep a loop. Thanks!


texts: Why does the matrix field produce such a massive amount of duplicate information?

texts:
The matrix field in Craft CMS is producing massive quantities of duplicate data. About 70 database rows per entry. Is there something I'm doing wrong? I don't think this will be sustainable for my database. The image embedded displays a fraction of the entries into the matrix table for a single Craft CMS structure entry.
Using Craft Pro 3.6.12


texts: Removing x-powered-by and changing cookies names for security?

texts:
I noticed that anyone interested in finding out what software is used for my website could find that out very easily just by looking at the headers and cookies received by craft.
You can find two headers that will expose craft:

"Set-Cookie": "CraftSessionId=".
"X-Powered-By": "Craft CMS".

Thats concerns me because if any security vulnerability will be found on craft, than immediately my site could be more exposed to threats. also, it will be easier for attackers to plan an effective attack against my website, because using craft means that i use SQL, php, twig and more.

I understand that it helps spreading the word on the cms. But i thinks that in some cases it may be better to remove it.

I have two questions:

Will it be against the terms and agreements of craft to remove those headers?
Will writing a plugin for it be the best way, or maybe there is a better way?

Thanks ahead!


texts: How to display Craft Commerce subscription description from a linked entry

texts:
I must be missing something obvious here but I don't see any reference to this in the docs.

Under Commerce Settings > Subscription plans > You can link a related entry to the Description but it is not clear how to display it on the front end.


texts: Disable modification of assets title and name

texts:
I want to disable the modification of both the file name and title of a specific asset type.
How can I do that ?


texts: Exclude category from search results using "relatedTo"

texts:
How can you execute a search query, that excludes all entries associated to a specific category?
Many answers say "fetch all the items associated to that category, and then filter them out" - However we have around 2000-4000 entries that we would like to exclude so do not feel this is feasible.
Effectively I want something like...
Entry::find()
->relatedTo([
   'and',
    ['targetElement' => [1,2,3], 'field' => 'category'],
    ['targetElement' => 'not 4', 'field' => 'category'],
])->all();

So find all that are in category 1 or 2 or 3, but make sure they're not in 4.
Thanks


texts: How do I set where the user is sent from a custom login form?

texts:
Is there a way to send the user to a different page than the control panel when logging in from a custom login form?

I've tried..

<form method="post" action="" accept-charset="UTF-8">
    <input type="hidden" name="action" value="users/login">
    <input type="hidden" name="redirect" value="apply">

I've also tried setting the returnUrl session in a login event within a plugin. There's a bit left to do in the init function but you get the idea. Currently the code should redirect all logins.

public function init()
{
    craft()->on('userSession.onLogin', function(Event $event) {
        // load the user info and determine user group
        // if part of applicant user group
        // load any existing unfinished applications
        // set a session for the unfinished application
        // redirect to /apply which should load the unfinished application
        craft()->session['returnUrl'] = "/apply";
    });
}


texts: Is it possible to display additional fields on the entries list in admin?

texts:
For example, in addition to the auto-generated title for an entry is it possible to display another column alongside with another field? I would like data input be as easy as possible for the client. The more information available on this page to view and sort by the better.

Unless there is another way to approach this I am not aware of? Would a plugin be required for example?


texts:
I'm trying to figure out how searching for Commerce Orders in the CP works. I've run some tests searching against the following fields:

Shipping Business Name
Billing Business Name
Shipping Method

In all cases, searches seem to match nothing in these columns. For example, if the Shipping Business Name was "Acme" and I enter that in the CP search bar, I get no results.

Is this expected behaviour? That seems hard to believe if it is. How would a user filter down the list of Orders for a particular company or shipping method... or whatever?


texts: How Can I Include a Conditional for First Type of Matrix

texts:
I want to include a conditional for when the 'Text' block type is returned for the first time in a loop. In css it would be first-of-type.

Here's what I have at the moment:

{% if type == 'text' and loop.first %}

{% endif %}

In this instance my text block type is loop index 3 but I want to adjust the conditional because it is the first text type in the matrix field.


texts: Now Craft 3 is available as a download, do you need to use composer for any part of upgrading a Craft 2 site to Craft 3 (if Craft 3 has been downloaded)?


texts: How can I output child urls that reflect a structured menu hierarchy when the structure has no URL format specified?

texts:
I am using a structure for navigation. The structure has two fields :
entry field: 'contentLink'
custom link: 'customLink'

These are used to create a menu structure like:
About
- sub item 1
- sub item 2
- sub item 3

The section for this is set to have no url templates setup.

The entry links for sub item 1 to 3 point at entries in a page structure called 'pages' which is currently flat (ie no children)

In my template i am using a drop-down menu and code to get child items which works OK.
    {% set menuentries = craft.entries.section('topnav') %}

{% for entry in menuentries %}

    {% if entry.contentLink.first|length %}
        {# attempt to set navlink var #}
        {% set navlink = entry.contentLink.first().slug %}

    {% elseif entry.customLink|length %}

        {% set navlink = entry.customLink %}

    {% endif %}

     {% if entry.level == 1 and entry.children|length %}

            {{ entry.title }}

                {% for child in entry.getDescendants() %}

                        {{ child.title }}

            {% endfor %}

    {% elseif entry.level == 1 and not entry.hasDescendants() %}

{{ entry.title }}

    {% endif %}
{% endfor %}

But i cant figure out how to get:
a) a url for child.slug that reflects the heirarchy of the menu structure
b) parent and child active classes for highlighting / breadcrumb purposes

question restated:
How can I output child urls that reflect the a structured menu hierarchy like: 'about/sub item1' when the structure has no URL format specified?