texts: How can I record sales data from Stripe Checkout and then restrict access to content based on the item purchased?

texts:
I have a client that is going to use Stripe Checkout (https://stripe.com/checkout).  We are trying to figure out how we can simply record the sale data into Craft.  We know of other plugins that use Stripe, but we really want to use Stripe Checkout as it is great for mobile.

How can we write data to an entry after the Stripe sale?  We would
need basic things like Customer Name, Item(s) purchased, Order
Total.  The items would all be entries in Craft already.
How can we restrict content viewing based on the items purchased?
Basically if you buy Product X which is an entry page of content,
how can I secure that entry so only people who have a confirmed
purchased can view the template?  Since there will be about 10
products, we really can't use User Groups for this.  We need the
permission to be on the item purchased level.

Any help is greatly appreciated.  If we need a custom plugin for this would anyone be interested in making one?  Should be pretty simple using the Stripe API I would imagine.


texts: Get every slug from entry for each language

texts:
For the robot.txt file, I want to get every URI from the entries for every language. Right now it just gets the URI from one language.

{% set crawledEntries = craft.entries({
    relatedTo: { sourceElement: crawlSites, field: "entryCrawler" },
    order: "sortOrder"
}) %}

{% for entry in crawledEntries %}
    Disallow: /{{ entry.uri }}
{% endfor %}

This now loops just through one locale.


texts:
The closest thing I found to what I need is here, the problem is, even though it's only 8 months old, it appears outdated. I see there is an "outstanding balance" in the PayController, but I have no idea how to allow a customer to pay a specific amount at the gateway.

I created an adjuster that discounts a specific amount, so I am able to bill the correct amount at the time of payment, but the amount that I discounted needs to be reapplied to the order in order to be billed at a later date, which I haven't found a way to do this as every possibility I've seen/tried is either a read-only or it's another adjuster which I can't get to fire at the correct time. I tried to put that amount back on with an adjuster with the EVENT_BEFORE_ORDER_COMPLETE but then craft obviously sees the order total has changed and kicks me back to the payment form with my new adjustments, which negates my old one.

tldr

I just need to know how to set the amount a customer must pay at the gateway. Is there a specific way an adjuster needs to be set up in order to do this?


texts: Stop image upload if moderation fails using EVENT_BEFORE_HANDLE_FILE

texts:
I have a frontend form where images can be uploaded.
I am handling the image moderation within EVENT_BEFORE_HANDLE_FILE on the Asset class. I am setting session errors for any moderation issues detected.
This is all working great, however I need a way of stopping the image uploading if errors are detected, but I want the session errors to continue to show as the page refreshes.
What is the best way to stop the image upload in this event, but for it to still set the session errors?
Thanks


texts:
I've set up multiple translation files (de.php, fr.php, es.php etc.) in craft/translations/ to translate static text.

While my site is in development, I am trying to keep these lang.php files in sync, so that they all contain at least the strings of the primary locale as array keys.

But the more strings are added or changed, the more annoying this undertaking gets. Any idea on how I could make this more simple and efficient?


texts:
When I delete an asset in the CP, the asset/file will be deleted, but it is still shown in the assets list (without thumb).

The issue can't be solved with the "Update asset index" function. (There is also the file listed: "Missing file"!)

  yii\base\ErrorException: unlink(/Applications/MAMP/htdocs/xxxxxxxx/storage/runtime/assets/sources/108.png): No such file or directory in /Applications/MAMP/htdocs/xxxxxxxx/vendor/yiisoft/yii2/helpers/BaseFileHelper.php:407


texts: Use same handle for different fields on different entry types

texts:
I've got two entry types: blog and job. Each has a category field but different category groups: blogCategories and jobCategories. I would like to write a Twig include to accept either a blog or a job and display its categories like:

{{ entry.title }}

{{ entry.category.all()|column('title')|join(', ') }}

Is there any way to do this? I tried creating two fields, both called categories but the field handle has to be unique. Is there such a thing as a field alias?


texts: Eager load entries from another site in a Matrix block

texts:
I'm having trouble to get Eager Loading to work with an entries field that can select entries from another site in a multi-site setup.
We're using a Matrix content-builder setup. Different kinds of blocks for text, images, etc. That works well.
We also have a Widget block type that consists of one entries field. You can select an entry from a Widget section. That section has multiple entry types for "special content blocks".
In one of these entry types we have another Matrix field. One of the blocks has an entries field were you can select from other sites.
When not eager loading, it all works.
On the Widget-entry-type template I can do entry.entriesField.site('*').unique().one() to get the related entry from another site.
When I select only entries from the same site, it works.
But when I also select entries from another site, I get empty arrays and errors.
I have tried these notations:
{% set content = entry.matrixField
  .site('*')
  .unique()
  .with([
    'simpleBlockType:assetsField',
    'widgetBlockType:entriesField.matrixField:entriesField,
  )]
  .all()
%}

And
{% set content = entry.matrixField
  .with([
    'simpleBlockType:assetsField',
    ['widgetBlockType:entriesField.matrixField:entriesField', { site: '*', unique: true }],
  )]
  .all()
%}

On the Widget-entry-type template I've tried:
{% set relatedEntry = entry.matrixField.entriesField[0] ?? null %}
{{ relatedEntry.title }}

Which results in Key "0" in object with ArrayAccess of class "craft\elements\db\EntryQuery" does not exist.

Craft CMS 3.5.17.1


texts: How would you import content with embedded images, ideally using FeedMe?

texts:
More of a general question rather than a specific issue I have right now. I want to migrate a site from a bespoke CMS, which relies heavily on CKEditor for embedding inline images into HTML content.

Obviously I'd like to import the html content, but somehow translate the embedded images into proper Craft asset uploads, embedded into a Redactor field (obviously I know that keeping images separate from text is fine, but that is a bigger issue than I'm prepared to deal with!).

Would love to know if anyone has done this before, and how they approached it. Extra points for doing it with FeedMe, which works very well for me.


texts: Asset subfolder is not showing in the entry field as a folder option

texts:
I have an asset folder images and I have created a subfolder in the images folder so:

images
   |
subfolder

In my entry fields I am not seeing the subfolder in the asset selection pop-up. Any ideas why this would be?


texts: Matrix loop (nesting?) issue using switch

texts:
First let me say this: I'm new to Craft and Twig. So: my apologies for probably overlooking the obvious. I hope you can offer me some help... I've been trying for a couple of days to solve this puzzle. Nothing seems to work. ;-S

I'm trying to create a simple events calendar using Craft 3, Twig and Bootstrap 4. The calendar exist of two parts: 1. a section with 3 columns (col-4) that lists the events; and 2. a divider (col-12) that contains the month and year. I used the Matrix field in Craft to be able to be flexible in sorting events within a certain period of time.

The Issue:
I expected to see the three columns to neatly sit beside each other horizontally (on the desktop version of the site). But this doesn't seem to work right now: because I use a for loop to enable switch, the for loop I need for outputting the event-items results in the same row of events being repeated a couple of times instead of just once.

What am I doing wrong?

I very much appreciate any thoughts.

Greetings from The Netherlands, sorry for my bad English,

Mars

{% block calendar %}

    {% for block in entry.calendarGroup.all() %}

        {% switch block.type %}

            {% case "events" %}

                    {% for entries in entry.calendarGroup.type('events') %}

{{ block.eventDate }}

{{ block.eventTitle }}

{{ block.eventType }}

{{ block.eventTime }}

{{ block.eventLocation }}

{{ block.eventDescription }}

                    {% endfor %}

            {% case "months" %}

{{ block.month }}

{{ block.year }}

            {% endswitch %}
        {% endfor %}

{% endblock %}


texts: Is it possible to convert a plain text field to a rich text field, without losing content?

texts:
I originally had some content stored in a plain text field but I want to give my co-workers the ability to add anchor links, lists etc..

If I were to change the field type form Plaintext to Rich Text would I lose that content?

Also right now to output it, I am using the following :

<p>{{ entry.field }}</p>

so I would have to change that to just using

{{ entry.field }}

Will converting it to rich text, automatically add paragraph tags for me or would I have to go into each one and resave?


texts:
How can I listen in my plugin to see if

craft()->on('users.saveUser', function(Event $event) {

onsaveUser came from front end creation or control panel ?


texts: Allow user to delete their own account from the front end

texts:
I'd like to allow a non-admin user to remove their own account from the front end of my app, without allowing them CP access.

I'm concerned that if I give the user group deleteUser permissions they will just be able to delete any other non-admin user if they change the values of my forms hidden inputs.

Here is my current form:

<form method="post" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="users/deleteUser">
  <input type="hidden" name="redirect" value="account/delete/success">
  <input type="hidden" name="userId" value="{{ currentUser.id }}">
  <button type="submit" class="btn  btn--red">Delete my account!</button>
</form>

Is it best that I create a custom controller action to handle this and first check they are only deleting themselves before passing it off to the craft()->users->deleteUser() function? Or is there a better way?


texts:
My Craft blog has the path localhost:8888/blog
The Assets are in the folder assets, so its localhost:8888/blog/assets.
I set the path of an image to /assets, but then it looks for an image at localhost:8888/assets. Is there any way to handle this dynamically, without needing to write blog/ in front of every asset url?


texts: Is there a way to include partials in Craft without setting a path?

texts:
To separate code and avoid duplication I am trying to split up recurring pieces of twig code into partials (think of a nav or a block of services for example).

I tried using include but Craft requires me to register a template path. This is also stated in the docs.

I'm not really sure this is the best way to do it since I would litter my "Sections" with "Singles" which would just function as nothing more include templates.

For example in my home.twig I have the following piece of code:

        {% include 'pages/home/dienstenGrid.twig' %}

Which would render the corresponding include template. But to be able to do this I have to register this "section"

Something about this feels gross, and I was wondering if there's a better way to go about this issue. If This is the way I will use it this way (Star Wars: The Mandalorian pun intended)


texts: Entry URIs incorrect when using entriesService->saveEntry()

texts:
I'm doing an import, and saving entries into a channel with saveEntry(), but the entry's URL gets saved in the wrong format.

The URL format for the channel is: news/{postDate.year}/{slug} and I'm saving the entry with the following code:

$title = utf8_encode($article['article_language_name']);
$description = utf8_encode($article['article_description']);
$text = utf8_encode($article['article_text']);
$date = new \DateTime($article['article_start'], new \DateTimeZone('Europe/Oslo'));

$entry = new EntryModel();
$entry->sectionId = $targetSectionId;
$entry->typeId = $targetEntryType;
$entry->authorId = $targetAuthorId;
$entry->postDate = $date;
$entry->enabled = true;

$entry->getContent()->title = $title;
$entry->setContentFromPost(array(
    'leadText' => $description,
    'bodyText' => $text
));

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

All the URIs lack the year param in them, but that does get included if I save the entry via the CP afterwards.

What am I doing wrong? The postDate seem to be in the correct format, but maybe I'm missing something?


texts: Nginx Vhost Config - Get page based on translated URI and without parameters in url

texts:
I have a localized site, localization works fine for homepage (/en/), however the links to other page does not work (/en/rooms) where /chambres works fine for default language.

The English 'chambres' page is accessible with /en/?p=rooms

I would like the english page being accessible with /en/rooms

It's definitely an Nginx vhost config issue. The config listed in Locales sub directories on Nginx didn't solve my problem.

This is my english index.php:

// Tell Craft to serve the English content
define('CRAFT_LOCALE', 'en');

This is in my general config file:

'quartiergeneral.craft.dev' => array(
        'devMode' => true,
        'usePathInfo' => true,
        'omitScriptNameInUrls' => true,
        'environmentVariables' => array(
            'basePath' => '/home/vagrant/Code/quartiergeneral/craft/public/',
            'baseUrl'  => 'http://quartiergeneral.craft.dev:8000/',
        ),
        'siteUrl' => array(
            'fr' => 'http://quartiergeneral.craft.dev:8000/',
            'nl' => 'http://quartiergeneral.craft.dev:8000/nl/',
            'en' => 'http://quartiergeneral.craft.dev:8000/en/',
        ),
    ),

This is my nginx config vhost:

server {
    listen 80;
    server_name quartiergeneral.craft.dev;
    root /home/vagrant/Code/quartiergeneral/craft/public;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
        rewrite ^(.*) /index.php?p=$1 last;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/quartiergeneral.craft.dev-error.log error;

    error_page 404 /index.php;

    sendfile off;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}


texts: Determine Entry based on URL Parameters?

texts:
I have a bit of code that checks if a page's title has been manually set in a parent template, and if it has to use that, otherwise to use entry.title. This is what that bit looks like:

{% set activeTitle %}
     {% if pageTitle is defined %}
         {{ pageTitle }}
     {% else %}
         {{ entry.title }}
     {% endif %}
{% endset %}

I however have some pages like so:
http://example.com/foo/text.html?sectionId=6&handle=bar&entryId=170&slug=somethingclever

How do I get the entry based on the parameters that are defined in the URL? And then use this entry's entry.title to set my page title?


texts: How to change the Craft 3 activation email?

texts: In my organization many of the employees believe the user activation email sent out by Craft is spam.  How do I change the email text and possibly add an image, like our company logo, to the email?


texts: Similar plugin filter results by section

texts:
I currently have the Similar plugin on my system, and I'm looking for similar entries by Category. It's working great, but I'm looking to limit the results to a specific section.
    {% set limitCriteria = craft.entries().section('merchants').limit(4) %}
    {% set similarEntriesByCat = craft.similar.find({ element: entry, context: entry.vertical, criteria: limitCriteria }) %}

    {% for similarEntry in similarEntriesByCat %}

{{ similarEntry.title }} ({{ similarEntry.count }} tags in common)

    {% endfor %}

But the above code returns the following database error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column
'structureelements.structureId' in 'group statement' The SQL being
executed was: SELECT elements.id, elements_sites.siteId,
COUNT(*) AS count FROM (SELECT elements.id AS elementsId,
elements_sites.id AS elementsSitesId, content.id AS
contentId FROM elements elements

Unsure how to fix the above?


texts: Guest Entries - Two ajax forms for different section entries. Receiving 404 only on second form?

texts:
I am using the guestentries plugin to create two different section entries. I have two similar html forms on the same front end page. They both use the jquery validate plugin before submiting via ajax. The first form for sectionId(3) does some stripe token generation before submitting to the plugin to submit the payment and create the entry. This is working fine.

The second form doesn't do any stripe calls and is using very much the same jquery ajax call to submit to a sectionId(4). This ajax submission is always returning a 404 and doesn't get to the guestEntries plugin so it seems craft isn't handling this submission like it should?

Succesful request/response

[Code]

    var formData = $("form[name='playerForm']").serialize();
    $.post('/', formData , function(response) {
      if (response.success) {
      //On Submit Success
      $("form[name='playerForm'] input[type='text'],select").val("");

      $('#playerForm').slideUp();

      $('#registered_user_name').text(response.title);
      $('#myModal').modal('show');
      $('#submitLoader').replaceWith('<input type="submit" class="submit" id="playerSubmit" value="Continue" />');

    }else{
      console.log(response);
    }
  });

[Form Data]

CRAFT_CSRF_TOKEN:kv8AfC8Odbhq7OFX6eUhJEi~lm2LqTgmubFer48b|4af89cb67bc43b2efb63a00273e638708f85f5ab
action:guestEntries/saveEntry
sectionId:3
fields[firstName]:Test
fields[lastName]:Guy
fields[homeTown]:Town
fields[phoneNumber]:234 342 2343
fields[companyEducationalInstitution]:Test Company
fields[averageScore]:81-90
fields[yearsInTheTournament]:1
token:tok_19pQkWKdnBUCmelLfVYMRhaF
fields[email]:test@test.com

Failed request/response

[Code]

var data = $("form[name='sponsorForm']").serialize();

$.post('/', data, function (response) {
  if (response && response.success) {
    console.log(response);
  } else {
    console.log(response);
  }
  $('#submitLoader').replaceWith('<input type="submit" class="submit" id="sponsorSubmit" value="Submit" />');
});

[Form Data]

CRAFT_CSRF_TOKEN:kv8AfC8Odbhq7OFX6eUhJEi~lm2LqTgmubFer48b|4af89cb67bc43b2efb63a00273e638708f85f5ab
action:guestEntries/saveEntry
sectionId:4
fields[sponsorFirstName]:Test
fields[sponsorLastName]:Guy
fields[sponsorPhoneNumber]:252 356 5626
fields[company]:Test Company

I've compared the request headers and they are identical so I don't think it's an ajax header problem. Not sure why first form would work and second would fail. Any help is greatly appreciated.


texts:
I'm trying to order my users with craft.users.order('lastName'), which should be no problem, since I'm pulling that straight from the documentation; however, it's not working for some reason. Is this a current a bug in Craft?

Currently, I have users with these last names: Apple, Campbell, Jackson.

With order('lastName'), it's printing out: Campbell, Jackson, Apple. So no alphabetical order is being applied asc or desc.


texts: Set Twig variable with javascript/jquery for displaying entries based on clicked value

texts:
I have a filter system on my website which uses categories. The categories have all got their own ID tagged to their HTML Element. Now I just need to get the clicked checkboxes to add their ID to the Twig variable which displays the entries in the for loop.

{% set categories = craft.categories.section('retrospect') %}

{% set relatedCategories = [] %}

{% for category in categories %}
  {% set relatedCategories = relatedCategories|merge([taggedIds]) %}
{% endfor %}

{% set related = craft.categories.section('retrospect').id(relatedCategories) %}

{% set relatedArticles = craft.entries.section('retrospect').relatedTo(related) %}

{% for entry in relatedArticles.order('caseNumber asc').after('2016-01').before('2016-12') %}
  {{ entry.title }}
{% endfor %}


texts: Create structured object from query results

texts:
I'm trying to create a list of countries with a sublist of territories per country based on their existence in the same record. The following is shorthand pseudocode to illustrate:

    locations =>
         United States =>
             California
             Massachusettes
             New York
         France =>
             Lille
             Marseille

Here is my code so far:

   {% set allEntries = craft.entries.section('projects').limit(2000) %}
   {% set countries = allEntries|group('country') %}
   {% set country_arr ={} %}

   {% for country, entriesInCountry in countries %}

       {% if not attribute(country_arr, country) is defined %}

         {# Add country to list, if unique #}

         {% set country_arr = country_arr | merge([country]) %}

       {% endif %}

       {% for entry in entriesInCountry %}

          {# Somehow add the entry.state here as a property or sub-object of the country, if unique #}

       {% endfor %}
  {% endfor %}


texts: I'm following this tutorial (Managing Your Craft Inventory Using Snipcart Webhooks) and have downloaded the repository from GitHub and cloned. The folder was created without inconvenient but is still not recognized in the admin dashboard


texts:
I would like to make instruction field info on multiple lines in CP to improve legibility.
You can make a line return when you input the field instructions but it does not work.


texts: How do you create two grid columns like the Entry Edit page within a plugin?

texts:
I have a plugin where I'd like my CP tab to output two columns just like the entry page.  On the left, would be the body and then there would be a nice dividing gap and then on the right there would be a aside column.

I've tried to copy the way that the Entry Edit page works but I must be missing something.

Extending _layouts/cp wraps everything on the page with the following three divs which don't seem to get output at all on the Entry Edit page:

             ...

How does the entry page get rid of these divs?  I'm not seeing anything obvious in the templates.

EDIT To be clear, I can create the layout that I want, except for the fact that the layout I want gets wrapped in the above code and makes the gutter disappear and messes up the padding around the two columns on the page.  If I extend the {% extends '_layouts/cp' %} and remove those three divs above, just like the Edit and Entry page seems to do somehow, the page displays just as I want it to.

What I can't figure out is how the Entry page is getting rid of those three divs. It uses {% extends '_layouts/cp' %} and those divs do not appear on the Edit an Entry page.


texts: Inline image transform using Matrix field for image quality?

texts:
Hope I'm not posting incorrectly here but don't have enough reputation yet (really don't understand that system at all) to be able to comment on another post here on the exchange.

Original Post - inline image transforms

I'd like to get this to work but not having any luck at all. This is my code in my template so far.

{% for block in entry.matrixBlocks %}

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

{{ block.text }}

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

{{ block.quote }}

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

    {% set smallImage
        = {
        mode: 'fit',
        width: 600,
        height: 200,
        quality: {{ block.quality.value }},
        position: 'top-center'
        }
    %}

    {% for asset in block.image %}

    {% endfor %}
    {% endif %}

{% endfor %}

The quality in {{ block.quality.value }} is the name (handle) of a field I have storing a number from 1-100 in my Matrix Block. I am using Max Lazars range field to store the number.

Upon trying this say by Live Preview the page never refreshes. If I change the {{ block.quality.value }} to a number then it all works again as expected.

Would love to get this working so any help would be greatly appreciated to let me know where I'm going wrong.

Thanks,

Mark


texts:
I want to get all images from the section projekte which are bound to the asset field bild I then want to fiddle around with .limit() and maybe random filters.

So I grabbed all images like described here

This works but as soon as I add .limit()

{% set projectImg = craft.entries.section('projekte').find() %}
{% set projectImages = [] %}

{% for item in projectImg %}
  {% set currentImage = item.bild %}
  {% set projectImages = projectImages | merge(currentImage) %}
{% endfor %}

{% for asset in projectImages.limit(3) %}
   <img src="{{ asset.url }}">
{% endfor %}

This results in

  PHP Notice: Array to string conversion

Why can't I just ad whatever filter I want on that new loop now?


texts: Trouble running a plugin console command

texts:
I'm trying to get a basic console command for my plugin to run but not having much luck. I have created a folder called consolecommands inside my plugin directory and have created a file called AcmeNotificationsCommand.php.
In this file I have:
namespace Craft;

class AcmeNotificationsCommand extends BaseCommand
{
    public function actionHello()
    {
        echo "hello";
        return 0;
    }
}

From the console I am running /Users/dave/acme/craft/app/framework/yiic acmenotifications hello
But yiic comes back and says:
The following commands are available:
- migrate
- shell

So I guess it's not picking up my new console command.  What am I missing?
Update:
It occurred to me that maybe I was running the wrong yiic file since I could not see the Querygen command that is in the app/consolecommands directory as expected.
So instead I tried running /Users/dave/acme/craft/app/etc/console/yiic to see what commands were available and I got the following error:
0 /Users/dave/code/acme/craft/app/Craft.php(397): CComponent->__call('getTranslatedBr...', Array)
1 /Users/dave/code/acme/craft/app/Craft.php(397): Craft\ConsoleApp->getTranslatedBrowserLanguage()
2 /Users/dave/code/acme/craft/app/etc/db/DbConnection.php(57): Craft\Craft::t('Craft can???t c...')
3 /Users/dave/code/acme/craft/app/framework/base/CModule.php(387): Craft\DbConnection->init()
4 /Users/dave/code/acme/craft/app/etc/behaviors/AppBehavior.php(41): CModule->getComponent('db')
5 [internal function]: Craft\AppBehavior->isInstalled()
6 /Users/dave/code/acme/craft/app/framework/base/CComponent.php(261): call_user_func_array(Array, Array)
7 /Users/dave/code/acme/craft/app/services/PluginsService.php(89): CComponent->__call('isInstalled', Array)
8 /Users/dave/code/acme/craft/app/services/PluginsService.php(89): Craft\ConsoleApp->isInstalled()
9 /Users/dave/code/acme/craft/app/etc/console/ConsoleApp.php(53): Craft\PluginsService->loadPlugins()
10 /Users/dave/code/acme/craft/app/framework/base/CApplication.php(165): Craft\ConsoleApp->init()
11 /Users/dave/code/acme/craft/app/framework/YiiBase.php(121): CApplication->__construct('/Users/dave/cod...')
12 /Users/dave/code/acme/craft/app/etc/console/yiic.php(76): YiiBase::createApplication('Craft\ConsoleAp...', '/Users/dave/cod...')
13 /Users/dave/code/acme/craft/app/etc/console/yiic(4): require_once('/Users/dave/cod...')
14 {main}%

I also noticed a similar error when looking at the databaseimportexport plugin. Not sure if this is a bug or whether I am still doing something wrong?


texts: Why does my custom element type error around locale being missing on the element types' model?

texts:
I have made numerous elementTypes in my plugin that all work perfectly but for some reason one elementType keeps having an error when trying to view the Model's content or custom fields.

This is the error:

Property "Craft\Myplugin_OrderModel.locale" is not defined.

Everything looks exactly the same as all the other models that are elementTypes in my plugin.

All my plugins elementType models are using

public function isLocalized()
{
    return false;
}

but the issue still persists with that one Model.


texts: What can we do to help avoid member activation emails going to spam?

texts: We have a new Craft site that includes front-end member registration. We've heard from the client that many of the activation emails are getting stuck in spam filters (and I just tested with the same result). Is there anything that we can do to avoid this? Perhaps add SPF records?


texts: Add settings to plugins cp section instead of settings page

texts:
I've setup a plugin like so http://domain/admin/plugin-handle (cp section) and a settings page here http://domain/admin/settings/plugins/plugin-handle

I can edit my plugin settings under the latter URL, however I would like non admins to be able to do so as well, but under http://domain/admin/plugin-handle

How can I go about this? Adding e.g.

{{ forms.textField({
    label: 'Headline'|t('craft-terms-of-service'),
    instructions: 'Enter the headline of your TOS here.'|t('craft-terms-of-service'),
    id: 'tosHeadline',
    name: 'tosHeadline',
    value: settings['tosHeadline']})
}}

to the http://domain/admin/plugin-handle template (src/templates/index.twig) (cp section) non-admins have access to, I get Variable "settings" does not exist. I can't figure out how to make it accessible/exist.

Thanks in advance

Edit

Figured out how to add fields to the cp section through the "Getting Started with Craft Plugin Development" course on craftquest.io, however the way I'm saving the settings to the db is rather crude. I'm just doing Craft::$app->db->createCommand(.... to update the plugins table. It works, but I'm sure there are much more elegant ways of doing it?


texts: Customizing Stripe payment form for Craft Commerce 2

texts:
Where does one start with matching the style of the Stripe payment form to the rest of the site?

Using Stripe for Craft Commerce Plug-In

 {{ plan.getGateway().getPaymentFormHtml({})|raw }}

This enables the form with Card Holder info and credit card details.


texts: I want to edit the registration form on my site. I have set up new fields and added it to the field layout under setting. However, the changes still don't appear on the registration form. Another problem is that the registration form is not an entry. Under the menu bar, the registration form seems to be just an added URL. Please help.


texts: Use conditional for Element API results?

texts:
Using the Element API is there a way to get entries by dateUpdated OR dateCreated within the last whatever time, say day?

Or a way to get the entry IDs for both of those criteria then do a query based on just the IDs from both results?

I want to get any entry that was created or updated within the last day using the API but can't quite get it.


texts: How to use the same category group as a filter on multiple channel sections?

texts:
I have two channel sections, each with only their own entry types. I've added the same category group field to both. I'd like to filter each channel's list of entries by the same category group.

So if you're on Channel Steve (for example) you could hit the Category B link and see all the entries in the channel tagged with Category B. Then the same for Channel Bob. The same Category B link would be there, but when clicked it would show only the entries in Channel Bob tagged with Category B.

The problem I'm running into is that each category group uses only one path and template, and I need n of them. It seems like it'd be easy enough to associate one path/categories with one template multiple times for each category group so the category variable would be available on each channel's template. I think this is the optimal solution.

Right now I'm making it work with URL segment sniffing, but that feels hacky.

So, how can you set up category filtering on multiple channels with the same category group?


texts:
I'm currently adapting a shipping plugin that has a form for people to submit their tracking number and shipping company.

The template checks the variable, and if it exists, it generates the proper information for the tracking number and company. If the variable doesn't exist, it shows the form.

basically this

if($ttr<>"") {
      All the business logic
} else {
    <form method="get">
        <input type="text" name="tracknum" />
        <select name="company" class="smallForm" id="company">
                (...options...)
        </select>
        <input type="submit"/>
        <input type="hidden" name="orderAction" value="track"/>
    </form>
}

The original check for this this variable looks like this

if (isset($_POST['tracknum']))
$ttr = $_POST['tracknum'];
else $ttr = $_GET['tracknum'];

So for I put each check in its own variable function, as so

public function ttr()
{
   if (isset($_POST['tracknum']))
       $ttr = $_POST['tracknum'];
   else $ttr = $_GET['tracknum'];
   return $ttr;
}

and call it thusly

{% if craft.PluginName.ttr|length %}
    All the business Logic
{% else %}
    <form method="get">
        <input type="text" name="tracknum" />
        <select name="company" class="smallForm" id="company">
                (...options...)
        </select>
        <input type="submit"/>
        <input type="hidden" name="orderAction" value="track"/>
    </form>
{% endif %}

This currently returns

Undefined index: tracknum

Specifically on the line

else $ttr = $_GET['tracknum'];

Now this makes sense to me, as the form hasn't been submitted, so There should be nothing in the $_POST or $_GET. But if that's the case, why does it work on the original website, but not here?

Thanks!


texts:
I am Craft newbie, and am trying to use PayPal express checkout but am stuck on a confirmation route.

How do I register a route like this:

localhost:8888/app/confirm?token=EC-5UA33446UB5625646&PayerID=8RB74GZ8ASWGQ

What I have done so far:

Registered route confirm on the plugin but when PayPal adds the token and payerId, Craft doesn't understand the route anymore.

public function registerSiteRoutes()
{
    return array(
        'app/confirm' => array('action' => 'app/confirm')
    );
}

Any help will be appreciated.


texts: Adding new matrix block will result in wrong locale

texts:
I have matrix fields where I dont have translation on the whole matrix, but only on the fields within a certain block. Nothing complicated or fancy. When I add a new matrix block in the admin, it will result in a locale that is not the same as the one I'm editing at the moment: I have two locales installed (sv and en). Everything works fine. But its just that when I'm editing the swedish (sv) entries I can see that the locale-indicator next to the matrix text-field says "en". But when I edit the swedish locale, I want to start adding text in the locale that I'm editing at the moment.

I'm using Craft Pro 2.4.2668

Above is a screenshot from the admin, with the locale-indicator (screenshot taken right after klicking the "+ Menu item"-button


texts: field from category not available via craft.categories

texts:
my categories have a custom field called titleTag for SEO as well as a number of other fields. When I render them at their URI (/categories/cat1) I can output those fields easily with {{category.titleTag}} etc. However on the main category page I also have a filter button that loads another URI via jQuery.load() to filter the items based on category. So in the filter template I have this to start.

{% set filter = craft.request.getParam('filter') %}
{% set category = craft.categories.slug(filter) %}

I then want to output (amongst other things) the custom field values of the found category like so {{category.titleTag}} but it comes out null (the category found I am testing with has the field filled out.

Where am I going wrong?


texts: Updating Craft Produced Fatal Error.What now?

texts:
Just tried updating craft from version 2.4.2669 to the latest version 2.4.2702 unfortunately it threw a fatal error with the following error message:

  Status: OK

  Response:  Fatal error: Out of memory (allocated
  33030144) (tried to allocate 41 bytes) in
  /homepages/3/d272256762/htdocs/crafttest/craft/app/framework/db/CDbCommand.php
  on line 518

So I then tried to manually install it by uploading the app folder. Clicked through on the update databases it started working, but again threw the same error.

The site is on a shared server so I can not do much regarding memory limits.

So now I have no CMS and no frontend what can I do to rectify this problem to either rollback to the previous version or update to the newer one?


texts: Using Aliases inside Admin Panel for fields

texts:
I was wondering if it was possible to use an alias inside a field in the Admin panel. For example, I have a global section called "Navigation" which contains a matrix called "Links". This matrix allows the client to create links for their navigation bar. Inside each matrix block, is a field called "Link Url" where the client can put in a link.

Right now the client is hardcoding urls for the production site, so my links don't work on my dev environment. I would like to rectify this, with some type of elegant solution.

Any ideas?


texts:
I'm looking to call the following Module function from a front end form. I've looked through numerous answers but I can't seem to find a definitive answer on this.

Here's my Module's code, but obviously I don't want this to run every time and entry get's saved, but when the form on the front-end calls it.

<?php

namespace modules;

use Craft;

use yii\base\Module;
use yii\base\Event;
use craft\services\Elements;

class ShifterModule extends Module
{
    public function init()
    {

        parent::init();

        Event::on(
            Elements::class,
            Elements::EVENT_AFTER_SAVE_ELEMENT,
            function (ElementEvent $event){
                // Get the correct Entry that's currently saving
                if ($event->element instanceof craft\elements\Entry) {
                    $entry = $event->element;
                    // Set $field to the Field Value
                    $field =  $entry->getFieldValue('proposalStatus');
                    // Set the Proposals > Campaign Authors Email
                    $owner =  $entry->getFieldValue('proposalCampaign')->first()->getAuthor()->emailAddress;

                    if($field == 'delivered'){
                      return Craft::$app
                          ->getMailer()
                          ->compose()
                          ->setFrom('test@test.com')
                          ->setTo($owner)
                          ->setSubject('Proposal Delivered!')
                          ->send();
                    }
                }
            } // Close Function
        ); // Close Event
    } // Close Public Function
} // Close Module Off


texts: Avoid notice of variable's not being set within dev mode

texts:
With dev mode on, I'm getting a warning there is no entry.title, which I know about already because that's what I'm testing for:

{% if entry.title | length == 0 %}
    {% set entry = craft.entries.section('sectionname').slug(craft.request.segment(2)).first() %}
{% endif %}

Is there a way to test for a variable without dev mode triggering this notice?


texts: Translated entry page can not be found (404)

texts:
I have installed and built a website using Craft CMS (with latest updates). I'm running this Craft installation on a Homestead virtual machine.

When I enabled localization and translated entries in a structure section, the url opens a 404 page.

In my setup I have two locales nb_no and en. Both locales are enabled for the section artists. Both locales are using the same url structure for entries: artists\{slug}.

My configuration for siteUrl is as follows:

'siteUrl' => array(
    'en' => 'http://page.craft.dev/en/',
    'nb_no' => 'http://page.craft.dev',
),

Debbuging the problem I see that there is an error in TemplatesController.php. In the function actionRender($template, array $variables = array()) the value of $template is en/artists/andre-bratten instead of artists/_entry as is the case for the main language entry.

Further exploration of logs shows me that Craft executes the following query which returns no result:

[09:30:32.080][trace][system.db.CDbCommand]
Querying SQL: SELECT `elements`.`id`, `elements`.`type`
FROM `craft_elements` `elements`
JOIN `craft_elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id
WHERE (elements_i18n.uri = :uri) AND (elements_i18n.locale = :locale) AND (elements_i18n.enabled = 1) AND (elements.enabled = 1) AND (elements.archived = 0). Bound with :uri='en/artists/andre-bratten', :locale='nb_no'
in /home/vagrant/web/ekko/craft/app/services/ElementsService.php (151)
in /home/vagrant/web/ekko/craft/app/etc/web/UrlManager.php (281)
in /home/vagrant/web/ekko/craft/app/etc/web/UrlManager.php (140)

In my database elements_i18n table the entries both have uri = "artists/andre-bratten" and different locales.

As well there is a problem with wrong locale in the sql query (nb_no instead of en). I set CRAFT_LOCALE to en in the public\en\index.php file.

As I'm rereading this I think that there could be a problem with resolving the correct path (i.e. removing en/ from the front) when the locale is set incorrectly. Does anyone have any ideas why this is happening?

Update

I found out that when I access http:\\page.craft.dev\en\ I am loading public\en\index.php. However when I access http:\\page.craft.dev\en\artists\{slug} it loads public\index.php. So I assume there is a problem with Homestead and nginx?


texts: How do I use Plain Text Field in URL Format?

texts:
I'm creating an events system & I want to include the venue in the url of the event along with the event name.

For now the venue name is just stored using a plain text field.

Is there an easy way in craft to convert a string & slugify it? Could I use any filter I add to Craft? Can I do it without a plugin of some sort?

I've tried the following

{ (eventVenue ? "-" ~ eventVenue | lower | replace(' ', '-') | replace('/[^\w]/','')) }

along with using Twig PCRE

{ (eventVenue ? "-" ~ eventVenue | lower | preg_replace('/[^A-Za-z0-9-]+/') ) }

Both of which give the error Expecting name or number


texts: How do I print the options in a dropdown field?

texts:
I have a dropdown field with X options.  I want to print each option as a button.

I tried...

    {% for option in entry.isotope.options %}

{{ option }}

    {% endfor %}

isotope = dropdownFieldHandle

But I get the error Variable "entry" does not work'.


texts:
A little question , does anybody have or know someone with a plugin for Craft which can show Offie365 files/docs in Craft to use on an intranet/site?
Just like the feature below:

Assets are files managed by Craft. They live in “asset sources”, which represent physical folders on your server. And with Craft Pro, you can also set up Asset Sources that live on Amazon S3, Rackspace Cloud, and Google Cloud.


texts:
I'm working on a online store website and we need a filter to hide some products based on the country. I created a lightswitch field called "Hide in Europe" (default false) and added it to the categories, and set it to true on some products to test.

This is the block of code that creates the query params to filter the products.

<!-- START QUERYPARAMS -->
        <!-- Initialize query paramaters array -->
        {% set queryParams = {} %}

        <!-- Add sale parameter to query paramaters array if searching for sale items -->
        {% if craft.request.getSegment(2) == "sale" %}
          {% set queryParams = queryParams|merge({ hasSales: true }) %}
        {% endif %}

        <!-- If on new arrivals page, add new arrivals to query parameters array -->
        {% if craft.request.getSegment(2) == "new-arrivals" %}
          {% set queryParams = queryParams|merge({ newArrival: true }) %}
        {% endif %}

        <!-- If order parameter passed in, merge it to the query parameters array -->
        {% if craft.request.getParam('order') != "" and craft.request.getParam('order') != "default-sorting" %}
          {% set queryParams = queryParams|merge({ order: craft.request.getParam('order') }) %}
        {% endif %}

        <!-- Initiating rate variable -->
        {% set rate = 0 %}

        <!-- Setting rate according to current currency -->
        {% for currency in craft.commerce.paymentCurrencies %}
          {% if currency == cart.paymentCurrency %}
            {% set rate = currency.rate %}
          {% endif %}
        {% endfor %}

        <!-- Set price variables to default values if none are passed in -->
        {% if (craft.request.getParam('lowPrice') != "" and craft.request.getParam('highPrice')) != "" %}
          {% set lowPrice = (craft.request.getParam('lowPrice')) / rate %}
          {% set highPrice = (craft.request.getParam('highPrice')) / rate %}
        {% else %}
          {% set lowPrice = 0 %}
          {% set highPrice = 1500 * rate %}
        {% endif %}

        <!-- Add price paramaters to queryParams array -->
        {% set queryParams = queryParams|merge({
          defaultPrice: [
            'and',
          '>= ' ~ lowPrice,
          '<= ' ~ highPrice,
          ]
        })
        %}

        {% set queryParams = queryParams|merge({ hideInEurope: false }) %}
        <!-- END QUERYPARAMS -->

        <!-- Perform query and store results in results array -->
        {% paginate craft.commerce.products(queryParams).type(typesArray).search(queryString ~ (q is defined ? ' ~ ' ~ q : '')).limit(productLimit) as pageInfo, products %}

As you can see, we have:

{% set queryParams = queryParams|merge({ hideInEurope: false }) %}

But for some reason, the products that I set as TRUE are still showing on the list. On the other hand, if I set hideInEurope: true, only the products that I set the field as true show, so it seems to be working. Looks like when I set the param to false, it gets "ignored". Am I missing something?


texts:
I want to use the UID to get a user from a url and don't want to use the ID as it is guessable. I know I can do craft()->users->getUserByUid($uid); but after getting the uid, the uid is not on the user model which is kinda a pain.

For example what if i wanted the uid for the currently logged in user?


texts: Difference between using subscript syntax and "dot" syntax when accessing attributes of a variable or advantages of usage one of them

texts:
When to use

{{ variable.property }}

and when to use

{{ variable['property'] }}

Is there a difference between these methods of accessing attributes of a variable or advantages of using one of them?


texts:
How would I write a variable to detect if the current page/Url I'm viewing is for an entry, rather than a section home page or a single?

i.e

{% if I'm currently viewing an entry %}
    do this
{% else %}
    do this
{% endif %}


texts: Possible to Get grunt-uncss Working with Craft?

texts:
I'm working on a site that uses bootstrap so has a very large CSS file with many selectors that are not being used. To reduce the size of the file, I'd like to use the grunt-uncss task, but it does not work as well with CMS-based sites, as opposed to static HTML files.

I've seen guides for how to make it work on Wordpress but the guide includes Wordpress specific plugin-ins that I don't believe are available on Craft.

Curious if anyone is using the grunt-uncss with on a Craft site and how it was set-up to make it work effectively? Would like it to run on all pages of the site, ideally. Thanks!


texts: How to search children with relatedTo param

texts:
My templates that referenced entry.children or entry.getChildren() have started throwing deprecation notices:

  Calling getChildren() to fetch an element’s target relations has been deprecated. Use the relatedTo param instead.

What is the preferred way to search for an entry's children — either ALL of its children, or just its direct children — using the relatedTo() param?


texts: Associating multiple FreeForm entries with a single Craft entry

texts:
I have a Freeform which collects information on item(s) to be converted from analog to digital (VHS tape 16mm film, etc). The form requires the user to be logged in.
There may be cases where the user fills out the form more than once, because they have more than one item to convert. I want to do two things:

Save the results of each form submission in a standard Craft entry. I believe I understand how to do this, I just need to hook up all the fields.
Relate one or more form submissions to a single "order", which I believe would be represented by a single Craft entry.

An order entry would have:

User
Date
Relationship to 1 or more form submissions.

What is simplest way to accomplish this? FYI, I do not want to write a custom plug-in, nor write a lot of code.
My first thought was to create an initial order form which collects only the title of the order, and then pass that via a query string or JavaScript into the second form, thus creating a relationship where the first form is the "parent" and submissions of the second form are the children.


texts: Freeform unsubscribe and redirect non admin users away from admin area

texts:
Good Evening all,
I have a site that lets users subscribe/unsubscribe using Freeforms Stripe payments.
Everything is working fine, except for when the user unsubscribes, the link that is required is within the Craft Dashboard, therefore the user has to have a basic amount of panel access, which I want to avoid if possible, however as a fix, is there any way of redirecting non admin users away from the login/dashboard if they type /admin?


texts:
I want to cache the cart using key cart.id to save some db queries.

{% set cart = craft.commerce.cart %}

{% cache globally using key "cartId=" ~ cart.id ?? "empty" until cart.dateUpdated %}

{% if cart.lineItems | length %}
    {% for item in cart.lineItems %}
        {{ item.sku }},
    {% endfor %}
{% else %}

Cart has no items

{% endif %}

{% endcache %}

Is caching by cart.id sufficient?
Is there any potential risk?
What is {% set cart = craft.commerce.cart %} actually setting when cart.id = null ?


texts: How can I set a landing page for a structure with no slug?

texts:
In Craft2, I have structures that each have a landing page/homepage for that structure.

If the structure's URI format is "liver/{slug}", how do I make the 'landing page' entry have a URI of only "liver/", with no slug?

This is important since I want users visiting the liver/about-us page to be able to remove 'about-us'...and land on the liver homepage (not get a 404).

I don't understand routing very well-- from what I have gleaned I cannot see how to make routing associate a given URI with a given entry-- I only understand how to associate it with a template.

This is similar to this question, except that I want these landing pages to have dashboard entries and use the same template as all the other pages...not be an index-type page.

Note: I have seen answers regarding adding a site homepage to a structure, but this is not a site homepage- these landing pages do not live at the site domain root...they live at the root of each structure's URI.

Thanks in advance for the help.


texts: Rename Entries to Content on CP top menu

texts:
A purely cosmetic change, but just wanted to know if its possible to change the menu item for Entries to something like Content? From a client point of view, I just know some will beg me to change this :)

Would also be handy to remove the Dashboard altogether as well for some cases.


texts: How do I create a custom Twig extension which includes third party code?

texts:
I found several solutions to build a dynamic, complex navigation in craft. One is described here:
 Adding active class to globally cached navigation. Now i would like to create a more powerfull twig filter for
 creating different navigation and breadcrumb types with selecting of active links. I already wrote some test code in plain php and used for this the library simplehtmldom (helper for changing dom elements in php like in jquery). A demonstration about what i want to do can be found here:
 http://www.bahu.ch/craft/. Now i started with creating the twig filter, but i can't include the library in my plugin. Here is a quick overview of my plugin code.

   <?php
   namespace Craft;
   use Twig_Extension;

   use Twig_Filter_Method;

Now i need to include the library (i know, that the next line is incorrect)

   include('simple_html_dom.php');

   class k4NavigationTwigExtension extends \Twig_Extension

   {

public function getName()
{
    return 'k4Navigation';
}

public function getFilters()
{
    return array(
        'k4Navigation' => new Twig_Filter_Method($this, 'k4Navigation'),
    );
}

public function k4Navigation($navigation)
{

    $html = str_get_html($navigation);

on the next line the current url should replace the string "test.html"

    $selectElem = $html->find('a[href="test.html"]')[0];

    if (is_object($selectElem)){
       // loop li and set class active
        for ($i = 1; $i <= 20; $i++) {
            $selectElem->setAttribute("class","active");
            $selectElem =  $selectElem->parent();
            if (!is_object($selectElem)){
                break;
            }
        }
    }

    return $html;

   }

   }

Maybe someone can give me a hint, how to includ the library and the first example? You can download the full test code and started plugin from here: https://github.com/tombauer/k4-navigation

Many thanks for any help!

Sunny regards
Tom


texts:
just getting start with Craft, and I can't figure out why my images won't output. Any time I try to output even the path to the url of my image, I get an internal error: Craft\AssetFileModel and its behaviors do not have a method or closure named [...].

I can successfully do this:

{% if entry.pageImage | length %}
    {% for pageImage in entry.pageImage %}
        {{ pageImage }}
    {% endfor %}
{% endif %}

Which just outputs the title of the image. But I want to display the image. I was expecting to be able to be able to use {{pageImage.getUrl()}} or {{pageImage.url}} or {{pageImage.fileName}} but these will throw the aforementioned error. How do I output an image?


texts: Is it possible to take a partial payment of an order in Craft Commerce?

texts:
I have a request from a client to be able to take deposits for events purchased through craft commerce. These are high ticket items and customers would like to spread the cost of payment over several weeks/months before the event.

Is this something that is possible using craft commerce?


texts: Show a child's Matrix within a Structure

texts:
I want to show a child entry and can so:

    {% for entry in craft.entries.section('products') %}

    {% switch entry.level %}
        {% case '1' %}
            {# level 1 #}

{{ entry.title }}

        {% case '2' %}

            {# level 2 #}

{{ entry.title }}

        {% case '3' %}

            {# level 3 #}

{{ entry.title }}

        {% case '4' %}
            {# level 4 #}
            4

    {% endswitch %}

    {% endfor %}

but I can't get a matrix field to show for the child entry, using:

{% for block in entry.myMatrix %}

            {{ block.intro }}

{% endfor %}

within any of the cases?


texts: How can I purchase Craft Client or Craft Pro?

texts:
Docs say 'Right within Craft. If you’re running Craft Personal or Craft Client, there’s a link at the bottom of every page in the CP, which brings up a modal window that handles the whole process.'

I just installed Craft Personal 2.3.2629 and there's no link I can see.


texts: Getting checkbox options for a new entry, without having an entry

texts:
How would I get a list of all the checkbox options associated with a specific field, without having an entry to loop over? I'm using the same form for creating new entries and editing existing ones. Been using {{ entry.fieldValue | default( ) }} for almost everything else.

{% if entry is defined and entry.id is not empty %}
    {% for option in entry.myFieldOptions.options %}
        <div class="checkbox">
            {% set checked = false %}

            {% if option.selected %}
                {% set checked = true %}
            {% endif %}

            {% if not checked %}
                <input type="hidden" name="fields[myFieldOptions][]" value="">
            {% endif %}

            <input type="checkbox" value="{{ option.value }}" name="fields[myFieldOptions][]" {% if option.selected %} checked="checked"{% endif %}>{{ option.label }}
        </div>
    {% endfor %}
{% else %}
    //hardcoded values
    //is there a way to reference available checkbox options directly?
{% endif %}


texts: Output field content for a product in Craft Commerce

texts:
I have added the field "Product Image" to my products. The field is an "asset field" which enables me to upload an image for each product. The field handle is productImage.

How can I output this image in my template?


texts:
I'm trying to display how long til a certain post expires depending on a date/time field.

Example

  Expires in 13 days.

My field is currently displayed by doing {{ entry.expiration }}

I just don't know how I would just display the days remaining until this date.

Thanks


texts:
Is it possible that when my user adds a new entry in a channel on the English site, it gets copied to the channel of my Belgian site, but this entry is set automatically to disabled?

So my English user adds a blog item and enables them, they are copied to my Belgian website but they are disabled?

Thanks!


texts: Plugin to report when site becomes unavailable

texts:
I have a Craft installation on DigitalOcean, with the smallest package:

512MB Memory
1 Core Processor
20GB SSD Disk
1TB Transfer

I installed the default LAMP droplet.

PROBLEM:
MySQL crashes from time to time. There were no significant server load either.

What might be a root cause?

Bonus question:

Is there a plugin that automatically reports when the site is down?


texts: How to build a language switcher that covers entries with custom routes?

texts:
I have a site with a structure and various channels, that live inside that structure.

I started with the language switcher from https://craftcms.stackexchange.com/a/26347/8325; but that will only work for the structure, because I need to build the URLs for some entries that use custom routes manually.

Now I need to build that more complex language switcher.


texts: I could do with flipping the rows in a table, within a template. Is that possible?


texts: Pull in images to table rows using craft.assets wilst looping through a table field

texts:
Thanks in advance to anyone who can help me :)

I have a table field in Craft that my template is pulling in data from... the issue is that in the box at the start of each row I want a different image.

Every time the loop goes round and pulls in the data for each row from the table in Craft I also want it to pull in an image using craft.assets.folderId().

Here is my code so far.. it pulls in the individual images but it repeats the the first row of the table for each image... and then it pulls in all the the images again repeating the next row and so on...
please see this link to get an idea of what I mean: http://code7dev11.co.uk/how-it-works

{% if entry.howItWorksTable | length %}

            {% for row in entry.howItWorksTable %}
                {% for image in craft.assets.folderId('2') %}

                    {{ row.stages }}
                    {{ row.skillsLearnt }}
                    {{ row.classes }}
                    {{ row.price }}

                {% endfor %}
            {% endfor %}

{% endif %}


texts: Template and other files do not update with nitro

texts:
I am using nitro for the time. Sometimes some templates or other files do not update after saving. It feels very random and I cannot exactly reproduce it. At some point they just don't update. I can restart the host in Docker. This will update it once. It's happening on multiple installs of craft. While others are not affected at all. Just now I created a fresh craft install and it seems to work fine. Then I created another one. And it instantly fails to update the changes I made in the config file.
Craft 3.6.12
Nitro 2.0.7
Docker 3.3.1
I deleted and reinstalled nitro and docker twice. Bumped the docker resources to CPU 4 and Memory 10GB. Removed hosts, added them back. Changed file names. Nothing helped.
Any suggestions what else I could try? I could imagine I am missing something simple …


texts: How to limit the amount of entries that is output when limit doesn't work

texts:
I'm trying to limit the amount of entries on my page.

Currently I want 1 news entry (based on if the checkbox is ticked, there could be 10 entries with the checkbox ticked but I only want to show 1 (the latest)) The issue is that the limit() twig function doesn't work with my elementCriteriaModel.

My code:

{# Checking if any news entries have the FeaturedEntry field completed #}
{% for entry in craft.entries.section('news').level(2) %}

    {% if entry.featured.contains('isFeatured') %}

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

News *Chosen*

{{ entry.title }}

                        {{entry.author}}

    {% else %}
            Do Something Else Here

If I attach the limit function to {% for entry in craft.entries.section('news').level(2).limit(1) %}, this only limits the amount of entries my selector can check for the featured field. If i put limit(1) it only checks the first news entry for the field.

I know i can use the slice function but I'm having some trouble inserting it into the right place.

Any help would be very appreciated.


texts: Possible to assign fields (or an image) to a category?

texts:
I'm just getting to grips with Craft but it seems very flexible. To try it out I have set up a structure to store some sample products. These products have an image, text, tags and belong to a category (E.g cakes). I can sort and output products, display in groups even sort by tag - brilliant.

One thing I struggling with is how assign a image and other fields to the category? So that I can then have a page with a list of categories each with an image and text Or even output a single category that I want to highlight on another page?

Should this be a "parent" entry? If so how do I assign a set of fields to the parent item but not the child?

Possibly I am thinking about approaching this the wrong way and I should create a "types" structure in which the entries have a required field that is the "category" and use this to search for any products of matching category?

Confused - any pointers appreciated.


texts: I am having a real hard time understanding why there is not a way to control the password strength of a front-end user registration form. With Craft 3, are there no settings anywhere to control this? I have a project that would include Craft Commerce to handle subscription payments, and during the subscribe portion, the user would need to register first. It seems so strange that a user can register with a weak password.


texts:
I'm creating a product page for a product with multiple variants. In this case the variant represents a different size (with unique SKU, stock, etc..).

It's laid out like so (don't mind the ugly styling):

I don't want to pre-select a size option because I want to avoid people adding the wrong product to their cart.

In the template there's a hidden field with the purchasableId of the variant. The value attribute starts empty and when people click one of the options it is set to the corresponding id.

<input type="hidden" name="purchasableId" value="">

However, when people click 'Add to cart' right away, without selecting a size the following Craft\Exception is shown:

Not a purchasable ID

How can I customize this error message to notify the customer that they have to select a size option?

I could of course solve this problem by using javascript but that doesn't seem very solid to me. So is there a way of validating the stuff added to the cart in the back-end and getting something like a JSON response?


texts: How can I limit the output of assets randomly if an asset exists?

texts:
How can I limit the output of assets based on this criteria?

search all entries randomly in section "homes" for only entries with at least one asset image
limit those results to 8 random assets

I tried this but it does not always show exactly 8 asset images as the random is called first:

{% set assets = craft.assets.limit(null) %}

{% for homesEntry in craft.entries.section('homes').limit(8).order('RAND()') %}
    {% if homesEntry.homeImages|length %}
        {% set asset = homesEntry.homeImages.first() %}

        {% if asset %}

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

Any help is appreciated.


texts: Is this Garnish message bad? "Element was added to more than one selector"

texts:
My plugin has a field type. When I'm editing an entry which uses that field type, this message gets logged to the console:

Element was added to more than one selector

I can tell that it's Garnish which is generating this message, but what does it mean? Is it a problem that needs to be fixed? And if so, how would I go about fixing it?


texts:
In my project, I have a reference to XMLReader in a plugin; however, I get this error message:

Class 'Craft\XMLReader' not found

Here is the code which calls it:

$reader = new XMLReader();

Can XMLReader be used within Craft, or can there be a customization which would allow it?  Thanks


texts: Accessing SEOmatic meta via controller action in Element API triggers HTTPForbiddenException

texts:
I'm attempting to fetch SEO meta for entries inside of an element API, roughly following the advice in Element API integration
Below is the exact code in my element-api.php:
<?php

use craft\elements\Entry;

return [
    'endpoints' => [
        'api.json' => function() {
            return [
                'elementType' => Entry::class,
                'criteria' => [],
                'transformer' => function(Entry $entry) {
                    $seo = Craft::$app->runAction('seomatic/meta-container/all-meta-containers', [
                        'uri' => $entry->uri,
                        'siteId' => null,
                        'asArray' => true,
                    ])->data;

                    return $seo;
                },
            ];
        },
    ]
];

If I hit this endpoint directly in a browser - e.g. http://my-url.test/api.json - it returns a response exactly as expected. However, if I try to hit the endpoint using an external GET requestion with Accept: application/json (I'm using https://paw.cloud, specifically), I get back an error exception of yii\\web\\ForbiddenHttpException
Is there something about runAction inside of an Element API call that isn't allowed? Is there something I need to do to allow this in outside requests?


texts: How to localize password emails and password change form?

texts:
Just wrapping up my first multi-language Craft 2.x site, and the last localization issue we're having is the password reset process. I can't find a way to localize:

The email which is triggered by the "forgot password" form.
The language which the user will be see to when clicking the email's "reset" link.

There are some inconsistencies here because when I have my user set to, for example, Canadian French as their preferred locale, the subject of the email is localized, but the body is not (naturally, since there's no place to actually translate the body text anywhere that I can find), and when the link is visited, the form is in English (even though the link resides in my /fr/ directory, where the config file sets my local to  fr_ca, and the user in question has fr_ca as their preferred locale).

Is there a solution here?


texts:
I have this supersimple navigation:

   {% for entry in craft.entries.section('homepage, arbeiten, info, kontakt, shop') %}

         {{ entry.title }}

    {% endfor %}

Is it possible to add an order filter which orders the entry by the order I wrote the entry handles? I tried to apply .fixedOrder but that does nothing.


texts: no element type exists with getCriteria and custom element type

texts:
I am working on a plugin using the getCriteria function, but for every Element Type I put, I always get an error:

  No element type exists by the type “Comerce_Group”.

$criteria = craft()->elements->getCriteria("Comerce_Group");
$criteria->number = $number;
return $criteria->first();

And here is the Comerce_Group code:

class Comerce_GroupModel extends BaseModel
{
    protected function defineAttributes()
    {
        return array (
            'id' => AttributeType::Number,
            'number' => AttributeType::String,
            'itemTotal' => AttributeType::Number,
        );
    }
}


texts:
I have built a few fields with the Table field.  I noticed an odd behavior maybe it's normal, but want to check.

I use a Table field with defaults entered, the defaults do not show up.  Now for the odd, if I put the Table field in a Matrix field, the defaults show up.  Is that normal Table field behavior?


texts: How I can capture previous and current URL to a hidden form field

texts: I need to create a hidden form field and populate the previous and current URL can someone tell me how I can do that in Craft.


texts: Many db requests with relationship fields

texts:
I have a page with a lot of entries fields. They are awesome but that leads also to a LOT of db requests.

Aside from caching are there some best practices to lower db requests on entries fields?

For example my whole navigation is built with entries fields:

{% for entry in globalsNavi.businessSorter %}
    {{ entry.title }}
{% endfor %}

Would it make any difference if I grabbed only url and title in this example since there are a lot more fields available. And if it would make a difference how would I have to write this?

Something like:

{% for entry in globalsNavi.businessSorter( entry.title, entry.url ) %}


texts: Remove expiration date field from section / entry type

texts:
By default, every entry has an expiration date field allowing the editor to expire an entry. I'm currently working on an application with some sections where expiring an entry doesn't make much sense and could break some parts of the site. So I would like to remove the "expiration date" field from some sections, to prevent someone accidentally setting an expiration date, or setting the field believing it to work in a different way than it actually does.
I've found no way to properly remove the field, at least there's no option for that in the section settings. I could just hide the field with CSS and JS, but of course that's not a solid solution. I would prefer a solution that's enforced on API level. Maybe it can be done with a hook? Or is there a better solution for this (except building a custom element type from scratch)?


texts:
I'm using {% block content %} and a main layout file.

When using live preview the "entire" frame isn't shown (including layout files).

Is there an easy way to get the whole template in?


texts:
I have the following Module loaded into my system, following the Event's on the FeedMe documentation I've implemented the following to change the slug per entry import but unfortunately, it's returning a strange error that I just can't fix.

Here's the module:

<?php

namespace modules;

use Craft;

use craft\feedme\base\Element;
use craft\feedme\events\ElementEvent;
use craft\feedme\services\Process;
use craft\feedme\events\FeedProcessEvent;

use yii\base\Event;

use craft\helpers\ElementHelper;
use craft\elements\Category;
use craft\elements\Entry;

class TitleChangerModule extends Module
{
    public function init()
    {
        parent::init();
        Event::on(
          Process::class,
          Process::EVENT_STEP_BEFORE_ELEMENT_SAVE,
          function(FeedProcessEvent $event) {
            switch($event->feed['name']){
                case 'merchants':
                    $element = $event->element;
                    $element->slug = ElementHelper::createSlug($element->title.' '.'Coupon Codes & Promo Codes');
                    break;
            }
        });
    } // Close Public Function
} // Close Module Off

It returns the following error on each import via the feedme logs.

  Class 'craft\feedme\base\ElementEvent' not found - Element.php: 58


texts: How do I reference a variable/expression inside an expression in twig templating?

texts:
This is the desired code

Which works. However I want the transform name to be replaced by the contents of

entry.newsImageSize

So in a kind of pseudocode it would be

which of course does not work.


texts: Problems exporting entries from ExpressionEngine 3 with Feed Me 2 beta plugin

texts:
I am trying to export entries from my EE 3 install to Craft and import them using the Feed Me 2 beta plugin.

I believe I have followed the instructions on creating a template from within ExpressionEngine 3 with the export.php code from engram-design's github.  I have enabled PHP on the template from within EE.

When I run the mysite-url/export?id=1 file, it gives me this error page:

  {!-- ra:0000000004427cd500000000745c77df --}
  Notice

  Undefined property: EE_Functions::$EE

  ee/legacy/libraries/Functions.php(680) : eval()'d code, line 4 show details

  Severity: E_NOTICE
  Notice

  Trying to get property of non-object

  ee/legacy/libraries/Functions.php(680) : eval()'d code, line 4 show details

  Severity: E_NOTICE

  Fatal error: Uncaught Error: Call to a member function query() on null in /home/iwatermt/public_html/system/ee/legacy/libraries/Functions.php(680) : eval()'d code:4 Stack trace: #0 /home/iwatermt/public_html/system/ee/legacy/libraries/Functions.php(680): eval() #1 /home/iwatermt/public_html/system/ee/legacy/libraries/Template.php(1825): EE_Functions->evaluate('{!-- ra:0000000...') #2 /home/iwatermt/public_html/system/ee/legacy/libraries/Template.php(559): EE_Template->parse_template_php('{!-- ra:0000000...') #3 /home/iwatermt/public_html/system/ee/legacy/libraries/Template.php(237): EE_Template->parse('{!-- ra:0000000...', false, '1', false) #4 /home/iwatermt/public_html/system/ee/legacy/libraries/Template.php(168): EE_Template->fetch_and_parse('', Array, false) #5 /home/iwatermt/public_html/system/ee/legacy/libraries/Core.php(680): EE_Template->run_template_engine('', '') #6 /home/iwatermt/public_html/system/ee/legacy/controllers/ee.php(68): EE_Core->generate_page() #7 [internal function]: EE->index() #8 /home/iwatermt/p in /home/iwatermt/public_html/system/ee/legacy/libraries/Functions.php(680) : eval()'d code on line 4

Any ideas what I'm doing wrong?


texts: hashing form fields to prevent tampering

texts:
I have a front end form for entry creation. I have a few options I don't want tampered with. The docs for |hash say "Prefixes the given string with a keyed-hash message authentication code (HMAC), for securely passing data in forms that should not be tampered with."

I've tried a dropdown field:

<input type="hidden" name="fields[businessStatus][]" value="{{ 'created'|hash }}">

When |hash is added the page just reloads instead of going to the correct redirect URL. So I tried a plain text field with |hash and a hashed string is submitted instead of the string before the filter. I'm guessing this is why the page reloads for the dropdown field, what's being submitted doesn't match one of the field's values.

What am I doing wrong? Am I misunderstanding how |hash works?

Also, it says "Prefixes the given string", what if you need to protect a integer?


texts: How to add class to ul ol tag in redactor by using formattingAdd

texts:
I try to add a class to tag ul by field Redactor. I have prepered special config file for Redactor. For example in Redactor field a have a created simple list so i select this list and next from formatting option i choose my new created option which should add a class to that ul tag and
unfortunately it not works.

However if i use this option on standard paragraph class is added. So i have not idea what i do wrong.

Below content my config file:

{
  "buttons": ["formatting", "bold", "italic", "unorderedlist", "orderedlist", "link", "html", "fontcolor", "image"],
  "plugins": ["fullscreen", "fontcolor", "alignment"],
  "linkNewTab": true,
  "toolbarFixed": true,
  "formattingAdd": {

    "list-columns-3-each-under": {
      "title": "list-columns-3-each-under",
      "api": "module.block.format",
      "args": {

        "type": "add",

        "class": "my-class-for-list"
      }
    }

  }

}


texts:
Since my hosting provider is blocking mysqldump on its server, I'm trying to do a manual backup of my database in order to import the DB into my test environment.

I'm stuck on the elements to ignore since a manual export on PHPMyAdmin (prod env) and then import to PHPMyAdmin (dev env) environment triggers errors.

Do you guys have any experience in manual backups?

Thanks! :)


texts: Can I set a Commerce order custom field from a plugin

texts:
On a site with Commerce 1, I have set up some custom fields for order related data. I can set them using form inputs like so:

<input type="hidden" name="fields[myCustomField]" value="1">

I'd prefer to set it from a plugin using an even hook.

craft()->on('commerce_orders.onBeforeOrderComplete', function($event) {
    $order = $event->params['order'];
    $order>myCustomField = 3;

}

It fails with a CExeption:

  Property "Craft\Commerce_OrderModel.myCustomField" is not defined.

I can set my field from the form and then read the value from my plugin, so the field is readable, but I am unable to set it. So far, all I can figure out is that the Craft BaseModel strictAttributes parameter is set to true, and the model does not seem to have any attributes set for my field. The BaseModel attempts to set the field value by calling parent::_set(), which is what triggers the CExeption.

Is there any way to set my field from my plugin?


texts: How do I update a Craft website without losing data?

texts:
I have an existing website built with Craft CMS. I made a few changes locally and now I want to update the 'live' website. The problem is that I added a couple of fields and sections but I can't just replace the live database with the one I am currently working with locally because the content in the live database is more up to date and I don't want to override that content.

So how can I get those new fields and sections in the live/production database without losing any data in said database?


texts: {{ entry.postDate|date }} Variable "entry" does not exist

texts:
Might be basic, but not sure where I'm doing wrong. I was trying to display the post date of an article using this code
{{ entry.postDate|date('medium') }}.

But getting the error stating "Variable "entry" does not exist."


texts:
I'm trying to update a user password on save via a custom field (on registration via the back-end - the admin needs to specify a password on registering a user). Is this even possible?

Came across this question How do I change a user's password programmatically in a plugin? and tried using the users.onBeforeSaveUser event to update the $user->newPassword but the user cannot login with the details registered/created.

Any thoughts on above appreciated!


texts: Is it possible to view 'Expired' entrys on the front end?

texts:
I have a site with 10000 events which need to expire once they have happened, the main reason for this is to keep things tidy in the CP.

We need users to view events that they have completed after they have expired.

Is there an easy way to render these entries on the front end, without creating a custom route and changing the URL??

Getting the listing is easy enough:

done: user.eventsDoing.date('<'~ now|date('Y-m-d') ).order('date desc').status('expired')


texts: Is it possible to have lowercase globals?

texts: My question is simple and straightforward. Maybe I am making a mistake but it seems that all the text in a global field is always capital. I want to have 'Eng" in a global plain text field but it outputs "ENG"


texts: Custom fields on a structure or section archive page

texts:
I have a section (or structure, works both) for "events". On the archive template (see image below) I want to add a custom image in the header. The administrator needs to be able to upload the header image.

In a section/structure there is no dedicated page, so I cannot assign custom fields to it. How do I tackle this problem?


texts: Separated DB for each locale in subdomain with no shared Craft installation

texts:
The goal is to have single site (subdomain.domain.dev) with single locale(en_gb) in it and with one craft installation shared with this site only.

I'm not sure if I configured general.php and db.php correctly to get subdomain.domain.dev loaded.

Production steps of What I did:

Set up host to point to subdomain - subdomain.craft.dev

Folders structure:

craft

craft.dev

subdomain.craft.dev
Created database - subdomain_dev
Uploaded necessary files to subdomain folder and edited one line of code

// Tell Craft to serve the subdomain content
define('CRAFT_LOCALE', 'subdomain');
Uploaded en_gb templates to ../craft/templates/en_gb.

I'm not sure, If I also should edit $craftPath to point to templates files for en_gb locale.
Edited general.php

// All environments
'*' => array(),
// Development environment - Locale
'craft.dev' => array(
    'devMode' => true,
    'siteUrl' => array(
        'en' => 'http://craft.dev',
        'en_gb' => 'http://subdomain.craft.dev'
    )
)
);
Edited db.php

// All environments
'*' => array(
    'tablePrefix' => 'craft',
),

// Development environment - Locale
'craft.dev' => array(
    'server' => 'localhost',
    'user' => 'root',
    'password' => '********',
    'database' => 'craft_dev',
    ),
// Development environment - Locale
'subdomain.craft.dev' => array(
    'server' => 'localhost',
    'user' => 'root',
    'password' => '********',
    'database' => 'subdomain_dev',
    )

Locale en_gb was also created from back-end.
When I load the http://subdomain.craft.dev, I get Twig_Error_Runtime saying, that variable doesn't exist.It's like templates in ../craft/templates/en_gb wasn't found?


texts: How to create a new Entry model in Craft 3?

texts:
I want to create a new entry for a section named 'drinks'(having section id= 6). The namespace of the file having this code is namespace putyourlightson\userguide\controllers;.I copied this code from StackExchange. My first line is getting an error(Class 'Craft\EntryModel' not found).

$entry = new \Craft\EntryModel();

$attributes = [
  'section'   => $yourSectionId,
  'entryType' => $yourEntryTypeId,
  'field1'    => 'foo',
  'field2'    => 'bar'
];

$entry->getContent()->setAttributes($attributes);

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

How should you import it?


texts: How long to wait until license modal stops appearing?

texts: I recently setup a pre-production environment of my fully purchased Craft site license, but Craft license management didn't think the sub-domain I was using was "dev-sounding" enough. Now that I've rectified that problem by creating a sub-domain included on CraftCMS's official list and destroying the previous one, how long will I have to wait before my production instance stops complaining about needing a payment for trial licenses?


texts: EVENT_REGISTER_TABLE_ATTRIBUTES not working in Craft 3

texts:
I am developing a plugin to add custom column to entries table for which I am using EVENT_REGISTER_TABLE_ATTRIBUTES and EVENT_SET_TABLE_ATTRIBUTE_HTML and code example is:

Event::on(
    Element::class,
    Element::EVENT_REGISTER_TABLE_ATTRIBUTES,
    function(craft\events\RegisterElementTableAttributesEvent $e) {
        return array(
            'foo' => "Foo",
            'bar' => "Bar",
        );
});
Event::on(
    Entry::class,
    Element::EVENT_SET_TABLE_ATTRIBUTE_HTML,
    function(craft\events\SetElementTableAttributeHtmlEvent $e) {
        if ($e->attribute === 'foo') {
            return 'bar';
        }
});

Unfortunately, its not working. Could anyone please help what I am mistaking here.


texts: Can you get the HTTP status code in twig templates?

texts:
I need a nice way to determine whether I'm on a 200 page. Basically anything other than a status page (404, 500, 403) in twig templates.

I thought I could do something like craft.request.getStatus or craft.request.status but this didn't work.

From looking in the HttpRequestService.php file there doesn't seem to be anything to retrieve this info so I wondered if anyone has achieved something similar.


texts: How to target first or last item in a nav children loop

texts:
I'm trying to use this code:

{% nav category in categories %}

   {{ category.title }}

   {% children %}

   {% if not loop.last %} BLAH {% endif %}

{% endnav %}

It appears that the {% if not loop.last %} conditional doesn't work inside of a {% nav %} tag.

How can I target/style the first and last items in each level of a nav structure?


texts: Is it possible to extend twig with 'Twig_SimpleTest'?

texts:
I was on the Twig StackExchange forum and found an answer that suited my needs.

But I can't for the life of me figure out how to implement this into a Craft CMS Plugin.

I'm familiar with Twig_Function_Method and Twig_Filter_Method, but I can't find anything on Twig_SimpleTest.

Has the option to include "tests" been omitted from Craft CMS?


texts: Enupal PDF plugin: Passing Variable to Template

texts:
I'm using the Enupal PDF plugin and am trying to pass a variable ID into my template that generates the PDF... I'm assuming the following documents how to pass the variable through to the template - (see image):

But what I'm not told is how I should print this out in the pdf template. Outputting {{ foo }} doesn't work.

What am I doing wrong?


texts: Does Craft support a custom authentication backend for Admin?

texts:
Scenario:
I want to use Craft to build a community website for an organisation which uses LDAP and Google Apps. I'd like to users to be able to login to Craft Admin via their existing LDAP account (or via Google Apps OAuth, which is easier).

The ideal workflow would be something like this:
1. John Doe is a member of the community and requests access to the Craft site.
2. Admin user logs into Craft and adds John Doe as a new user with his SSO email address
3. John Doe can then login to Craft using his SSO login details (either via a custom front-end form, or directly via Craft admin).

Looking at the available Craft events & hooks, this doesn't seem possible currently without hacking up the Craft internals.

My question: Is there any way to implement this sort of SSO in a modular fashion in Craft? Or, will it require extensive hacking of Craft internals in a 'brittle' fashion?

Cheers,
Sam.


texts:
The title pretty much says it all.

I'm trying to connect to a RESTful API within Craft templates to pull various showtimes, prices, availability, etc. of a theater. I have my URL endpoints and username & password but have no idea where they need to go in the templates. The API uses Basic Authentication. Everything I'm reading is PHP specific and I'm not quite sure how that translates to Craft/Twig.

I like the Rest plugin by Dukt (https://dukt.net/rest) but it uses OAuth.

Any help/direction would be appreciated.


texts: Creating an active page within a channel

texts:
I need some advise about the best way to achieve this.

My site is set up with a Channel called 'Product' for example.

I then have entries within this section

Product A
Product B
Product C

Only one of these products will be active at once.

All links on the site for 'Product' will need to link to the active product page (A, B or C).

The way I'm thinking of doing this is having a lightswitch on the Product pages to state which is the current (active) one.

I can't get my head around how this might work at the moment so any advise would be much appreciated.


texts:
I use Smart Map for a project, but I have a question for this plugin.

Is it possible group the markers per cluster or I need see other options.

Tks


texts:
We have a client who has quite complex tabular data they need to add to their site. Hitherto they have been preparing these in Excel then pasting in but we are hitting issues with the way Redactor interprets merge table cells.

Short of editing the HTML for each of these via source (quite laborious and cannot really expect to do this each time the client wants to add/udpate a table) is there any way through redactor to add more complex table cell formatting?


texts: How can I prevent CMYK image colours being shifted when importing into Assets?

texts:
When importing CMYK images into Assets the colour of the image can be shifted dramatically. Often giving a washed out look.

How can I prevent this and ensure the image colours are as accurate as possible?


texts:
In Craft Commerce 1, there is documentation on how to re-order adjustments that do similar things.
https://docs.craftcms.com/commerce/v1/adjusters.html#ordering-adjustments

But I don't see any similar documentation for how to do that in Commerce 2.

I have 2 plugins that make adjustments to the Sale price and then Order total, but if run in the wrong order, it doesn't work.

Simple solution is to uninstall the plugins and install them in the correct sequence, but was wondering if there was still a way to force them to run in a certain order.


texts: How do I (also) cycle a class on a Matrix block?

texts:
I think I am doing exactly the same as here but I only get the "even" class at each iteration.

{% for block in entry.articlebody %}

    {% set index0 = loop.index0 %}

    {% switch block.type %}

        {% case 'heading' %}

{{ block.heading }}

        {% case 'text' %}

{{ block.text }}

    {% endswitch %}
{% endfor %}


texts: Passing data back to form on invalid submission

texts:
I currently have a form that is being displayed to the user via a custom route.

The form submits to a controller. The first thing the controller does is populate a custom model and validates it.

If the model fails validation, I want to skip the rest of the controller and pass the model back to the form. What is the best way to do this? I tried using craft()->urlManager->setRouteVariables and a $this->redirect, but the route variable didn't seem to come through, which I imagine is because setRouteVariables isn't supposed to be used like that.


texts: Adjust item stock accordingly to checkout carts

texts:
So in Craft Commerce, we have stock items. What I want is to display items in stock, but adjust it to active checkout charts containing those items.

(only when an active had a checkout or being disband stock must correct itself)

How would it be possible to implement such a thing?


texts: Cannot edit entries after Redactor 2.0.1 upgrade

texts:
I upgraded to Redactor 2.0.1 on Craft Pro 3.0.6, and now I'm getting this error anytime I try to edit an entry that uses Redactor.

InvalidConfigException('Redactor plugin not found: '.$plugin);

I have disabled and re-enabled the plugin to no avail.

Any assistance would be greatly appreciated. I'm unsure how to make it happy, and I haven't found anything in my Google/StackExchange searching.


texts: how to search for entries where a custom field is either not present or is empty

texts:
Some of my entries have the optional plaintext field myCustomField. I want to retrieve all entries except those where myCustomField is filled out.

I can get all entries that have an empty myCustomField

craft.entries({
    myCustomField: ':empty:',
})

but that doesn't include entries that don't have the field myCustomField.


texts: How can I update custom order fields in the frontend

texts:
I am struggling with using additional custom order fields. (Added in the Craft Commerce settings at "order fields", in the field layout manager)

I try to update them like this in the checkout process:

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="text" name="myCustomField" value="Test123">
    ...
    <input type="submit" value="Update Custom Field">
</form>

But in the Order in the CP, the field stays empty. Do I have to use another name for the field, like fields[myCustomField] or whatever?

I can update them in the CP, but not from the front-end...


texts: How to access a digital products information on the products page in Craft Commerce?

texts: I have created a digital product type and a digital product but strangely on the digital products template I can't access any information regarding the product like for example, entry.title. I'm getting a Variable "entry" does not exist. error. Any Ideas?


texts: Imager plugin doesn't generate images in multi-language website

texts:
I upgraded a website from a single to multi-locale site and found out that the images (generated with the Imager plug-in) won't load in the new locale; I get a 404 for every image that the browser tries to load. However, the images do load in the new locale when the entry has been loaded in the original locale first.

It seems that Imager only generates the images when they're requested in the websites original locale; does anyone have an idea how to solve this? Thanks for your help!


texts: How to display a tree view of all assets?

texts:
I like to display a tree-like view of all files in an asset source:

Folder_X

File_A
File_B
Folder_Y

File_C

Folder_Z

...

I know that I can iterate over all assets in a source ({% for file in craft.assets.sourceId('1') %}) but this gives just an alphabetically sorted list of all files. Maybe we need something like the nav-tag.


texts:
The documentation indicates it is possible to add sources for entries like this:

use craft\base\Element;
use craft\elements\Entry;
use craft\events\RegisterElementSourcesEvent;
use yii\base\Event;

Event::on(Entry::class, Element::EVENT_REGISTER_SOURCES, function(RegisterElementSourcesEvent $event) {
    if ($event->context === 'index') {
        $event->sources[] = [
            'heading' => \Craft::t('plugin-handle', 'Statuses'),
        ];

        foreach (Entry::statuses() as $status => $label) {
            $event->sources[] = [
                'key' => 'status:'.$status,
                'label' => $label,
                'criteria' => ['status' => $status]
            ];
        }
    }
});

Just implementing this example alone in a module will indeed add the sources in the left source column, but activating the source options do not present tables of element with the respective status, as expected.

How can I add sources that show entries with a specific status, as well as other criteria and what criteria options are possible to use?


texts: How do I access a custom Asset field within an Assets field?

texts:
I want to setup a custom field to assign a URL for an image.  On the front end I want to output the image and then wrap it in a URL. I've setup a field called 'logoURL' but not sure how to access that data.  What I have isn't working and I've tried several variations.

{% set logo = { width: 175, height: 120, mode: 'fit' } %}

{% for image in entry.logos %}

{% endfor %}


texts: What if two people have the same item in the cart and it is the last in the stock one of those people finishes the purchase, then technically that product is no longer in the inventory that happens there?


texts: Creating a editable table with Element Select in column

texts:
First of all, I'm starting in Craft in general so I'm having a hard time with things that might be basic.

I want to create a editable table with a Element Select in a column. Like:

I already have the possibility to add custom fields, but I don't now how to set up the template.

{{ forms.editableTable({
    id: 'timetable',
    name: 'timetable',
    required: false,
    cols: {
        name: {
            heading: "Name" |t,
            type: "select" |t,
            options: {
                'area-x' : 'Area X',
                'area-y' : 'Area Y',
                'area-z' : 'Area Z',
            }
        },
        artists: {
            heading: "Artists" |t,
            type: "elementSelect" |t,
        }
    },
    rows: ///
}) }}

But of course that doesn't work.

Can anyone light up the way?


texts: GraphQL private schema returning public schema scope

texts:
I am setting up GraphQL on my Craft project, v3.3.16.3
I have a public schema exposing a public entry type, and a private schema exposing a private entry type.
When I switch between them in the GraphQL -> Explore panel, both return the results of the public schema.

See attached screens.

Any suggestions would be much appreciated! Thanks :-)


texts:
I have entries that I would like to sort by 2 fields. First I would like to sort (or group) all of the entries in alphabetical order by a category field (brand), and then within each grouped brand I would like to sort the entries by a number field ascending (size).

I can perform both sorts individually with the syntax below, but I’m having difficulty combining them for a multisort-like function.

 entries|supersort('sortAs', '{ brand.first.title }')
 entries|supersort('sortAs', '{ size }', SORT_NUMERIC)


texts: Apply different classes and styles when in 'live preview' pane

texts:
Is there any way of adding a class onto a page body when it is viewed within the 'live preview' pane?

I can then use this to make things either show or not show.

I want to do this to highlight specific things to content editors that I don't feel are worth highlighting to regular users.

I think I can only do this by hanging rules off a special 'preview only' class.


texts:
I am writing a plugin which has a controller, service and a model. The model represents some fields which will be POST'd and then emailed via the service.

The controller uses an action to populate the model via the $_POST vars, which is exposed to the template for displaying validation errors:

$fields = BusinessLogic_EventBookingFormModel::populateModel($_POST);

if ($fields->validate()) {
    // send the email...
} else {
    craft()->urlManager->setRouteVariables(array(
        'errors' => $fields->getErrors()
    ));
}

I'd like to expose that model to the template before it's populated, I assume via a template variable. What is standard-practise for instantiating and then managing a reference to that model? Where would the instance live? In the service perhaps?