texts: Check for whole cart adjustment and apply line item discount

texts:
I'm writing a custom plugin for a customer that does 2 things.

Uses prices from Pricing Categories. There are 10,000 digital products, so adjusting prices for large quantities is cumbersome on a per-product basis.
Uses a Stock Photo model system of PrePay. Purchase a set amount of credits like $100, and get 10% off the products.

I have successfully completed the first step by using the EVENT_POPULATE_LINE_ITEM listener. The following works perfectly.

Upon consultation with the wonderful Michael Rog, I am taking a different apporoach to this project.

Create a function on the backend that upon an product entry save, assign the price from the category. This will assign the price in the CP, rather than doing any line item editing and cart manipulation on the front end.
I will be creating my own adjuster that will fire after a Gift Voucher has been added to the cart that will then apply the sale percentage to the line item in addition to the whole voucher process.

I'll post my update when successful.


texts: Check if a FieldHandle exists in Module without throwing 'Invalid field handle' exceptions

texts:
I've been pulling my hair out trying to work this one out.
I'm building a module to auto-populate a super-table on EVENT_BEFORE_SAVE, the module works exactly the way I want it to, everything seems to be working fine.
Except Craft throws a "Invalid field handle:" exception if the custom field doesn't exist on that entry.
I've tried to check if the field exists with a few different methods, but anything that directly references the fieldhandle seems to throw an exception.
What's the proper way of checking if a field exists and running the code if it does?


texts: asset.getUrl() not correct: missing subfolder directory

texts:
I created a new asset source/folder called "my-assets".

It has an entry in the DB in "craft_assetsources" with the id=10, path="my_base_folder/assets/my-assets/" and url="/assets/my-assets/",

plus an entry in the "craft_assetfolders" with the id=27, sourceID=10 and name="my-assets".

Then I've created a subfolder called "my-images", which only has an entry in "craft_assetfolders" with id=28, sourceID=10 and path="my-images/".

When I use the myImage.asset.getUrl() on an image from that subfolder, I get the url "/assets/my-assets/myImage.jpg" instead of "/assets/my-assets/my-images/myImage.jpg", which obviously results in the image not being found.

Any ideas why this happens and especially how to fix it?

I appreciate any help!


texts: _entry.twig isn't reading css while index does

texts:
This is the template im using and the index of the file is taking the css and printing it nicely however, the _entry.twig is only loading text, please check out the screenshots.

Below is the index of directory which loads css completely fine.

And one after is the _entry.twig which isn't taking any CSS.

Thanks!


texts:
I'm totally new to Craft (having previously developed on Silverstripe) but have read through the basic docs, have a local version installed and have set-up a HelloWorld plugin.

What I am now wondering is how to produce a flexible layout that provides editors with "drag & drop" components each in, for instance, Bootstrap style rows.

For instance a page layout that allows components for
- an advert
- a list of customers
- a block of custom text with a custom image etc. etc.
(e.g. https://www.salesforceiq.com/ which is Craft driven I believe).

The editor provides the relevant content for each custom component and can drag & drop them around to change their order as required & that order is reflected on the front end.  And those types of pages can appear anywhere in the site structure.

I'm guessing the answer is a section with a Matrix field, but I'm struggling to make the leap on how that can allow it to call on a set of custom fields that each call on custom templates?

Any help greatly appreciated!


texts: Yiic migrate command not working (memory exhausted)

texts:
I'm trying to launch a basic "yiic migrate create BasicMe MyPlugin"
But every time the memory gets exhausted, whatever memory_limit I set (I even tried 8Gb).

Fatal error: Allowed memory size of 3279945728 bytes exhausted (tried to allocate 72 bytes) in /path/to/craft/app/framework/base/CComponent.php on line 266

Any idea what's causing it ?

Nicolas


texts: Is this syntax correct for Sprout Redirects Regex 301 Rule to redirect Wordpress sniffers?

texts:
I am trying to add a 301 rule specifically for all the WordPress sniffers on my site.

Old URL

^\/(wordpress|wp|blog\/wp-admin|blog\/wp-login|wp-login|wp-admin|wp-config|wp-content|wp-includes|(.*)\.exe)

New URL

https://wordpress.com/$1

I used this rule previously using Retour on a site with success

It doesn't seem to work however using Sprout Redirects. It instead still gives a 404. Is there some syntax I'm missing or is this type of regex possible with Sprout Redirects?


texts: Asset indexing failing with large asset source

texts:
I've got an asset folder where i need to bring over about 20Gb of assets, obviously trying to update asset indexes from the Craft Cpanel is causing a serious failure.

Other than adding my assets in smaller chunks is there any other option to make it less memory intensive?

If the assets were on S3 rather than local, would it be less intense?


texts:
does anyone know if there is a flag, accessible at template level, that indicates whether the "System Status" lightswitch in Settings -> General menu is on or off? (I'm thinking something similar to craft.config.devMode)

I tried craft.config.isSystemOn but it did not work since the setting is not defined in the general.php config but rather via the user interface.

Just to give some context, I'd like to add extra items to the template for logged in admin users to see on the website only when system status is set to off (like a warning bar).

Thanks in advance!
Daniel


texts: How do I make use of the order fields In Commerce?

texts:
Building on top of the Commerce Example Templates. I've made an order field called 'Customer Reference'. I'm submitting data like this:

<form class="shopForm" method="POST">
<input type="hidden" name="action" value="commerce/cart/updateCart">

    Your Reference: {{cart.customerReference}}
    <input type="text" name="fields[customerReference]" value="">

<input class="btn btn-outline" type="submit" value="Update Reference">

This code seems to work ok. But after updating the cart the data doesn't seem to be saved, it doesn't show up in the Commerce back end. I'm also not able to be display the data later on in the ordering process, on the receipt for example.

I'm using this to display the data from the field:

{{cart.customerReference}} or {{order.customerReference}}

Can somebody tell me, possibly with some examples, how to properly submit and retrieve the content for custom order fields?

This is related to: How can I update custom order fields in the frontend

Working with: mamp


texts:
Is there a best practice for a paging based on the years of entries (instead of page numbers)?

Example:
I have 3 records with post dates 2019-01-01 2018-01-01 and 2016-01-01. So my paging should look like this:

2019 | 2018 | 2016

It is easy to fetch the needed info with a raw query like:

{% set pagingYears = craft.query()
    .select('DISTINCT YEAR(postDate)')
    .from('entries')
    .where({'sectionId': 1})
    .column()
%}

But does craft provide some components or a better way to solve such a problem?


texts: The file does not appear to be an image. Bug?

texts:
I've installed the latest ImageMagick on my ubuntu 14 server. If I force imageDriver to use 'imagick', I can only upload Gif images. And if I force it to use GD, I can upload all images but only static gif images.

The images are not changed in any programs.

It's important for me to have both options. Any ideas what this issues can be? I use php 7.0

Upload failed for background.jpg. The error message was: “Error uploading the file: The file “/var/www/html/craftcms/craft/storage/runtime/temp/assets57cb93709cf445.74590720.jpg” does not appear to be an image.”


texts: Using Craft Prune - convert JSON Array of Objects to simple array

texts:
I am using the Craft Prune plugin (https://github.com/mattstauffer/craftcms-prune) to pull out a JSON array of entries from a section of my site with the aim of integrating the data into a typeahead search field as autocomplete data.

The problem I seem to be having is that the JSON array structure needs to be simplified for use as a datasource with typeahead.

So the current JSON data structure is:

[{"title":"Entry One Title"}, {"title":"Entry Two Title"}, {"title":"Entry Three Title"}]

What I actually need the structure to be is:

["Entry One Title", "Entry Two Title", "Entry Three Title"]

I have already tried using the jQuery $.each() function and the jQuery $.map() function but they both simply return an array of objects not a simple JS array.

Any help appreciated.


texts: How to get values into twig template for fields of type Matrix in Craft CMS 2?

texts:
CMS: Craft CMS 2
In my admin panel I have globals set called X (under "Globals" from the sidebar and defined in craft_globalsets in the db from Global->Settings->New global set).
A field for the field layout for the global set is defined by using as Content a Field type Y of Matrix type with several plain texts fields A,B,C,...
How do I check/show such fields' values (A, B, C, ...) in twig?
What I have tried: I see that in the other parts of the code the handle defined in craft_globalsets (or equivalently in Settings->Globals) is used to fetch the globals' field value
e.g. for Globals -> set 'K' (handle in craft_globalsets: kHandle) there are several plaintext inputs and such are accessed in twig as:

{{ kHandle.firstField}}

and in fact it works - but when I od the same with set X

{{xHandle.firstFiledInTheMatrix}}

it's null
I have also tried to do

{%  set matrixFields = craft.fields.getFieldByHandle('Y') %}
{{  matrixFields }}

but this returned only the field name.
Perhaps I should do something like {{ xHandle.firstFiledInTheMatrix.getMatrixContent | getFieldContent }} and a for loop on this? (currently guessing the function names here)


texts:
I just updated the Charge 2 plugin to latest (version 2.2.1) and when I try to create a new coupon, I get this error:

CDbException
CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General
error: 1366 Incorrect integer value: '' for column 'amountOff' at row 1.

I've tried various scenarios; entering a fixed amount for the coupon, a percentage amount as well as trying various payment types, and it gives the same error above, regardless of whether I choose a fixed or percentage amount.

Has anyone else ran into this issue and if so, have you figured out a solution for it?

I also tried reverting back to previous versions of the plugin, and I get the same error. That last version that worked with coupons was Charge 2.1.8.

I'm running Craft 2.6.2997, PHP 7.1, MySQL 5.7.2.


texts: Is there a way to prompt for confirmation in cp?

texts:
I have a custom plugin that checks for assets filename, and I'd like to prompt for confirmation like in the example below.
Is there a way to do that in Cp? If user clicks No then $event->isValid = false;
    Event::on(
        Asset::class,
        Asset::EVENT_BEFORE_SAVE,
        function(ModelEvent $event) {
            if ($event->isNew && $event->sender instanceof Asset) {
                $result = self::$plugin->checknameService->matchName($event->sender->filename);
                if (!empty($result)) {
                    // Prompt: "I don't like this asset name, are you sure? Yes / No"
                }
            }
        }
    );


texts: How to only show translated fields in an additional locale?

texts:
I'm using the localisation feature for the first time, and I'm not sure if I understand its rationale.

On a site with entries that have multiple fields, I only have the main body text set up for translation. If I switch to the secondary language in the control panel, all fields are displayed and pre-populated with the contents of the main language (but according to my understanding, they're just pointers and not duplicated in the database).

Why are the non-translateable fields not set to disabled, marked up otherwise, or even hidden completely? Is there a way to do so?

(My concern is that my client can't identify which fields need to be translated, and hereby overwrites a non-translateable field with the secondary language.)


texts:
This is very basic as I am new to Craft CMS, but I created a Plain Text field in the Homepage section labeled "Tagline". When I enter the Twig code {{ entry.tagline }} into the index.html template, I get the error that the variable "entry" does not exist.

My index.html is at the root of the public folder.


texts:
I have come across an issue whilst using the Retour plugin for Craft similar to the question raised here but this is a redirect with a URL using the .htm extension and not .php.

Any ideas why this would not work?

Thanks


texts: Which section type for Craft Commerce customer account pages

texts:
I looking for suggestions for customer account pages.Something like;

account
 account/addresses
 account/my-orders
    account/orders/order-5566
    account/orders/order-5567

Which section type should i use Structure, Channels or Singles? Or just use folder/file templating structure?

I know Stackexchange is not a place for open ended questions but couldn't find any good example on this.


texts: Craft storage dir as linked in capistrano

texts:
I'm having some issues with my install of craft on a staging server.

I'm deploying using Capistrano, and (perhaps wrongly) added craft/storage to linked_dirs (to share between deployments). Since doing that, things have not been going so well with my installation. I keep get "No response" screen in the browser, (Error code: ERR_EMPTY_RESPONSE). I also get "unknown error occurred" messages when browsing round the admin doing normal things like updating entries etc.

The only consistent error is this one:

2015/03/26 17:33:53 [error] [exception.Craft\HttpException.503] exception 'Craft\HttpException' in /var/www/50th/releases/20150326171328/craft/app/etc/web/WebApp.php:916
Stack trace:
#0 /var/www/50th/releases/20150326171328/craft/app/etc/web/WebApp.php(230): Craft\WebApp->_enforceSystemStatusPermissions()
#1 /var/www/50th/releases/20150326171328/craft/app/framework/base/CApplication.php(180): Craft\WebApp->processRequest()
#2 /var/www/50th/releases/20150326171328/craft/app/index.php(62): CApplication->run()
#3 /var/www/50th/releases/20150326171328/public/index.php(19): require_once('/var/www/50th/r...')
#4 {main}
REQUEST_URI=/
---
2015/03/26 17:33:53 [error] [application]

It's worth noting that the site is in offline-mode.

Any ideas?!

Update:
I've found a consistent error message when trying to access "/admin/users":
[DOMAINNAME...]/index.php/admin/actions/elementIndex/getElements net::ERR_EMPTY_RESPONSE

Is being returned by jQuery trying to access elements. Does this help at all?


texts: Using a Sprout Form within a Sprout Form?

texts:
I'm creating a website where members have a form of questions to fill in each day. But within this form is a another set of questions that are always the same each day, but will have different answers in each day (it's like a diary entry, but built up of various fields).

Is there a way in Sprout Forms for a form to be almost "embedded" in others? So that if the fields in the embedded form are changed they then change across all the parent forms it is included in, if that makes sense?

The only way I can think to do it at present is create a form with 2 tabs: main and diary. The main tab will contain specific fields for that day, the diary tab will have the set questions that are asked each day. And then I do a "save as" to duplicate the diary fields into another form and change those in the main tab. Issue is that if the diary structure ever gets changed / updated I would have to manually do this perhaps 30 or so times.


texts: How to immediately redirect to an entry after creating the new entry from a frontend form?

texts:
I'm using a frontend form to create an entry with {{ actionInput('entries/save-entry') }} and would like to be able to use this entry immediately upon redirecting from the submit. From the docs I see that the redirectInput() function only accepts a url string. Is it possible to get my hands on the newly created entry's id in order to use it in the redirect?
For context, I have a page with a user-operated form which, when submitted, creates an entry that represents the customer's order. And upon submission I want to immediately head to a review page where it displays the new order's details back to them. Is there a better way to go about this flow? The only thing I can think to do is use a hidden field to set a unique hash on the slug which I also use in the url put in the redirect.


texts: Seomatic - disable tag manager from inside template

texts:
I am using Seomatic and i want to conditionally render google tag manager trancking code - or not.

How do I disable it using some Twig template code?


texts: Sprout Email: "Unable to save recipient."

texts:
Craft 2.5.2754, Sprout Email 2.01, fresh plugin install.

In attempting to use the Recipients feature, I created a new group (Contact Form Recipients) and hit the Add Recipient button. I filled out the email address, first, and last names, but it keeps saying "Unable to save recipient."

The error log says: Craft\SproutEmail_DefaultMailerRecipientModel->recipientLists failed validation: Recipient Lists cannot be blank.

I added a few more lists to be safe; no luck.

Is it possible I'm missing something, or is there a recommended fix or workaround for this?

Thanks for your help!


texts: Redirect to Browser Language and to Site. All websites share the same files

texts:
I have a multisite and multilanguage setup (craft 3).
SiteADe => siteA.com/de
SiteAFr => siteA.com/fr
SiteBDe => siteB.com/de (primary site)
SiteBFr => siteB.com/fr
etc.
ALL sites have a language identifier.
On my server I configured each website to the same directory and files.
So there's only one .env file and general.php for all websites.
The first structure entry of each website has "__home__" as slug.
All sites should be redirected to their language identifier.
e.g. siteA.com should be redirected to siteA.com/<browserlanguage>
Problem with this setup:
Everything works as expected as long as the language identifier is in the URL.
Problem begins if there's no language identifier in the URL:
Craft will only work properly on the primary site.
E.g. a sitemap.xml file will always be redirected to the primary site.
404 Errors are only displayed on the primary site. e.g. siteA.com/daksdf
I've managed to get around this by placing some hacky twig code within the __home__ template.
Anyways: I suspect that I'm taking the wrong approach on this.
How would I best setup my (web)sites?
And how would I forward them to  /<browserlanguage>?
Any help appreciated!
Stefan


texts: How can I get cookies that were set in javascript from a twig template? [NEW]

texts:
This question was already asked a few years ago, and the way of doing it was through a plugin. I was wondering if there is a way of doing it just using Craft and Twig.

I set up a cookie using JavaScript, and I want to read it with Craft. Is this possible?


texts: Creating partials outside of the templates folder

texts:
I'm interested in building a highly modular Craft site in which my folder structure might look something like this:

- craft/
- modules/
  - hero-banner/
      index.html
      scripts.js
      styles.css
  - carousel/
      index.html
      scripts.js
      styles.css
- templates/
    404.html
    index.html
    _layout.html
index.php
robots.txt
.htaccess

An example of what hero-banner/index.html would look like:

{{title}}

{{subtitle}}

An example of how you'd use this in a Craft template like templates/index.html:

{{
  craft.componentUI.run('hero-banner/index', {
    title: 'Welcome to my site!',
    subtitle: 'This is an intro paragraph that has a bit more detail about this site.',
    image: 'http://dummyimage.com/800x350/000000/555555'
  })
}}

A couple reasons I'd like to do something like this:

To create a parity between a style guide and the live site. This way a change to hero-banner/index.html would be reflected in the style guide and the live site. I understand a partial can do the same thing, but I'd prefer something like this because...
We can encapsulate a module's HTML, CSS and JavaScript in one place. Doing this will allow us to utilize Git or npm to manage these modules individually if we'd like to use them on other sites. It also makes locating a module's assets much easier since they're centrally located rather than being in 3 different folders.

I've found a way to reference template files outside the standard templates/ directory to make this work. So I know this sort of setup can work.

However, my question is what problems could arise from this type of setup? Do I need to be concerned about performance/security/something else entirely?

Edit: Just for further clarification, I'm not looking to serve my CSS and JS through Craft. I want to keep my CSS and JS as-is, but wondered if I could call the modules from those directories (outside of the normal Craft templates).


texts:
I am using Michael Rog's Calendar add-on with these params:

{% switch craft.request.getSegment(2) %}
    {% case '' %}
        {% set thisCalendar  = '2,3' %}
        {% set calendarTitle = 'Full Calendar' %}
    {% case 'mts' %}
        {% set thisCalendar  = '2' %}
        {% set calendarTitle = 'MTS Calendar' %}
    {% case 'day-school' %}
        {% set thisCalendar  = '3' %}
        {% set calendarTitle = 'Day School Calendar' %}
{% endswitch %}

{% set calendarParams = {
    dateRangeStart: 'today',
    dateRangeEnd: '+36 months',
    calendarId: thisCalendar
    } %}

The individual calendars are working and showing the correct entries but without a segment 2 I am only getting the events from Calendar ID 2 but not from ID 3.

If I do this:

    {% case '' %}
        {% set thisCalendar  = '3,2' %}

I get events from Calendar ID 3 but not from ID 2.

How do I get events from all calendars? Is comma separated the correct syntax? Should this be working?


texts: Can I disable languages from the General Config Settings?

texts:
I started to develop my new Craft site in two languages (French & German). Once done here, I have to put the website online temporarily in one of these two languages (French).

So I turned off all sections and entries to disable the language (German) but:

This was tedious and time consuming to do this manually via the CP
domain.com/de/ now redirects to the homepage with empty content instead of redirect to the 404 page

Questions :

Is there a faster and safer way to temporarily disable a website language with the General Config Settings?
Is it possible to disable some website languages depending on the environment and / or if devMode is enabled?


texts: How to assign a URL to only one slide in a template using Matrix?

texts:
So I am using the matrix field to enable uploading of images onto a slideshow for the homepage section. My goal is to have one of the images link to another URL when you click on it. Basic stuff when using plain HTML, but I have it setup like this in Twig:

{% for block in entry.information %}
{% if block.type == "images" %}
   {% set image = block.image.first() %}
       {% if image %}

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

This code runs fine and my slideshow images are all displayed using just one loop.

The problem is, all my slides are having an anchor field activated. I only want one of the slides to have a link to a URL, however, in the future I may want to add links to other slides so I need something that is also dynamic enough to support this.

My whole entire approach may be wrong and I might need to use a completely different approach... assistance is greatly appreciated.


texts: Why is Redactor cutting off Headings after Heading 2?

texts:
my client sees the attached screen in the editing window. it seems that Redactor is cutting off headings after Heading 2. They are using Chrome.
ideas?


texts:
In CP, there is the widget called "Recent Entries". You can pull out entries from your sections, limit a count of entries.

I'm building a plugin that has very similar widget to recent entries widget.

THE GOAL

Filter entries by date range within widget.

I was only able to set a fixed date range within widget's class ...

// To get entries from a specific date range
$criteria->postDate = array('and', '> 2016-06-10 23:59:59', '< 2016-06-30 00:00:00');


texts: Plugin migration - calling services help

texts:
In my Craft 2 plugin my initial init function looked like:

public function init()
{
    parent::init();

    if(!extension_loaded('imagick')) {
        PdfThumbnailerPlugin::log("imagick library not found - cannot make pdf thumbnails" , LogLevel::Warning);
        return;
    }

    craft()->on('entries.saveEntry', function(Event $event) {
         craft()->pdfThumbnailer_saveEntry->setThumb($event);
    });

    craft()->on('assets.saveAsset', function(Event $event) {
        PdfThumbnailerPlugin::log("on save asset");
        craft()->pdfThumbnailer_saveAsset->checkAsset($event);
    });

}

I cannot understand (due to lack of devchops) or find an example of how to call my functions (which were in service files) in Craft3.

I can see the constants used in the new style 'listener' but have no idea what or where these are referenced in the v3 docs.

    // Register our site routes
    Event::on(
        UrlManager::class,
        UrlManager::EVENT_REGISTER_SITE_URL_RULES,
        function (RegisterUrlRulesEvent $event) {
            $event->rules['siteActionTrigger1'] = 'pdfthumbnailer/save-entry';
            $event->rules['siteActionTrigger2'] = 'pdfthumbnailer/save-asset';
        }
    );

My plugin in craft 2 would create a thumbnail from the first page of a PDF asset.

UPDATE:
SO i eventually made some progress with :

Pdfthumbnailer::$plugin->SaveEntry->setThumb($event);

Except this kept saying it could not find service method:

Getting unknown property: joomkit\pdfthumbnailer\Pdfthumbnailer::SaveEntry

It turns out that the method 'SaveEntry' only was found when named 'saveEntry'. Why would this be the case? (excuse pun)


texts: Twig "Is defined" throwing error on matrix row EntryModel property

texts:
When checking if a matrix block property is defined, I'm getting an error:

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

The line that is throwing this error is specifically checking if that property is defined.

{% if block.contentSource is defined %}
    {# Stuff and things #}
{% endif %}

-- Or --

{% set theThing = block.contentSource ?? "fallback" %}

Am I expecting the "is defined" check to be smarter than it actually is? I can't see an example of this in the matrix field or craft twig/templating docs.

Thanks :)


texts: Convert checkbox values from an array to a string

texts:
I have a front end form with multiple checkboxes. Is it possible to convert the checkbox values from an array to a string before it's submitted to the database?

I want to save the checkbox values into a PlainText Craft field in the database.

If I try to submit the front end form checkbox values into a PlainText field currently, I get the error: trim() expects parameter 1 to be string, array given

It looks like perhaps using the join or merge filter may accomplish this but I'm not sure.


texts:
It seems that something like

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

works in a Controller so that {{ calupdateResponse }} has a value, but it doesn't work in a function in a plugin's Services (no error, just no values show up in twig).

I'm wishing that a single function in Services can output a number of variables to twig for templating. What is the most straightforward way?   Is it necessary to create a function for each one in PluginVariables.php?  Then I have many functions instead of just one.  This is for a CP page, if that makes a difference.

On a related note, is it possible for twig to instantiate a plugin's model, with access to all it's properties?

Thank you!


texts: How do I make display a specific post based on what the day of the week it is?

texts:
I can do it in PHP, but I'm having trouble converting it to twig.

Here's the PHP:

$day = date("l");
date_default_timezone_set('America/Chicago');

if ($day == "Saturday")
{
    echo "
SATURDAY SPECIALS
";
    echo "

";
    echo "
FOOD
";
    echo "
Half priced desserts
";
    echo "
DRINK
";
    echo "
$1 off Seasonal Pints
";

}
elseif ($day == "Sunday")
{
    echo "
GAMEDAY SPECIALS
";
    echo "

";
    echo "
FOOD
";
    echo "
One Free Kids Meal w/ each Adult Meal
";
    echo "
DRINK
";
    echo "
$3 on ALL Bottled Beers
";    }
elseif ($day == "Monday")
{
    echo "
MONDAY SPECIALS
";
    echo "

";
    echo "
FOOD
";
    echo "
$1 Tenders
(5 piece min.)
";
    echo "
DRINK
";
    echo "
$2 Lonestar Pints
";  }
elseif ($day == "Tuesday")
{
    echo "
TUESDAY SPECIALS
";
    echo "

";
    echo "
FOOD
";
    echo "
$.50 Boneless Wings
 (10 piece min.)
";
    echo "
DRINK
";
    echo "
$4 Margaritas
";  }
elseif ($day == "Wednesday")
{
    echo "
WEDNESDAY SPECIALS
";
    echo "

";
    echo "
FOOD
";
    echo "
Half price APPs!
";
    echo "
DRINK
";
    echo "
$3 shots of Jameson & Jager
";
}
elseif ($day == "Thursday")
{
    echo "
THURSDAY SPECIALS
";
    echo "

";
    echo "
FOOD
";
    echo "
2 for $10 Wingzup Burgers
";
    echo "
DRINK
";
    echo "
$3 Draft Beers all day
";
}
else
{
    echo "
FRIDAY SPECIALS
";
    echo "

";
    echo "
FOOD
";
    echo "
$2 Chili Pies
";
    echo "
DRINK
";
    echo "
$10 Pitchers (Bud Lt./Ziegenbock/Lone Star)
";
}


texts: What's the template command to print available tokens?

texts: I'm trying to dump a list of available template tokens, and their contents. There's a command that's available in dev mode, but I haven't found it's documentation.


texts: Trouble loading custom element action (menu option)

texts:
How do you load a custom element action using getAvailableActions inside my Element Type class?

public function getAvailableActions($source = null)
{
    $customAction = craft()->elements->getAction('Custom');

    $customAction->setParams(array(
        'label' => Craft::t('Custom'),
    ));

    $actions[] = $customAction;
}

The above renders a PHP error PHP Fatal error: Call to a member function setParams() on a non-object

PluginName_CustomElementAction is my file inside the elementactions folder, inside my plugin. Which is copied directly from https://craftcms.com/docs/plugins/element-actions

Here's what it looks like:

namespace Craft;
class PluginName_CustomElementAction extends BaseElementAction
{
    public function getName()
    {
        return Craft::t('Custom');
    }

    public function isDestructive()
    {
        return true;
    }

    public function performAction(ElementCriteriaModel $criteria)
    {
        // Remove all the ingredients from the selected elements
        $elements = $criteria->find();

        foreach ($elements as $element)
        {
            craft()->cocktailRecipes->removeAllIngredientsFromElement($element);
        }

        // Success!
        $this->setMessage(Craft::t('Ingredients removed successfully.'));
        return true;
    }
}

What is wrong with my getAvailableActions object?


texts: How to display itemCount using the Shortlist plugin?

texts:
I am using the Shortlist plugin as a rating system throughout the site and need to display the numeral for the total, with a very simple conditional.

{% set item = craft.shortlist.item('favourites') %}

{% if craft.shortlist.itemCount > 0 %}
    **{{ number }}**<i class="fa fa-large fa-heartbeat">
{% else %}
    <i class="fa fa-large fa-heart-o">
{% endif %}

I have tried {{ item }}, {{ count }}, {{ itemCount }}, but am unable to display a numeral.

Any suggestions?


texts: Creating an .txt file for every entry dynamically

texts:
I'm looking to create a .txt file with table field data taken from an entry on the fly. All entries would have their own designated files. It's for video chapters with JW Player. They ask for a .vtt file but with testing a .txt seems to work.

I've had a good search but can't seem to find much. I guess the worst case scenario is uploading them via FTP, but preferably not! Thanks.


texts: How can I group entries based on a dateTime field?

texts:
I am getting all entries from a section like this:

// get the parent entry.
{% set author = craft.entries.section('mySection').authorId(currentUser.id).first() %}

// get the child entries from the parent.
{% set entires = craft.entries({
    'section': 'mySection',
    'level': 2,
    'descendantOf': author.id
 })%}

// myDate is a dateTime filed (yyyy-mm-dd)

{% for year, entry in entries|group('myDate') %}

{{ year|date('Y') }}

                {% for entry in entries %}
                    {% if attempt.myDate|date('Y') == year|date('Y') %}

{{ entry.myDate }} > {{ entry.type.name }} - {{ entry.foo }}

                    {% endif %}
                {% endfor %}

        {% endfor %}

What I have is close, however, it's outputting multiple years. For example,

2016
  [entry]

2016
  [entry]

2015
  [entry]

 ...

I'm trying to group all of the child entries by year. For example, if I have 3 entires with the same year (2016) I am trying to show:

2016
  [entry]
  [entry]
  [entry]

2015
  [entry]

2014
  [entry]
  [entry]

...

Thank you for any suggestions!


texts: SuperSort Matrix Block sort by Year / Month / Now Data

texts:
{% set allCVs = entry.profileCv.all() %}
      {% set cvEntries = [] %}

      {% for item in allCVs %}
        {% set fromMonth = item.fromMonth.value %}
        {% set fromYear = item.fromYear %}
        {% set toMonth = item.untilToday ? now|date('n') : item.toMonth.value %}
        {% set toYear = item.untilToday ? now|date('Y') : item.toYear %}
        {% set fromMonth = fromMonth|length == 1 ? '0' ~ fromMonth : fromMonth %}
        {% set toMonth = toMonth|length == 1 ? '0' ~ toMonth : toMonth %}
        {% set cvEntries = cvEntries|merge([{
        sortKey: toYear|default(fromYear) ~ '.' ~ toMonth|default(fromMonth) ~ '-' ~ fromYear ~ '.' ~ fromMonth,
        fromMonth: fromMonth,
        fromYear: fromYear,
        toMonth: toMonth,
        toYear: item.untilToday ? now|date('Y') : item.toYear,
        type: item.experienceType,
        label: item.label,
        untilToday: item.untilToday
        }]) %}
      {% endfor %}

      {% for item in cvEntries|supersort('sortAs', '{sortKey}') %}
        {% include 'profile/_profile-cv-row' with {
        from: {
        month: item.fromMonth,
        year: item.fromYear
        },
        to: {
        month: item.toMonth,
        year: item.toYear
        },
        untilToday: item.untilToday|default(0),
        type: item.experienceType,
        label: item.label,
        description: item.description,
        trainer: item.trainer,
        certificationTitle: item.certification.one().title is defined ? item.certification.one().title : 'title',
        certificationDescription: item.certification.one().certificationDescription is defined ? item.certification.one().certificationDescription : 'description',
        } %}
      {% endfor %}

So what i want to do is to let supertsort sort my matrix blocks depending on the the data from

"sortKey: toYear|default(fromYear) ~ '.' ~ toMonth|default(fromMonth) ~ '-' ~ fromYear ~ '.' ~ fromMonth,"

But i get the errors:

Key "experienceType" for array with keys "sortKey, fromMonth, fromYear, toMonth, toYear, type, label, untilToday" does not exist.

Key "description" for array with keys "sortKey, fromMonth, fromYear, toMonth, toYear, type, label, untilToday" does not exist.

Key "trainer" for array with keys "sortKey, fromMonth, fromYear, toMonth, toYear, type, label, untilToday" does not exist.

If i delete all this 3 from my second loop, there is no error anymore, but of course missing data in the frontend.

Any idea whats wrong?


texts: How to set a different URL format for each entry type of a section?

texts:
Is there any way to set a different url format for each entry type of a section?

I have an entry type "image" on which I will be using the Randomm plugin by Fred Carlsen to generate random strings for the URLs. Something like mysite.com/image/324739483. So I have to set the URL format to image/{customFieldHandle}.

But I also have an entry type "articles" and I'd like to add the actual article name in the URL, like mysite.com/articles/some-article-name.


texts:
I'm trying to output an amform in a template that has been selected from a Form field. From the amform docs, it says:

{{ craft.amForms.displayForm('formHandle') }}

My matrix fieldname is called myFormField:

so:

{{ craft.amForms.displayForm('{{block.myFormField}}') }}

But it doesn't look like craft is parsing {{block.myFormField}}:

No form exists with the handle “{{block.myFormField}}”.

Any thoughts?


texts: Entry URI format with postDate not working

texts: I have a News channel that's looped on an 'News Index' template. Each news entry is linked to its respective link via {{ entry.url }}. In my News channel settings, I have the entry URI format to be news/{postDate.year}/{slug}. However, the {{ entry.url }} link goes to news/{slug}. I assumed that if you set the URI format in the channel settings, it would create entry URLs based on the specified URI format. But that doesn't seem to be working. Can someone let me know where I'm going awry?


texts: Does Craft Commerce support multi-channel fulfillment and inventory?

texts: I have a client with several retail locations. They would like a single unified website for the chain, and many of the products will be the same at each location, but each location will need to handle its own orders, including fulfillment and inventory. Users should only have access to orders that pertain to their location (similar to how sections can be limited to certain users). Is there a native way to do this with Craft Commerce, or a plugin that would achieve the same thing?


texts:
Folks:

I've got an e-commerce site that I'm upgrading. I've upgraded to Craft 3 and can reach the CP and the home page.

This site is tightly integrated with Commerce 1. When I visit the plug-in page, Commerce is listed but "missing". I've attempted to claim the license (using the license number listed on the plug-ins page) but the license number is not recognized.

Do I have any options other than purchasing a complete new license? Is there a way to use Commerce 1 with Craft 3?


texts: How can you filter entries in the CP by Author? I assumed entering something like author:tdavis (where tdavis is my username) would do it, but no results returned. I also tried substituting id for username.


texts: Fetch the three entries before, and after, a given Structure entry, with wrapping

texts:
For a given structure entry, I need to return the previous three, and the next three entries as one array. But if the given entry is the last in the structure, I need the "next three" to wrap around and select the first three entries, if that makes sense.

The given structure entry should not be included the results.

Does anyone know how I can achive this: all my efforts so far have failed or are far too complex.


texts: Login Modal - How to handle incorrect password / credentials?

texts:
I'm developing a site in Craft 2, using a modal to display the login form. The modal can be seen by clicking the Login button at top right.

I'm essentially using the form as outlined in the Craft 2 docs here. But it's not set up to work properly with a modal behavior. Currently, if a user types the wrong password credentials, the form still executes, refreshing to the homepage. It's only when the user once again clicks the "login" button that the modal is once again revealed, now showing the error message.

How might I check whether the user's credentials are valid before submitting the form? If credentials are incorrect, I'd like to prevent execution of the form and keep the modal on screen for the user to try again.

Thanks


texts:
Struggling a bit here - have created a custom plugin where I want to validate form submission against a predefined model before saving to the database. All pretty straightforward so far …

However, if I try to use native (Yii 2) validation then a record is saved regardless of whether it is valid or not. For example, if I set the model rules as follows:

public function rules()
    {
        return [
            [['formName'], 'required'],
            [['formName'], 'string', 'min' => 1, 'max' => 255, 'skipOnEmpty' => false]
        ];
    }

The record is saved, even if $model->formName is empty. For example, see the following Controller code:

public function actionUpdate()
    {
        $this->requirePostRequest();
        $request = Craft::$app->getRequest();
        $site = Craft::$app->getSites()->getCurrentSite();

        $formName = $request->getBodyParam('formName');
        $formId = $request->getBodyParam('formId');

        // get ID (if exists)

        if ($formId) {
            $formRecord = FormRecord::find()
            ->where(['id'=>$formId])->one();
            // if count == null return false
        } else {
            $formRecord = new FormRecord;
        }

        $formRecord->formName = $formName;
        $formRecord->siteId = $site->id;
        if ($formRecord->validate()) {
        …

The code will always validate - even if the formName is empty.
This seems a bit crazy to me - am I misunderstanding something about Yii validation rules here?

Help/thoughts appreciated,

Cole


texts:
I've been trying to get the homepage to show up in the navigation...

What I'd like to display is the following...

    About

    Schedule

    Media

    Contact

The following works to create the last 3 pages, but the homepage (about) does not seem to create.

  {% set entries = craft.entries.section('page').find() %}
  {% nav navItem in entries %}

    {{ navItem.title }}

  {% endnav %}

The following works for a semi-dynamic homepage... however the name does not create... (If they change the title of the homepage on the backend, I'd like it to switch on the front-end.

  {{ craft.entries.slug('_home_').entry.title }}

Could anyone with a bit more experience with this give me some insight? I'm confused outta my mind.


texts:
I realize this may not be possible to do at all. But I thought I'd go ahead and ask anyway. I'm trying to set up a "hero" image of sorts for specific entries. Here is how I have it setup currently:

Series > Series Entries

Each series entry has a series artwork entry that belongs to it.  What I'm trying to do, is have Craft dynamically add the image in based on what series comes up. However, I have it styled just right in my css and I'm using it as background-image: url(). Is it possible to have craft dynamically change it? I tried to using a for loop and putting it in hard coded in the html, but I lose the responsiveness framework of Foundation.

Edit: Code:

{{ entry.title }}

    {% endfor %}

    #hero {
        background: url(https://s3-us-west-2.amazonaws.com/bridge-     assets/photos/hero_image_blue.jpg) #074e68;
        background-repeat:no-repeat;
        background-size:cover;
        height: 200px;
        text-align: left;
        position: relative;
        width:100%;
        padding: 100px 20px 0 20px;

        @media #{$medium-only} {
            height:300px;
       }

       @media #{$large-up} {
        height:300px;
       }
    }

Edit 2:

Here is my series page which lists all the series

{% extends "_layouts/_page" %}

{% block content %}

Messages

        {% for series in craft.entries.section('series').level(1).order('postDate desc') %}

            {% for image in series.seriesArtwork %}

                   {{ series.title }}
                  {{ series.seriesDates }}

            {% endfor %}

        {% endfor %}

{% endblock %}

and the css

section.series {
    position: relative;
    top: 20px;
    display: inline;

    li {
        list-style: none;
        text-align: left;
    }

    #overlay img {
        width: 100%;
        vertical-align: top;
    }

    img {
        position: relative;
    }

   @media #{$medium-up}{

   }

    .card {
        padding: 10px;
        margin-top: -10px;

        span.series-dates {
            display: block;
            color: #0A9CC9;
            font-family: 'grota_sansregular';
            font-size: 14px;
            margin-top: -5px;
        }

        span.series-title {
            font-family: 'grota_sansregular';
            font-size: 24px;
            color: #333;
        }
    }
}

And then when you click on a series (still work in progress, just trying to get image working first),

{% extends "_layouts/_page" %}

{% block content %}
  {% for image in entry.seriesArtwork %}

{{ entry.title }}

   {% endfor %}

{{ entry.title }}

    {{ entry.body }}

Written by {{ entry.author }} on {{ entry.postDate|date('M d, Y') }}

{% endblock %}


texts: Group entries by Category and then in each category by related entry field

texts:
I have a channel with categories and an entries field. I need to first group all entries by their category. This is working fine.

{% set entries = craft.entries.section('publicationsChannel') %}
{% set relatedCats = craft.categories.relatedTo(entries) %}

{% for category in relatedCats %}
   {{ category.title }}

  {% for entry in relatedEntries %}
    {# this list of entries needs to be grouped by the regionCountry field #}
    {{ entry.title }} <br>

  {% endfor %}
{% endfor %}

However what I now need to do is take the list of entries and further organize them according to a relationship field handle regionCountry

There are only 3 entries in that channel Canada, US, UK and they need to be grouped in that order.

I can't seem to wrap my head around the logic needed to do this.

What I need finally is.

Category 1

Canada

entry 1

entry 2

US

entry 1

entry 2

UK

entry 1

entry 2

Category 2

Canada

entry 1

entry 2

US

entry 1

entry 2

UK

entry 1

entry 2
etc...


texts: Multi-page form with Yii in a Craft site?

texts:
I have a Craft-based website and need to make a complex multi-'page' form on one page. The form isn't related to any Craft Entries etc, and doesn't need to save the submitted data to Craft's database (it's sent to a different database).

Having looked at a few form-related Craft plugins, I think I'll be best writing this from scratch. I'm experienced with PHP, but not Yii and I'm not quite sure how best to structure this within a page that will be generated by Craft (an Entry).

I'm guessing I could write a plugin and a variable in it is used in the Craft template to generate the form. Given that, some questions:

Should I create a series of Yii forms, one per 'page' of the form, and use the one indicated by a hidden 'step' form field?
Is there any issue with saving data to Yii sessions (for each form step's inputs) within a Craft site?
I could have templates for the different form 'pages' in my plugin. How would I pass data from the form (fields, submitted data, error messages) to the template?

I guess I'm also looking for general responses of either "This looks like a sensible route to explore" or "OMG don't go that way, there are monsters!" :)

EDIT: I think I should be using the plugin's Controllers to handle form submission, passing data to templates etc. Rather than having a plugin variable in a Craft Entry's template. Maybe I can integrate Yii forms with those Controllers?


texts: Is it possible to define optional route segments?

texts:
Is it possible to have optional route segments/variables with getCpRoutes() and getSiteRoutes()?

I'd like the following route to work, even if the URI only contains one segment ("myplugin") rather than two ("myplugin/somevalue"):

"myplugin/(?P<myVariable>[-\w]+)" => array( "action" => "myPlugin/myAction" )

How would the regexp look? Is it even possible, or do I need another route pointing to the same action, but omitting the myVariable segment?

This question is kind of a follow up to Route that should be matching numbers not matching a zero?


texts: Password protected area with unique files

texts:
We're considering using Craft for a new project. One of the features requested is to have a password protected area. Each user would have access to their own files only. So we'd need to be able to setup users and assign files to them. It also needs to be simple enough that the client could do this without our intervention.

I'm pretty familiar with how I would do this with EE but wondered if/how it could be done with Craft.


texts:
How does craft manage the counts? And how do I set it to a specific number?

I've already tried to do it manually with something along the lines of

ALTER TABLE tablename AUTO_INCREMENT = 1

But that doesn't really do the trick.

I've also noticed that there is no auto_increment setting in the table structures. Can someone please point me in the right direction?

Thanks!


texts: How to set base URL on the installation of Craft CMS on server

texts:
I am a beginner. I just install it on a server and also on localhost. But facing the same problem.
I set it http://www.example.com/ but I go to this URL it shows me the directory but when I go to http://www.example.com/web it goes to the default template.
I want to access default template on http://www.example.com


texts: Display entries by Category (Category in Super Table)

texts:
I'm been kicking myself for hours and going round in circles trying to get list of entries displayed by category when the category is selected from within a SuperTable (static table) row. I would really appreciate if someone could please help point me in the right direction.

I have a structure entries section named "services" with a number of entries created.
I have a category group named "serviceCategories"
I have a "SuperTable" static table field handle named "service"
In my SuperTable I have a row named "serviceCategory" which allows me to select a single category from the category group named "serviceCategories".

I'd like to create a standalone web page that displays all the category titles with the list of related entries.

I've tried:

{% set categories = craft.categories.group('serviceCategories') %}
{% for category in categories %}

  {{ category.title }}

  {% set services = craft.entries.section('services').relatedTo(
    { targetElement: row.serviceCategory }
  ) %}

  {% for service in services %}
    {{ service.title }}
  {% endfor %}

{% endfor %}


texts:
I'm new to Craft CMS, and was wondering if it is possible to migrate a Craft CMS website to a test domain, to do redesign work, before moving the update site back to the live domain?

and will this effect any license?

looking forward to hearing from you.

Kindest regards
Anrich Vigus


texts: Could I use categories for users instead of user groups?

texts:
I'm developing a sports league site. The roles I'm setting up are admins, coaches, and players - with myself being the "super" admin.

This is my first Craft project, so right off the bat I started developing the site by distinguishing the capabilities of each role through the user groups. I'm currently having issues with registering coaches & players to their respective user groups through plugins, though.
No one other than myself will be using the Craft CP. I'll be creating their own back-end dashboard to manage their own teams, user profiles, etc...

Which leads me to the question: Should I even be designating the users to different user groups? Or just throw them into specific categories & check against those with the current logged user?

Theoretically they would have all the permissions through Craft, but I'd limit what they can accomplish through the dashboard I create for them.


texts: Noob here. Can I buy a license without installing the software?

texts: I'm not the developer. I have no need for the software on my workstation. I just want to buy the license. Can I buy a license without installing?


texts:
does anyone know if you can send emails using utf-8 instead of ascii in CraftCMS 2?

I am using the Freeform plugin to send entries from a "Contact Us" form to a CRM that needs to receive the e-mails in utf-8 but they are coming in as ASCII. Is there a way to change this in either the plugin or in Craft?

Thank you!


texts: Redactor removes article tag from HTML while saving

texts:
I'm using Craft 3.x. I'm using the Redactor plugin in Craft. I have an HTML with an article tag (HTML tag). As soon as I save it, Redactor strips the article tag because of which UI goes for toss.

.
.
.

After saving, It simply removes these tags and keeps the inner tags.


texts: How to differentiate EVENT_BEFORE_UPDATE_SUBSCRIPTION events in Commerce 2/3

texts:
I'm listening for various subscription events to send emails to members. Right now, I'm dealing with subscriptions where a renewal payment fails. I'm specifically listening for EVENT_BEFORE_UPDATE_SUBSCRIPTION.
The problem is it's called twice per attempt (successful or not). Once for the Stripe invoice creation and once for the Stripe transaction attempt. Here's what is might look like:
Day 1: EVENT_BEFORE_UPDATE_SUBSCRIPTION called as the renewal invoice is created. The subscription status is active.
Day 1 (1 hr later): EVENT_BEFORE_UPDATE_SUBSCRIPTION called as the transaction fails. The subscription status is suspended.
Day 2: EVENT_BEFORE_UPDATE_SUBSCRIPTION called as a second renewal invoice is created. The subscription status is suspended.
Day 2 (1 hr later): EVENT_BEFORE_UPDATE_SUBSCRIPTION called as the transaction succeeds. The subscription status is active.
You can see from the above that just listening to the EVENT_BEFORE_UPDATE SUBSCRIPTION will result in two emails being sent each day. Even if I listen for the status being suspended, an unnecessary email will be sent the following day.
What I really want to do is differentiate between the event being called by Stripe creating an invoice and Stripe attempting a transaction.
Has anyone done this or know a variable I can test against to identify whether it's an invoice creation or transaction that has triggered the event?


texts: Craft 3 - Save new Entry with Relations (Categories/Assets)

texts:
i simply can not get my "job" done. I try to create a plugin for Craft, a simple one. It reads some date and should create new entries out of this data. First i stuck on a stupid save-mistake, someone here helped me get my error :)

Now, i  can create and save an entry.
But i can not add a category, an image or a matrix-based entry.
I tried several old craft 2 tutorials and got with the categories to Craft::$app->relations->saveRelations, but after i got rid of all errors, it saves my entry, create a ne row in my database relation table, but in the entry, i can not find the relation. The database row in relations seems to be incorrect. Last version of my code: i tried to convert this Problem/Example into my version in craft 3. No success :(

I think, if i understand my problem, i will be able to create several relations, because categories, Assets and so on are just types of fields. And they are related to the entries - am i right ?

I'll show my current code.....has anyone a good advise or an example how to add a relation(category) and how to create and add an image asset ?

    $section = Craft::$app->sections->getSectionByHandle('mychannelentryhandle');
    $entryTypes = $section->getEntryTypes();
    $entryType = $entryTypes[0];
    $entry = new \craft\elements\Entry();
    //      $entry->id = $uid;
    $entry->title = $title;
    $entry->sectionId = $section->id;
    $entry->typeId = $entryType->id;
    $entry->siteId = 1;
    $entry->authorId = 1;
    $entry->enabled = true;  // TODO:  Decide if published or not
    $entry->postDate = $postDate;
    $entry->slug = 'test_' . $uid;

    if (Craft::$app->elements->saveElement($entry)) {
        echo 'New entry created successfully.';

        // SAVE CATEGORY RELATION
        $field = Craft::$app->fields->getFieldByHandle('categoryfieldhandle');
        try {
            $relationsIds[] = $entry->id;
            Craft::$app->relations->saveRelations($field, $category, $relationsIds);
        } catch (\Exception $e) {
            // Something went wrong – return `false` or an error message, log the exception?
            print_r('ERROR WHILE SAVING CATEGORY');
            print_r($e->getMessage());
            return false;
        }

        // Save the new Relation
        Craft::$app->elements->saveElement($entry);

        $result = true;
    } else {
        echo 'Could not save the new entry.' . "\n";
        print_r($entry->getErrors());
        $result = false;
    }

Just testing code, not pretty but functional ;)


texts:
I've created my first Craft3 plugin and installed it locally via a composer.json path. After doing the composer require, the plugin showed up as installed (with a green dot) under Admin->Settings->Plugin.

However, the plugin has the following code:

$plugins=Craft::$app->plugins->getAllPluginInfo();
error_log('We have version '.$this->getVersion().' and handle '.$this->getHandle());
$plugin=Craft::$app->plugins->getPlugin($this->getHandle());
if ($plugin==null) {
     error_log('Could not find self');
} else {
     error_log('Fond self with version: '.$plugin->getVersion());
}
/* @var PluginInterface $plugin */
foreach ($plugins as $plugin) {
     error_log(json_encode($plugin));
}

calling any page and then checking storage/logs/phperrors.log shows:

22-Jan-2019 13:18:52 Europe/London] We have version 1.0.0 and handle craft-project-name
[22-Jan-2019 13:18:52 Europe/London] Could not find self
...
[22-Jan-2019 13:18:52 Europe/London] {
"developer":"myname",
"developerUrl":"https:\/\/www.example.com",
"description":"Example plugin",
"documentationUrl":"https:\/\/www.example.com",
"class":"rbairwell\\craftprojectname\\Plugin",
"basePath":"\/Applications\/Dev\/craftcms\/craft-project-name\/src",
"aliases":{"@rbairwell\/craftprojectname":"\/Applications\/Dev\/craftcms\/vendor\/rbairwell\/craft-project-name\/src"},
"name":"Craft Project Name",
"version":"1.0.0",
"sourceLanguage":"en-US",
"hasCpSection":false,
"packageName":"rbairwell\/craft-project-name",
"isInstalled":true,
"isEnabled":false,
"moduleId":"craft-project-name",
"edition":"standard",
"hasMultipleEditions":false,
"hasCpSettings":false,
"licenseKey":null,
"licenseKeyStatus":"unknown",
"licensedEdition":null,
"licenseIssues":[],
"isTrial":false,
"upgradeAvailable":false}
...

Why is the plugin unable to find itself using getPlugin even though it's confirm it's handle name and why, in the list of plugins does it come up isEnabled: false even though the admin front end shows it as installed+enabled and obviously the plugin is functioning?


texts: How to do advanced routing to a Craft channel

texts:
For a project I have, I am unable to use the standard Craft routing for a channel. For example,

/events/{slug}  <- this is how Craft wants to do it
/{slug}         <- this is how the client wants it done

I have tried to do this using routes, and can easily route to the correct template, however the entry is not defined.

Is there any easy way to not have to use Craft's routing that requires the events portion of the url? And have the entry variable available in the template?

Added to this is the fact I need to do URLs like

/{slug}/blog/{article-slug}
/{slug}/faqs/{question-slug}
etc etc

The homepage is a static template, but as there is no content to exist under /events, and being that events is the root of all other content (which is filtered by the event slug) I can't see a way so far to not have to use the full path the 'Craft' way.

Bonus Question:

Is there any way to prevent /events/{slug} from responding to requests also? Is it just using the exit 404 tag in templating?


texts: Passing multiple parameters to the Element API

texts:
How should I go about passing multiple parameters to the Element API?

The scenario is that I would like to display all my categories for a given section in a form, and allow the user to select categories, and send them to the API. I would like to receive back a json object of all the entries that have the categories assigned.

I am aware that I can dynamically catch url segments, but I'm not understanding how I would pass something like a GET parameter as a segment.

Thanks for the help!


texts: Handoff to Paypal Express with Craft Commerce

texts:
I'm running into issues handing off a cart transaction to Paypal Express. I've set the paymentMethodId correctly on the cart, but when I submit to commerce/payments/pay I am only getting redirected to my cart page and nothing is showing in the Commerce debug logs.

Aside from having cart items and a paymentMethodId, is there anything else required for the Paypal handoff? How can I further debug this?

<form method="POST" id="paypal_checkout_form">
  <input type="hidden" name="action" value="commerce/payments/pay"/>
  <input type="hidden" name="redirect" value="/thank-you?oid={{ cart.number }}"/>
  <input type="hidden" name="cancelUrl" value="/shop/cancel"/>
  <input type="hidden" name="orderNumber" value="{{ cart.number }}"/>

  {{ getCsrfInput() }}
</form>


texts:
We’re having a big issue with SEO data. Any link preview does not pull the entry title but the global site title. For example, on this blog post, all link previews (Google, Twitter, Facebook, LinkedIn, etc) show just Bridge Partners as the title and not the page title of Darby Greenwell Joins Bridge Partners To Lead Analytics Practice. I have searched high and low for solutions to this problem. Can anyone help point me in the right direction? Thank you!

www.bridgepartnersconsulting.com


texts: Joining two plugin tables by reference Id causes duplicates

texts:
I'm running a query in which I need to join two tables table_views and table_clicks. Both tables share several column names (mainly refId, month, year and total).

However when I try and join these tables together, instead of returning ~18 or 20 rows/records. It repeats the join for every single row, producing 360 records.

How can I query and combine both tables by their reference Id?

        $records = craft()->db->createCommand()
        ->select('*')
        ->from('table_views table_views')
        ->leftJoin('table_clicks table_clicks', 'table_views.refId=table_clicks.refId')
        ->where('table_views.refId = :refId', array(':refId' => $id))
        ->query();


texts: Is there a way to change what happens after you save a new entry?

texts:
I want to remain on the page I just saved so I can view it in the browser and return to continue editing, without having to find the page again in the all pages/entries area.

Is there a way to change the Craft CMS defaults on this?


texts:
Description

I’m having an issue getting Enupal Snapshot working on our staging server. The settings do not want to save in the craft admin.

It isn’t obvious what the error is. I have checked my log files and this is the only error I see replating to Enupal's plugin. I think this is a red herring as I have this working on my local environment.

2019-11-13 09:16:37 [-][1][-][error][enupal\snapshot\Snapshot::error] Something went wrong when creating the PDF file: Error executing "ListObjects" on "https://franklin.ams3.cdn.digitaloceanspaces.com/?prefix=tools%2Finnovation-assessment%2F&delimiter=%2F&encoding-type=url"; AWS HTTP error: Client error: `GET https://franklin.ams3.cdn.digitaloceanspaces.com/?prefix=tools%2Finnovation-assessment%2F&delimiter=%2F&encoding-type=url` resulted in a `403 Forbidden` response:

Steps to reproduce

run which wkhtmltopdf outputs /usr/local/bin/wkhtmltopdf
Save path to plugin settings

Additional info
Craft version: 3.3.9
PHP version: 7.2.24
Database driver & version: MySQL 5.7.27
Plugin version: 1.2.6


texts: Display all entries matching field of a section

texts:
I have two sections:
Games
Publishers

Games has a field called 'GamesPublisher' that is Entries type (set to Publishers)

I have a publisher called 'Microsoft' with an ID of 49.

I want to display all Game entries for the Publisher 'Microsoft' (ie ID 49)

I also want to set the order of the displaying in ASC order based on the field 'GamesCatalogNumber' which is in the section Games.

So far, it looks OK, but I have yet to figure out to limit entries to a specific Publisher.
http://www.colorcomputergames.com/tandy-catalog/

{% set entries = craft.entries.section('games').relatedTo(entry) %}

    {% for entry in entries.order('GamesCatalogNumber desc') %}

{{ entry.GamesCatalogNumber }}: {{ entry.title }}

    {% endfor %}

    {# Set parameters for prev/next elements list #}
    {% set params = craft.entries.section('publishers').order('title asc') %}

    {# Get the prev/next elements #}
    {% set prevEntry = entry.getPrev(params) %}
    {% set nextEntry = entry.getNext(params) %}

    {# And make sure to only output the links if the element exists #}
    {% if prevEntry %}Previous Publisher{% endif %}
    {% if nextEntry %}Next Publisher{% endif %}


texts: Using the Search Filter with Entry Fields

texts:
I've got an entry page and at the bottom I would like to show related products and then underneath that, related offers.

As the main page entry isn't assigned to any categories I've tried to use a custom field and the search param to show 'related' entries and this works fine, BUT, when I try and make it dynamic, it doesn't pull through. I'm guessing this is some kind of parsing order and that the custom field isn't parsed before the loop is created.

This works fine:

{# To exclude certain category #}
{% set categories = craft.categories.slug('not preferential') %}
{% set entries = craft.entries.section('offers').search('A1').relatedTo(categories) %}

But this doesn't when I try and make it dynamic:

{% set categories = craft.categories.slug('not preferential') %}
{% set entries = craft.entries.section('offers').search('{{ entry.model }}').relatedTo(categories) %}

I've also tried setting the variable first but it doesn't work:

{% set range = "{{ entry.model }}" %}
{% set categories = craft.categories.slug('not preferential') %}
{% set entries = craft.entries.section('offers').search(range).relatedTo(categories) %}

Hopefully this makes sense. Still in the basics I suppose of Craft but worth the learning curve.


texts: Force specific language for user activation mail and edit localized email templates

texts:
I'm trying to figure out how to set the default language for new users and user activation emails. I have found the defaultCPLanguage config setting which does indeed change the default language of new accounts created through the backend. However, the activation email doesn't use that default language. Based on testing I have determined that the account activation email will be sent in the language that the user creating the new account has set in their account preferences. So if I create a new user account with my admin account, which is set to English, the activation email will be in English as well. If I set my language preference to German, the activation mail will be in German.
Is there a way to change this? The CP doesn't provide a way to change the language preference of a new account. I would prefer it if the activation mail always used the language set as defaultCpLanguage.
As a sidenote, the templates for account emails are editable from Utilities -> System Messages. However, I can only edit those templates for my current language preference. To edit the messages in a different language, I have to set my account preference to that language first. This is weird and unintuitive. Is there a better way to edit System Messages across different languages? Or at least have the System Messages tab always display the messages in the defaultCpLanguage?


texts: Can not login in the control panel: Internal Server Error 500

texts:
The website ist working, but I can not login in the control panel.

In the console:

500 Internal Server Error - .../resources/lib/jquery-2.2.4.min.js?d=1493300895
setcookie() expects parameter 3 to be integer, float given (/html/alte gerberei/craft/app/framework/web/CHttpRequest.php:1514)

...

Has anybody an idea? Thanks in advance.


texts: Wrap a quote in differently styled quotes depending on locale?

texts:
I want to show quotes for my french visitors like so:

  « Something intelligent someone said. »

but visitors of my english locale should see the quotes formatted like so:

  “Something intelligent someone said.”


texts: How to clear the database of unused fields?

texts:
I have one section with different entry types. One entry type uses two matrix fields, another one only one, and so on.

Since the frontend layout is always the same, I use one template for the whole section:

{% extends "_layouts/main" %}

{% set title = entry.title %}

{% block content %}
    {% include "_fields/content__circles" %}
    {% include "_fields/content__body" %}
    {% include "_fields/content__links" %}
{% endblock %}

This works great, except when I change an entry to another entry type: Because the field-data isn't deleted from the db and shows up anyway, even though the field isn't added to the new entry type.

This is actually great, because that way your data isn't gone if you delete a field by mistake etc., but over time the db gets bloated, which I want to prevent.

Question: How can I delete data of fields which aren't used without editing each entry by hand or going in the db?

Clearification: entrytype 1 has content__circles and content__body, entrytype 2 has only content__body. After switching from type 1 to 2, the data of content__circles is still kept in the database, and is even accessible inside the entry-variable.


texts: In GraphQL how to query entries where related entry has a specific value

texts:
Lets have this query:

query test {
  entries(section: "vacancies") {
    title
    ... on vacancies_vacancies_Entry {
      description
      organisation {
        title
        ... on organisations_organisations_Entry {
          organisationType
        }
      }
    }
  }
}

Now how would I go about only displaying vacancies from an organisation that has a specific organisationType . I've had a quick read through graphQl docs and couldn't find anything that could help.

I guess I can first query organisations, get their IDs and then pass it to relatedTo parameter to another query, but that's 2 API requests each time I want to make a query. Is it possible to somehow use one graphQL query as a parameter in another graphQl query? Are there any better solutions to this?


texts: craft.feeds does not appear to be working

texts:
I want do display a financial widget on a front-end of a site.

The financial data is actually a feed:

http://test.solutions.vwdservices.com/customers/vastned.com/page-modules/widgetrss

But it's not working on the frontend. No content.

{% set feedUrl = "http://test.solutions.vwdservices.com/customers/vastned.com/page-modules/widgetrss" %}
{% set limit = 1 %}
{% set items = craft.feeds.getFeedItems(feedUrl, limit) %}

{% for item in items %}

{{ item.title }}

        {{ item.summary }}
{{ item.date }}

{% endfor %}

This is my feed data:

<Feed xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/2005/Atom">
<Title>Aandelen Vastned</Title>
<Id>0</Id>
<Updated>2014-08-22T17:29:40</Updated>
<Entry>
<Title>€ 36,81</Title>
<Id>00000000-0000-0000-0000-000000000000</Id>
<Updated>2014-08-22T17:29:40</Updated>
0,00%
<Author>
<Name>Grijs</Name>
</Author>
</Entry>
</Feed>


texts: 1045 Can't Connect To DB with Laravel Valet

texts:
I can connect to a Craft 3 site just fine using Laravel Valet, but when I attempt to get a Craft 2 site working with it, it gives me this in the log:

[exception.CDbException] SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

Visiting the site with the /index.php?p=admin portion appended to the url gives this:

Craft can’t connect to the database with the credentials in craft/config/db.php.

I 100% have the correct db credentials, as the Craft 3 site is using the same ones and is running just fine at sitename.test

'http://example.test' => array(
    'server' => 'localhost',
    'user' => 'root',
    'password' => 'thecorrectpw',
    'database' => 'dbname',
)

Does anyone have any idea what could be going on? I would like to keep using Valet as it makes my life easier, but I am going to fling my laptop out the window into the city streets in about an hour or so if I cant get this working =)


texts: Additional Fields aren't sent within Contact Form email

texts:
I am using Contact Form v1.9.0 with latest version of Craft.
I've additional fields to the form so that the inputted values appear in the email message. However, the only field being sent within the message is the message[body] field.

A link to a gist of my form code is below:
https://gist.github.com/anonymous/f380c316ad14864aed7aa95dbb2cafc8

I am using jquery to copy and replace the value of fromName and fromEmail, which you'll see are hidden fields.

This exact form has been used on numerous sites in the past few months, using Contact Form 1.8.1.

Any thoughts on why those additional fields aren't being attached to the email message?


texts: Craft commerce stripe - Starting subscription without payment fields

texts:
Is there a form similar to {{ plan.getGateway().getPaymentFormHtml({})|raw }} for starting a subscription that has a free trial, without taking payment details?
So essentially when the trial is up, I present the user with a form to add the card details.
Or would it just be simpler to create an extra free subscription that merely ends, then present the user with a form to start a different paid subscription? Either way, is there a simple form to start a subscription without payment details? Thanks :)


texts: Multiple URL Formats per element type (Entries, Categories)

texts:
I suspect this boils down to a feature request, but I'll start here in case there are any other ideas.

Basically, I want to be able to define multiple URL formats for a single section or category group.

Here is the scenario:

Section gear with URL format gear/{slug}
Category group productTypes with URL format gear/{slug}, {parent.uri}/{slug}
Section reviews with URL format reviews/{slug}.

What I want to do but can't, is define a second URL format for productTypes, with the format reviews/{slug}, and {parent.uri}/{slug}.

Similarly, I want to define a 2nd format for gear, of reviews/{slug}.

So I'd end up with:

gear/gear-entry/
gear/category/
reviews/category/
reviews/gear-entry/
reviews/review-entry/

So I really need Craft to know about those additional formats to avoid crossover URLs.

Routing and assigning the entry and category variables is not a problem, I'm really just concerned with the slug/uri validation.


texts:
We are trying to add Craft alongside another CMS. I currently have Craft setup with the Craft app directory above web root and then two web accessible sub-directories as follows:

blog
offer

Each subdirectory has a Craft index.php file in it, pointing to the one craft app directory above web root.

My issue now is trying to serve up a different set of pages based on which sub-directory the user accesses (ie. "www.domain.com/offer" or "www.domain.com/blog"). I thought I could add routes to do this but they don't seem to work as I'd hoped.

Are routes the right way to do this? I thought I could have defined a route of "blog/" to load a specific template but that does not work (I assume that first URL segment isn't available to the route based on having the index.php file in that directory?).

Is there another way to handle this that I haven't thought of?

Thanks,
Mike


texts:
I'm currently working on creating a full-sized Edit Page for my own Element Type.

I created a elementSelectField and wanted to know if you guys have some advise or good articles to read on that matter. Right now I'm crawling my way through the craft code for reverence and i am not sure if I'm doing this correctly :)

{% set section = craft.app.sections.getSectionByHandle('days') %}
{% set elementType = craft.app.elements.getElementTypeByRefHandle('Entry') %}

{{ forms.elementSelectField({
        label: 'Day'|t('app'),
        instructions: 'The day the cookie belongs to'|t('app'),
        id: 'day',
        name: 'day',
        elementType: elementType,
        selectionLabel: "Choose a day"|t('app'),
        sources: ['section:'~section.id],
        criteria: '',
        elements: elementType,
        viewMode: 'list',
        limit: 1,
    })
}}

I think this is Ok? Sending the form to my controller and dumping it there, the selectfield's value array contains only the choosen entry's id.


texts: How do you not output table field if there are no values?

texts:
I'm doing, what I think should work fine, however, I'm still getting a blank table output on the page if the table field is left unfilled when creating the entry. It's like the "if" check is being ignored for some reason. The table with data outputs as expected fine. What am I missing here? Gotta be something simple. Here's a link to the page in question: http://nightowlmusic.org/family/rotiron

{% if entry.discography | length %}

                Discography

            {% for row in entry.discography %}

                {{ row.releaseName }}
                {{ row.releaseYear }}

                    {% if row.purchaseLink %}Click here to purchase{% endif %}

            {% endfor %}

{% endif %}


texts: How can you get an entry type's name from its handle in a template?

texts:
Each of my entry types have their own template.

The url is something like:

/foo/{entryTypeHandle}

And the route is:

'foo/(?P<routesEntryTypeHandle>[-\w]+)' => 'bar.html'

In the template I can get the section the entry type is in:

{% set section = craft.sections.getSectionById(5) %}

And I can get ALL the entry types:

{% set entryTypes = section.getEntryTypes() %}

And I can get all the entries of that entry type:

{% set entries = craft.entries.section(section).type(routesEntryTypeHandle) %}

But I can't seem to get the entry type's name.

In the Sections Service there's a method called getEntryTypesByHandle but that's not available in the model.

I could get the entry type name from the entries, but that relies on there actually being results, which isn't assured.

{{ entries.first.type.name }}

I must be missing an easier way. Anyone?


texts: This will be my first time using Craft, where can I download free templates from or find instructions on how I can create my own templates?


texts:
I just copied my database across from local server to production server. I used Craft's control panel to create a backup. Then I used Sequel Pro to import this into the live server.
I got this error:

  [ERROR in query 121] The query length of 4327045 bytes is larger than max_allowed_packet size (4194304).

I clicked on 'Continue' and all looks OK on my live site.
Can someone suggest what this might mean? Should I worry? What should I do?


texts: Translation filter in Sprout Email plugin

texts:
I would like to make a notification of Sprout Email plugin bilingual.
However, in the body field, the translation filter does not work.
The tag of {{ fieldname.label|t }} is not translated.

How is it possible to translate it?
Actually it is the same question as this, but it was asked five years ago.
Translate filter and nested vocabulary properties


texts: Store form data with file upload in an asset source using Freeform

texts:
I currently have a form that has an upload file fieldtype and this currently stores the file in an asset source in Craft. What I would like to do is attach some of the form submitted field data alongside the asset using fields within the Asset field layout.

Ideally I would like to store the Form Submission ID, Name and Email address.

Any ideas as to how I would go about doing this?

Thanks,


texts:
I have a Blitz Cache but the only bit of dynamic data on the page is a "Follow" button which changes depending on if you're following this entry. Looking at their docs, I don't see a way of not caching a certain section or button?
{% if craft.follow.check({ elementId: entry.id }) %}
    favoriteRemove Brand
{% else %}
    favorite_borderSave Brand
{% endif %}

Is it possible to still make this dynamic?


texts: Hosting Craft Site on Github Pages with Paid Domain

texts:
I'm planning to move from an outside free hosting site to Github Pages free hosting, my site is a small portfolio, but I make changes every now and then so I want to take advantage to have my changes live right when I push to my repository, not having to copy those files to my hosting server and etc. Also I currently have a paid domain, the process would be, host on Github Pages, and redirect to custom domain, in this case I use Hostinger.

If possible:

I currently have on my Repo the templates folder, and my the public_html folder, do I need to include the whole craft folder and structure?

Please any step by step procedure would be appreciated, thanks.


texts:
We have a single page checkout where the items are selected and addressed added before going to
a cart summary page showing amount owed and tax due.
Was confused as to why certain codes were not working (checking validation against the service at https://ec.europa.eu/taxation_customs/vies/vatResponse.html) and realised the Craft Commerce submission requires the country ISO code as a prefix, eg a UK submission 166211234 needs to be GB166211234. Similarly dots and spacesm, etc need to be stripped out. Unless these are in the correct format relevant rules (eg do not add VAT if valid VAT tax record is added will not kick in).
So as a means for preparing this data thought could tap into an event to update this value.
The Addresses::EVENT_BEFORE_SAVE_ADDRESS event won't work as the update cart method/action saves the address after adding the line items and relevant calculations are made.
So then looked into the LineItems::EVENT_POPULATE_LINE_ITEM event so can theoretically fetch and update the address associated with the cart/line item being saved (we are only ever adding one item to the cart at a time. If an item already exists in the cart then that is removed first.
The following code looked promising (would ideally like to limit to EU tax zone but for now assume all sales are EU):
    // get line item
    $lineItem = $event->lineItem;
    // get order
    $order = $lineItem->order;
    // get billing address
    $billingAddress = $order->billingAddressId;
    // get billing address by ID
    $address = craftCommerce::getInstance()->getAddresses()->getAddressById($billingAddress);
    // get billing address tax ID
    $taxId = $address->businessTaxId;
    // get billing address country ID
    $countryId = $address->countryId;
    // get country ISO
    $country = craftCommerce::getInstance()->getCountries()->getCountryById($countryId);
    $countryIso = $country->iso;
    // strip non-alphanumeric characters from tax ID
    $cleanTax = preg_replace("/[^A-Za-z0-9 ]/", '', $taxId);
    // specify new, ideal tax ID
    $newTax = $countryIso . $cleanTax;
    // check if tax is specified, is not already optimised if not already changed
    if ($cleanTax !== '' && strpos($cleanTax,$countryIso) === false && $address->businessTaxId != $newTax) $address->businessTaxId = $newTax;
    // save the new address
    craftCommerce::getInstance()->getAddresses()->saveAddress($address, false);

However, whilst this saves the new address it doesn't update the existing one.
Any thoughts? Am I doing about this completely the wrong way.
Would rather than do this in the front-end JS if at all possible.
Cheers,
Cole
Craft 3.4.29.1.
Craft Commerce 3.1.12


texts: Craft CMS 3 admin panel returns 404 with SSL

texts: I'm using MAMP Pro for local development and was gong to set up my site with SSL this time around. I got a self-signed cert for local dev and I can go to my development site over https:// without any trouble but when I try to go to the control panel I get  404 error. I've updated the .htaccess file as suggested on Enforcing SSL for CP Requests but I still get a 404 error. All the Stack articles I could find on this issue were of no help either. Any suggestions? Something obvious that I'm overlooking?


texts:
Is it possible to show specific content or an entry for an individual user?

Here's what I'm trying to achieve:

A logged in user make a request to receive information on a particular service. An administrator then reviews the request and creates an entry specific for that user - whatever is contained within that entry is then displayed on the users dashboard for them to view.

How would I go about achieving this?

Thanks!


texts: Could different entities have the same handle?

texts:
I'm currently setting up a site. One routine operation there is to 1) create a category group and 2) create a 'Categories' field for it to attach to a section later.

Now for safety's sake I'm giving different handle names to the category group and the related field. For example, a category group has a handle called genre and the field — genre_field, just to ensure that no clashes between them would happen.

But is it actually a possible situation that handles of two different entities (here, fields and cat/groups, but it could be sections and fields as well and so on) could conflict?


texts: Craft Commerce, variable product prices based on weight. Is this possible?

texts:
I'm trying out the Craft Commerce plugin, and i'd like be able to let users order products with a custom price based on a choosen weight.

The price is now fixed to what you choose in the control panel, and there seems to be no easy way around that, but perhaps i'm wrong.

Is this possible? It's pretty crucial feature i need, so any help is appreciated :)

Cheers, Bob


texts: GeneratePendingTransforms stuck every time

texts:
I get a stuck GeneratePendingTransforms task over and over again. In the first place, I don't know why any transforms are getting created at that point. By now, almost every image transform for every image on the site must have been create once. And it seems like those generations happen on the weirdest moments. It can't be the images of a freshly posted entry that had to be created, because there's always +300 steps in the tasks (and there are 5 images at most on a new entry).

Anyway. It seems that those tasks also get stuck every time. I don't know why they get stuck. And yes, I know you can change the status to pending. But I can't keep doing this 10 times a day. The craft log doesn't give me much more information. Right now I have a GeneratePendingTransforms task that is stuck at step 333 from 341. And this is the latest info in the craft log file:

2016-10-08 21:55:00

Level   error
Category    exception.Craft\HttpException.404
Message Craft\HttpException in /srv/users/ijnluser/apps/ijnl/craft/app/controllers/TemplatesController.php:59

I don't know if stuck tasks also prevent the execution of pending tasks? But I also noticed cached items don't get cleared at all, and I have to clear them manually. Could this be because they are waiting to run, after the stuck task is done?


texts: Sprout email notifications - setting the recipient?

texts:
I have a front end form for logged in users to submit new entries. I want that user to receive a notification (via Sprout Email) that there entry has been received (it's pending/disabled on submission).

I'm struggling with what my recipient variable should be!?

I should add, it's the logged in user that added the entry that I want to receive the notification.


texts:
I've created an element type and want to have a 'Categories' and 'Tags' field built-in (the sources for each will be selectable in settings), but can't figure out the best way to go about this whilst supporting custom field layouts with tabs.
Do I just hard-code these fields into the edit page/hud html code then handle the logic on the save controller (this is fiddly whilst keeping it customisable/tab-able), or is there a better way to do it? I.e inject them into the field layout via the controller?
Can't get my head around this one.


texts: How do I properly use Twig syntax in dynamic title/URL fields?

texts:
I have an idea to create urls for entries that can't be guessed, but are automated without any extra effort from the content creator/editors. The intention is for the URL not require any authentication, but not be "guessable" just because you have another similar URL.

My thought was to use the Entry URL Format field to automate this. I tried the following but it didn't work as expected:

documents/{ (id * 1234567) | number_format(0, null, '-') }

I assumed I could use any twig syntax here due to the description/label for the input field:

  What the entry URLs should look like. You can include tags that output entry properties, such as {slug} or {postDate|date("Y")}.

So, is it possible to do what I'm trying? What's the correct twig syntax here?


texts: Add additional entry fields to backend search

texts: The search field in the craft backend entry section searches the title and slug field by default. Is it possible to add custom entry fields to this search function (in my case e.g. a custom item number or a field with additional keywords)?


texts: I managed to make an entry type that won't let me create any entries. How can I fix it?

texts:
I managed to make an entry type that won't let me create any entries.

The site is for a rock band, and the entry type in question is called "Shows". It contains five fields:

Venue
Lineup
Date
Time
Body

Date and Time are Date/Time fields, Lineup and Body are standard text fields. Venue is the field that I think is causing the trouble.

Venue is an Entries field that lets you select one from several venues, which are entries in a separate section (a Structure) called Venues.

When I enter data for a show, I'm able to select from the list of venues. When I try to save the Show, however, I get an error:

  Recoverable error: Object of class Craft\ElementCriteriaModel could not be converted to string.

The most meaningful looking highlighted line in the debug output is:

echo $this->getAttribute((isset($context["object"]) ? $context["object"] : $this->getContext($context, "object")), "venue", array());

All these pages are in the admin section, not in my templates, thus they are pages I can't edit, so I don't know what I can do to fix this error. Is it possible that I have created an entry type that Craft can't handle? There doesn't seem to be anything that unusual about the Venue entry type.

Have I done something obviously wrong? If not, how do I debug this?


texts:
I'm using the Connect plugin by Andrew Welch to get some data from an external database. Somewhere in the data, I need data from another related table. The way I'm doing this now is like this:
{% set games = craft.connect.query(db)
    .select(['*'])
    .from('games')
    .where(['and',{'LevelID': '15'},{'SeasonID': '2019'}])
    .limit(99)
    .all()
%}
{% for game in games %}

  {# use lots of data from the games table #}
  {# ... #}

  {% set home = craft.connect.query(db)
    .select(['Name'])
    .from('teams')
    .where({'ID': game.TeamA})
    .one() %}
  {{ home.Name }}

{% endfor %}

but I guess there must be a better way? Where I combine both queries? Or something like that?
Also, I would like to exclude results where the value of the column named "Status" is NOT "a" and NOT "b" (combined with the LevelID and SeasonID clause). How do I do this?


texts: How do I migrate a Wordpress project to Craft CMS?

texts:
How do I migrate my Wordpress project to Craft CMS?

What would be the best way?


texts:
I am testing Enupal Backup.
In the settings, I can choose to back up assets, templates, etc. But when I run the backup, only the database is acutally backed up.
What am I missing here?
I submitted an issue regarding this at the repo, in case it's a bug.


texts: How to save Asset field of an Entry programmatically in Craft 3

texts:
Using this answer on how to save data on Craft 3, I want to save also an asset field, but I cannot find out how.

It works for a Category field using the ids of the categories but not with ids of Assets.

Here is the code:

use craft\elements\Entry;
use craft\elements\MatrixBlock;

// Figure out the section & entry type
$section = Craft::$app->sections->getSectionByHandle('news');
$entryTypes = $section->getEntryTypes();
$entryType = reset($entryTypes);

// Create an entry
$entry = new Entry([
    'sectionId' => $section->id,
    'typeId' => $entryType->id,
    'fieldLayoutId' => $entryType->fieldLayoutId,
    'authorId' => 1,
    'title' => 'My Entry',
    'slug' => 'my-entry',
    'postDate' => new DateTime(),
]);

// search categories and retrieve therir ids
$categorySlugs = ['cat1','cat2','cat3'];
$craftCategoryIds = [];
foreach ($categorySlugs as $cs) {
    $craftCategoryIds[] = Category::find()->wpSlug($cs)->one()->id;
}

// get a an asset to be used as a featureImage
$featureImageId = Asset::find()->myField('123')->one()->id;

// Set the custom field values (including Matrix)
$fieldValues = [
    'summary' => 'Some "summary" custom field value...',
    'categories' => $craftCategoryIds, // <-- this works, categories are assigned
    'featuredImage' => $featureImageId, // <-- doesn't work, featured image is not set
    'matrixField' => [
        'new1' => [
            'type' => 'blockTypeHandle',
            'fields' => [
                    // the block's custom field values...
            ],
        ],
        'new2' => [
            'type' => 'blockTypeHandle',
            'fields' => [
                    // the block's custom field values...
            ],
        ],
    ],
]);

$entry->setFieldValues($fieldValues)

// Save the entry
Craft::$app->elements->saveElement($entry);


texts: Don't allow multiple users with same the password

texts:
I am working on a user registration page with AJAX.
I noticed that users are able to create accounts which have the same passwords. How do I disable this?

If users want to create an account with the same username I do get an error message, why does that not happen for passwords?

Thanks!


texts: Showing categories in Channel Entry URLs

texts:
I have a site which has two blog-like sections, which I'll call Blog and News. Each has a few categories. The categories are different in each section. An article always has (only) 1 category assigned to it. I want the URLs to be like:

/blog/                            # index page
/blog/category-slug               # listing all articles in category
/blog/category-slug/article-slug  # an article
/news/
/news/category-slug
/news/category-slug/article-slug

I'm struggling with how to construct this nicely out of Craft's Fields, Sections, Channels, Entries... I imagine I may need some custom routing, but haven't even got that far. Should I have two separate Channels and two separate Category sets? One Channel with two Entry Types and two Category sets? One Category structure with 'blog' and 'news' at the top level? How do I generate URLs for an Entry that will include /news/category-slug/...?

I'm going round and round in circles. I've tried things from answers here but haven't yet managed to display an entry at any URLs I expect.

(As an added wrinkle, I want the /blog/ and /news/ pages to appear to the user to be pages within a separate Structure... but I was going to worry about that once I've got the basic channel/category/entry stuff working!)


texts: Craft 3 js - extend the field layout designer field settings

texts:
I would like to have the ability to include a custom option in the field layout designer field settings. There is already a plugin for Craft 2 that uses this feature Relabel for Craft

And I would like to include a behavior like this in Craft 3 too but I can't find a way to solve this issue.

The FieldLayoutDesigner is initialized here and the settings are created with

initTab: function($tab) {
    if (this.settings.customizableTabs) {
        var $editBtn = $tab.find('.tabs .settings'),
            $menu = $('
').insertAfter($editBtn),
            $ul = $('
').appendTo($menu);

        $('
' + Craft.t('app', 'Rename') + '
').appendTo($ul);
        $('
' + Craft.t('app', 'Delete') + '
').appendTo($ul);

        new Garnish.MenuBtn($editBtn, {
            onOptionSelect: $.proxy(this, 'onTabOptionSelect')
        });
    }

    // Don't forget the fields!
    var $fields = $tab.children('.fld-tabcontent').children();

    for (var i = 0; i < $fields.length; i++) {
        this.initField($($fields[i]));
    }
},

But I don't see any triggers or other options to extend the content. Can someone please point me to the right direction how to include a custom button properly?

I think waiting for the click event on the wheel icon and wait until the DOM menu is created to attach a custom button might not be the best and intended idea?

Thank you very much.


texts: Event when a sections' entry type changes layout?

texts:
Is there a way or an event available to detect changes on the fieldlayout of an entrytype? We've wrote a piece of middleware that needs to be informed of such changes.

Thanks in advance,

Patrick


texts: Updates available on local copy but don't show on live site

texts:
My local copy of a live site is showing an update to Craft 2.2 build 2593 is available but a check for updates on the live site gives "Craft is unable to determine if an update is available at this time."

Has anyone come across this kind of behaviour before?

Am I safe to update my local copy, commit changes and push to live site?

Both local and live site are both in sync at the moment running Craft Pro 2.2.2592


texts: Checking for an object, based on a string, using Twig

texts:
Is there a way—using Twig—to check if a variable is set based on a string of the same name?

In this example below, editLink.object is a string with the value of "entryAlias". I want to check to see if a variable, entryAlias, has been set and to see if it's an entry.

{% if "#{editLink.object}" is same as(editLink.object) %}
    it workes
{% else %}
    not so much
{% endif %}

I've looked into same as and is, but I think the problem I'm having is converting the string to an object. Also, I'm pretty sure this can just be done using PHP, but I'd like to see if it can be done within Craft's Twig so this can be cached as part of a template.


texts: Commerce - Email users on new product input

texts:
Good Afternoon,
Is it possible to have Craft email a list of users (based on a category) when a new product is added to the shop?
Is there a pluigin that would do this, or is it a matter of a small script?