texts: Ran the Craft Updater from Control Panel the current install is no longer working

texts:
The previous install (3.0.34) was working fine until I ran the updater from the CP. The update failed with error (couldn't access web.config (IIS))

Now loading CP or front end displays the following error:
Warning: require(C:...Craft\Projects\Untye/vendor/craftcms/cms/bootstrap/web.php): failed to open stream: No such file or directory in C:\Users\rickn\Documents\Craft\Projects\Untye\web\index.php on line 20

Fatal error: require(): Failed opening required 'C:...\Craft\Projects\Untye/vendor/craftcms/cms/bootstrap/web.php' (include_path='.;C:\php\pear') in C:...Craft\Projects\Untye\web\index.php on line 20

Is there a way to finish the install manually and keep the previous work and data?

{
"require": {
   "craftcms/cms": "3.0.35",
 "vlucas/phpdotenv": "^2.4.0",
    "craftcms/redactor": "^2.1",
"craftcms/mailgun": "^1.3",
   "craftcms/contact-form": "^2.2",
"indigoviking/liquid-letters": "^1.2",
    "lukeyouell/craft-contactformtemplates": "1.0.1",
"doublesecretagency/craft-bootstrap": "4.1.1.2",
   "fatfish/navigation": "1.0.7",
 "superbig/craft3-templateselect": "^2.0",
   "craftcms/ckeditor": "1.0.0-beta.2",
 "verbb/navigation": "^1.0",
   "enupal/slider": "1.2.2",
 "studioespresso/craft-dumper": "^1.3",
   "topshelfcraft/wordsmith": "^3.0",
 "craftcms/craft": "^1.0"
 },
 "autoload": {
 "psr-4": {
    "modules\": "modules/"
  }
 },
 "config": {
   "optimize-autoloader": true,
 "platform": {
     "php": "7.0"
  }
 },
 "scripts": {
  "post-root-package-install": [
 "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
   ]
 }
}


texts: User registration; validate email but don't activate automatically

texts:
is it possible to have the public registration form validate the users Email, but still require manual activation by a system administrator?

There's User Registration - Keep as inactive until verified by admin which I think will stop a clicked email confirmation link from activating the user...

but from what I can tell Craft's "email confirmation" is really just an "activate user via link"; so it's not really confirming the validity of the email nor storing that confirmation anywhere; it's just activating the user. Is that right or am I mis-understanding it?

Thanks,
Matt


texts: Craft Cookies Plugin: Font Loading Detection

texts:
I'm trying to re-write my font loading detection using the Craft Cookies Plugin. I'm unsure if what I have done is correct...

Before

<!--# if expr="$HTTP_COOKIE=/fonts\-loaded\=1/" -->
<html class="fonts-loaded" lang="{{ craft.app.language |slice(0,2) }}" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
<!--# else -->
<html lang="{{ craft.app.language |slice(0,2) }}" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
<!--# endif -->

After

{% if getCookie('fonts-loaded') %}
    {% do setCookie('fonts-loaded', fontLoad, now | date_modify("+1 hour").timestamp) %}
    <html class="fonts-loaded" lang="{{ craft.app.language |slice(0,2) }}" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
{% else %}
      <html lang="{{ craft.app.language |slice(0,2) }}" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
{% endif %}


texts:
An entry could be validated by the following code in craft 2:

craft()->content->validateContent($entry);

How could be the same done in Craft 3 ?


texts: Is there a fallback when a Twig extension is not enabled?

texts:
So I have a plugin with a Twig Extension that does it's thing. If I were to disable my plugin I will get the expected error:

  The "extensionName" extension is not enabled.

Whenever I'm referring to anything to do with my plugin, I rely on the usual "is defined", "is not empty", "|default()", etc... options as appropriate fallbacks/checks incase my plugin fails.

However, short of doing a full check on wether my plugin is installed everytime, there doesn't seem to be an elegant solution for checking extensions are enabled until it's too late (and the page fails to load).

Any ideas on a workaround?


texts:
Has anyone got any experience working with iCal feeds - I have written a plugin utilising the CalFileParser library but the UK clock changes have thrown all the items out, so eg an all day event is now showing up as at 11pm the day before. For example:

BEGIN:VEVENT
DTEND:20170418T230000Z
DTSTAMP:20170412T114209Z
DTSTART:20170418T230000Z
SEQUENCE:0
SUMMARY:F4 Careers Day
UID:65d28288-9ba7-404c-85fe-b66682e2f605
END:VEVENT

Is importing as 23:00 on 18/04/2017. However importing the feed into Calendar (Mac) is reporting the event as expected at 00:00 on 19/04/2017.

If I update my site settings to BST (UTC+1) and parse the value into a DateTime object then it outputs to screen correctly, eg:

$tmp = DateTime::createFromString($item['dtstart']->date);

Outputs:

Craft\DateTime Object ( [date] => 2017-04-19 00:00:00.000000 [timezone_type] => 3 [timezone] => Europe/London )

However, on saving to my database record (to a column with AttributeType::DateTime) this date value is saved as 2017-04-18 23:00:00. This means that any attempt to retrieve and show this on my site outputs the wrong date/time.

Any thoughts on how to get my script to acknowledge the time difference and save this to the relevant record without having to tinker with the code every 6 months?

Cole


texts:
I am trying to use the relatedTo parameter to get user details for a given entry with this code:

{% for entry in craft.entries.section('blog').limit(1) %}

    {{ entry.title }}

    {% set authorDetails =  craft.users.relatedTo(entry) %}

    {% for person in authorDetails %}
        {{ person.firstName }} {{ person.lastName }}
    {% endfor %}

{% endfor %}

The Title returns fine, but nothing else. First time I have used relatedTo and guess there is something I don't understand about usage. Any advice greatly appreciated!

Roi


texts:
I inherited a site running craft and I was asked to move it to my server to host it. The other developer zipped the files and made a database dump for me.
Usually, when I move a site, they have Cpanel access, so I just move and it works with a few tweaks, but they didn't have Cpanel and I am in over my head.
I Know I haven't provided a lot to go on, as I don't know what you need to help me. What is a common thing overlooked? I can post error messages if it helps. The main one I get is the following:
[15-Sep-2020 13:22:01 UTC] PHP Warning:  Use of undefined constant _DIR_ - assumed '_DIR_' (this will throw an Error in a future version of PHP) in /home/client/public_html/index.php on line 7

[15-Sep-2020 13:22:01 UTC] PHP Warning:  require_once(./home/client//vendor/autoload.php): failed to open stream: No such file or directory in /home/client/public_html/index.php on line 11

[15-Sep-2020 13:22:01 UTC] PHP Fatal error:  require_once(): Failed opening required './home/client//vendor/autoload.php' (include_path='.:/opt/cpanel/ea-php74/root/usr/share/pear') in /home/client/public_html/index.php on line 11


texts: Selecting entries using a checkbox field

texts:
I had what I thought was a very simple issue: Select some categories on the front-end, filtering by a Checkbox field.

The Checkbox has values, which correlate to Locales.

The end goal was to create a 'workaround' to the fact that you can't disable/enable a category per Locale.

So on the template, I attempted:

{% for collection in craft.categories.group('dressCollection').regionAvailability(craft.locale) %}

But that doesn't work.


texts: How do I set this up the right way, transferring from Wordpress as CMS?

texts:
I'm trying to do something I'm used to in Wordpress, but can't really find a right way, or 'correct' way. What I was used to do in Wordpress; every page had a few options, like center content, background image, etc. In page.php (if you know Wordpses this'll make sense) I called a function pageDetails() (defined in functions.php) which returned me some variables for centering content, if it had a background image, etc.

Now I'm trying to do the same in Craft, so I created a section for the pages, added some custom fields to the pages, and now I'm trying to create a likewise method for defining a function once and use that for different 'entry types' to avoid repeating myself for each entry type template. For this, I keep coming back to creating a macro, that I define in _macros/macro.twig (for example). But, I can't get it to return variables.

In short; is there a way to use 'variables' from entry template, to the macro, and have the macro return vars (or array) to the entry template so I can use them in there? Or should I completely rethink this way of doing it?


texts: Query Craft CMS Table Field for exact values

texts:
Am I correct in saying you cannot search for specific text in a table field. e.g.

Table Fields Might hold the following data:

SKU1
SKU2
SKU3
SKU33

I then want to search for items that only return SKU3 not SKU33.

body::salty search will not work because i believe the field is stored as JSON.


texts: What would prevent my assets from reindexing on a local MAMP install

texts:
Having an issue with assets not reindexing from the Update Asset Indexes option.  If I add new folders to the file system they do not appear after I run the Update Asset Indexes, if I upload them manually in the backend then they do appear as normal.

How would I diagnose this?  Running Apache as my logged in user so it's does not seem to be a group / permissions related issue.


texts:
I'm trying to create a "Hack Job" version of Similar Entries, I'm using the following code but it seems to be getting the same entries over and over again. I know shuffle function does this, but I thought it'd be shuffling through the entire array of Entries?

{% set nextEntries = shuffle(craft.entries.section('merchants').id('not ' ~ entry.id).limit(15)) %}

I'm looking to make it grab a random 15 entries from the merchants section, which I will then cache.

Any help would be great.


texts: Author saved as NULL when updating entries from a plugin

texts:
I'm using a custom plugin with a service and controller to save relational fields to entries. I'm able to do this just fine, but when it saves an entry, it sets the author as NULL in the database and it no longer shows in the author's list of authored entries.

I've tried to both not set the author at all and to manually set the author to the previous author. Craft gives me an Internal Service Error saying "Property 'Craft\EntryModel.author' is read only." when trying to set the author in the code. Removing the retrieval and setting of the author saves the entry but marks the author as NULL

Has anyone else faced this? Is it a bug?

For reference, here's the heart of this service's code:

    $criteria3 = craft()->elements->getCriteria(ElementType::Entry);
    $criteria3->id = $kitId;
    $currentKit = $criteria3->first();
    $currentAuthor = $currentKit->author;

    $kit = new EntryModel();
    $kit->sectionId = '6';
    $kit->id = $kitId;

    $kit->author = $currentAuthor;
    $success = craft()->entries->saveEntry($kit);


texts: Filtering/searching for entries by category in the control panel

texts:
Is there any way of filtering by category in the control panel entries list?

Likewise, is there for an "entries" field (like how Playa lets you filter by channel, category)?


texts: Can I create multiple website using the same admin control panel and what I have to change for that?

texts:
I want to create the multiple website using Craft CMS existing control panel. I am using craft 3.x
Do I need the Craft Pro to use this feature?


texts: Have auto selected categories with new section entry

texts:
Is there a way to have auto selected a category when an editor creates a new section entry in the admin?
Kinda like a pre-filled field?


texts: Custom Labels for Address Fields Craft Commerce

texts:
I need to be able to assign and output my own custom labels for the fields that are in the shipping/billing addresses during checkout in Craft Commerce.

I've already done so on the form like so:

{% set countries = craft.commerce.countriesList %}
{% set states = craft.commerce.statesArray %}
{% set addressFields = {
    firstName: {
        label: 'First Name',
        required: 1,
    },
    lastName: {
        label: 'Last Name',
        required: 1,
    },
    address1: {
        label: 'Address',
        required: 1,
    },
    address2: {
        label: 'Address 2',
        required: 1,
    },
    city: {
        label: 'City',
        required: 1,
    },
    zipCode: {
        label: 'Zip Code',
        required: 1,
    },
    phone: {
        label: 'Phone',
        required: 1,
    },
    alternativePhone: {
        label: 'Alternative Phone',
        required: 1,
    },
} %}

{% set modelName = modelName is defined ? modelName : 'address' %}
{% set model = address is defined ? address : null %}

    {% for key,options in addressFields %}

            {{ options.label|t }}{{ options.required ? '*' : '' }}
            <input type="text" id="{{ modelName }}-{{ key }}" class="u-full-width" name="{{ modelName }}[{{ key }}]"
                   value="{{ model ? model[key] : '' }}">
            {% if model and model.getErrors(key) %}
                {{ model.getErrors(key)|join }}
            {% endif %}

    {% endfor %}

That works like a charm. I need to however also be able to output it with my custom labels as well. Here is my currently template area, i'm not sure how i can get my custom labels in here. Please advise:

{% for address in addresses %}
     {% for key,value in address.attributes() %}

          {% switch key %}

               {% case "id" %} {# ingore #}
               {% case "customerId" %} {# ingore #}

               {% default %}

               {% if value %}

{{ key|title }}:

                                   {{ key == 'countryId' ? address.countryText : (key == 'stateId' ? address.stateText : value) }}

               {% endif %}

          {% endswitch %}

     {% endfor %}


texts: Asset field - saving assets with dynamic subfolder by categories not working consistently

texts:
I have two asset (image) fields in project entry type, both with the same setting and with different outputs… Anyone knows why? Thanks

My fields are:

intro image field
gallery image field

Both should save uploaded images into one folder named by project and it's two levels category:

projects/{category.one().slug}/{category.inReverse().one().slug}/{slug}

My categories might look like:

accommodation

hotels
hostels
apartements

bussiness

offices
stores
fastfood

So both image fields should be saved to one folder, example:

projects/accommodation/hotels/project_slug

But they usually ends in two separate folders:

projects/accomodations/hotels/project_slug (intro image)
projects/hotels/hotels/project_slug (gallery field)

Any idea what is the problem and why the dynamic field folder structure varies from field to field?


texts: WebP-transform doesn't work with >600 pixel height

texts:
I am currently playing around with Craft's built-in transform for WebP. I am using GD driver. In general I am able to generate WebP files from my assets. That works well. But it only works up to a specific target height of the transform.
format: webp / height: 500 / quality 100: = works
format: webp / height: 600 / quality 100 = doesn't work
format: webp / height: 600 / quality 10 = works
format: webp / height: 700 / quality 10 = doesn't work
Doesn't works mean, that I just see a white area instead of an image. Works mean, WebP was successfully generated and I can see it in the browser.
Any idea to get this thing running? It would be so awesome to be able to generate webp right out of Craft assets.


texts: How to list the latest 3 entries per category per section?

texts:
I'm trying to create a condensed overview of my website content on my homepage. I'd like that page to loop through all sections, in each section looping through the categories that apply to the section, and for each category to pull the title, uri, and excerpt of the newest three entries.

I'm having trouble wrapping my head around how I'd do that.

What I'm after might be seen as:

SECTION
  CATEGORY 1 [title, description, view category archive]
    POST 1 [title, excerpt, publication date, view entry]
    POST 2 [title, excerpt, publication date, view entry]
    POST 3 [title, excerpt, publication date, view entry]
  CATEGORY 2 [title, description, view category archive]
    POST 1 [title, excerpt, publication date, view entry]
    POST 2 [title, excerpt, publication date, view entry]
    POST 3 [title, excerpt, publication date, view entry]
SECTION 2
  CATEGORY 1 [title, description, view category archive]
    POST 1 [title, excerpt, publication date, view entry]
    POST 2 [title, excerpt, publication date, view entry]
    POST 3 [title, excerpt, publication date, view entry]

For the sake of simplicity, all my categories are currently under a 'global' group. They also map pretty much 1:1 to the EntryTypes available in each section. (I'm not entirely convinced I'm using Categories / EntryTypes correctly, given that 1:1 relation... in fact that's another question to ask).


texts:
Is it possible to have a task (defined in a plugin) be scheduled in Craft to run on a recurring basis without having to use cron?

If so, where do I put those settings (eg, to run a task hourly)?


texts: Getting image for product in Cart Screen

texts: Really struggling with this (perhaps my brain is tired), but how would I get the image of a product for each entry in the cart screen in Craft Commerce?


texts: How to overrule Craft error messages with custom setError()?

texts:
I know I can set errors and notices in the CP with setError() and setNotice().
But it gets overruled by the default error message in my event.

I have a beforeDeleteEntry event which stops the deleting of an entry by using $event->performAction = false;. This makes Craft display a default error "can't delete entry". I'd like to add more to that error or show another one, but using setError() does not work. A setNotice() is shown however so I suppose the error gets replaced by the default Craft error.

Can I do something about that?


texts:
I have the following problem: I would like to have one craft backend / one installation for different one pager sites on different domains. The reason is, that we have one HTML template we would like to use for our landing pages for different purposes (e.g. landingpage with different testimonials) and we would like to use a different domain for each version of the landingpage.

My initial thought was, to build a channel and to setup it up like www.domain.com/landingpage01, www.domain.com/landingpage02 etc.

So how do I route mycooldomain.com to /landingpage01 and myothercooldomain.com to /landingpage02?

Or are there any other solutions for my problem?


texts: Is there a way to get the rich text field to automatically convert straight quotes to curly (smart) quotes? I'm not seeing anything on the redactorjs site or in the docs.


texts:
Is it possible for me to execute any "init" like function for my Plugin the first time the user visits the site? You could say when the first userSession is defined.

I tried looking through the docs to see if there was any Event for when the user session is created but I couldn't find any.

I want to add some default values to the userSession the first time the user hits my site.


texts: Get repeated events with the Solspace Calendar and Element API plugins

texts:
When looping through all events in Twig, repeated events will continuously come in. On a weekly event, for instance, it pulls one for this week, one for next week, etc. Lets say I have a meeting event set to repeat weekly, it would come back like this:

{% for event in craft.calendar.events %} ...

Meeting Event
Meeting Event
Meeting Event
...

I'm looking to load events asynchronously with the Element API plugin but I'm only able to get back each event once (even the repeated ones). How do I achieve the same behavior? Here is the basic setup:

<?php
namespace Craft;

return [
  'endpoints' => [
    'api/events.json' => function() {
      return [
        'elementType' => 'Calendar_Event'
      ];
    }
  ]
];

And it only returns:

Meeting Event


texts: How can multiple fieldtype instances without a content column be attached to the same entry type and still be uniquely identifiable?

texts:
We have a custom fieldtype that can be attached to an entry type multiple times and everything works just fine. This fieldtype has multiple input fields (shortUrl, longUrl) and they have been properly namespaced to make them unique (via the fieldtype handle) and when the data is saved, it gets saved to a table that defines the necessary columns (id, elementId, shortUrl, longUrl) since the defineContetAttribute() method has been set to false.

As previously mentioned, this fieldtype has been properly namespaced and is taking advantage of the Craft JS buffer to avoid naming conflicts.

The issue comes up when we try to retrieve the data from our custom table via preValue($value) because $value will be null and all the other values we have access to in this context  ($field->model->id, $field->model->handle, $field->element->id) are not unique enough to fetch a record.

I've tried a couple of workarounds but have not found a clean way to do this yet.

The prepValue() method provides the entry id ($field->element->id) which we can use to fetch the content (record) for each field since we have a relationship set but beyond that, I haven't found any other way to identify each record individually so that I can attach it to the right field instance within the input html.

There might be something simple that I'm missing and thought I would ask: )


texts: Live Preview not working in some sections

texts:
Live preview works in some sections, but not ones that use routes and have "entries in this section have their own urls" deselected.

Is this expected behaviour?

Is there any way to use live preview on these sections?


texts: Issue with Vagrant/Homestead setup (server requirements message)

texts:
I'm trying to set up a local dev environment for Craft. I've been following this video So far, I've installed Composer, Vagrant, and Virtual Box. I have my Homestead.yaml file set up and going to homestead.dev is loading craft, but now I'm getting the following message about not meeting the server requirements and a blank list of requirements.

Any thoughts on what I'm missing, or where I could look? Thanks!


texts: Why isn't relatedTo not working (anymore)?

texts:
I’m using a structure for creating new pages and navigation. In this structure there are multiple entry types where one is used for creating category pages. Here a user can add some content and select a category that will be used to load projects that are related to it.

In my template I'm using this code to do this:

{% set category = entry.projectCategory.first().slug %}
{% set params = {
        section: 'projects',
        relatedTo: category
} %}
{% set projectEntries = craft.entries(params) %}

{{ category }}

{% for projectEntry in projectEntries %}

                    {% set image = projectEntry.featuredImage.first() %}{% if image %}{% endif %}

{{ projectEntry.title }}

{% endfor %}

First I'm getting the category slug that was selected for this category page. After that I'm setting up my parameters for getting projects (this is another section) that are related to that category.

Before it worked perfectly fine when I had put in a "static" category (so not using the category variable) but when I tried to push the selected category the whole thing stopped working. Even going back to my original code that worked doesn't load any projects.

If I remove the "relatedTo" argument it loads all projects just fine.

Also the slug is perfectly shown in the H1 tag.

Any ideas?


texts:
I have a site that is mixed English and Chinese.  I've properly set up the locale to include Chinese as a locale, and have put Chinese translations for my fields in place.  That all works.

However, the site isn't one where you'll pick Chinese or English, it's going to display both in many cases.

So is there a way to explicitly set the English or Chinese translation of a global (or any field for that matter)?

I tried:

{{ myGlobalSet.myGlobal.en }}

As well as:

{{ myGlobalSet.en.myGlobal }}

...but it didn't like either one of them.  Is there a way to retrieve the localization of a field without having to switch the locale of the entire site?


texts:
I'm trying to get url from request,
 {{ craft.app.request.url }}

but the uri is chinese, like "localhost/測試",
it print out "http://localhost/����"
did i miss some setting in craft CMS ?
Thank you.


texts: What, if any, are the dangers to modifying users directly in the database?

texts:
Is it dangerous for the longterm stability of the Craft database to modify user privileges (i.e. suspend users or change user group) at a database level?

Example scenario:

Somebody has gone into the database and suspended specific users and didn't use the Craft CP. Would doing this action in Craft CP modify more tables than just "craft_users"?


texts: How to Redirect After Successful Registration Confirmation

texts:
When a user registers on the front-end of our site, we'd like the default behavior be that when they click on the confirmation link in the email they receive, they are automatically logged in and taken to a "My Account" page that we've created. Is this possible? Right now, they're redirected to the home page, and it doesn't appear that they're logged in.

We updated the postLoginRedirect variable in our config to the My Account page, but that didn't seem to do the trick.


texts: How to iterate over matrix field from a plugin

texts: I'm writing a plugin where I have the id of an entry, that entry has a matrix field, and I want to iterate over the blocks of the matrix field. In php. How do I do that? Pointers to good documentation for how to do this would be appreciated too.


texts: Getting entries from multiple categories

texts:
I have two categories, Annual Reviews and Publications.
I want to get all entries from these and paginate them.

The code I am using is fine for one category - both work individually, but as soon as the criteria contains two categories i get zero results no errors. I have tried using 'one()' on the initial categories as I only want category returned.
What am I missing? (using Craft Pro 3.1.31)

{% set publications = craft.categories.group('resources').slug('publications') %}
{% set annualreviews = craft.categories.group('resources').slug('annualreviews') %}

{% set entries = craft.entries({
section: 'resources',
relatedTo: [
'and',
{ targetElement: publications },
{ targetElement: annualreviews }
]
}).limit('10').orderBy('title') %}

{% paginate entries as pageInfo, pageEntries %}


texts: How to link to an entry in a Markdown field in the CMS

texts:
I want to do something that's perhaps connected to the id so that if the title/slug updates, then I don't have to hunt anything down in entries across the CMS.

Something like this maybe?
[Link to an entry](/section#entry:10725)


texts: Commerce PDF error: Image not found or type unknown

texts:
In the order template, this error shows up in the generated PDFs when adding standard JPG images.  We're running Commerce 1.2.x on PHP70.

It could be related to this dompdf issue, but how do we fix it in Craft Commerce?


texts: Images much larger on server and page than the local version

texts:
I am trying to bring image file sizes down as much as possible, but the images on the server turn out to be quite a bit larger than the same images I have saved locally.

For example, I have one local image that is 70KB. When I upload it into Assets it‘s 180KB. On the page itself it is being transformed like so:

{% set imgSize = {
    mode: 'crop',
    width: 960,
    height: 450,
    quality: 75,
    position: 'center-center'
} %}

That transformed image on the page is then 208KB.

So rather than optimising file sizes as I thought it did, my set up is making the files 3 times larger.

I have checked the server with phpinfo, and I can't see Imagick installed, but GD v2.1.0 is.

What can I do to prevent the images from becoming larger?


texts: No more than 10 blocks in globally used Matrix fields get saved

texts: When saving a globally used Matrix field, no more than 10 blocks (of the same type) get saved. The Matrix field has no max. Any ideas?


texts: Shortlist plugin error when creating a new list

texts:
I'm getting this error when I try create a new list:

CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 1364 Field 'userSlug' doesn't have a default value. The SQL statement executed was: INSERT INTO `craft_shortlist_list` (`default`, `public`, `type`, `ownerType`, `uid`, `ownerId`, `id`, `dateUpdated`, `dateCreated`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7, :yp8). Bound with :yp0=0, :yp1=1, :yp2='manual', :yp3='member', :yp4='8fb7840a-a399-4eb3-bdf7-c59cb656bbff', :yp5='1', :yp6=1698, :yp7='2017-04-24 09:11:47', :yp8='2017-04-24 09:11:47'

Some help would be greatly appreciated!


texts: Plugin for creating categories on an entry page in Control Panel

texts: Is there a plugin that allows to add a category via an entry page? I like how you're able to add categories in Wordpress admin right on a post page, not only via Categories section — this seems to facilitate the categorization of content by editors. It's possible that they'd rather skip the Assign a category button than do some extra work to create the required categories, and ability to enter new categories within the entry page would help to avoid that.


texts:
Is there any mechanism in Craft (or a plugin) which protects entries or assets from being deleted, if they are used in an asset / entry field used in an entrytype, global, ...?

Or is there a way to show how many relations an asset or an entry has? (I know some CMSs which show you the amount of "inbound" links to the assets and pages).

Thanks!


texts: I'd like a more personalized version of the offline page when the System Status is set to: Off. Is there a way to customize the page and/or change the text?


texts: Entry Post Date Format time since - X days ago

texts:
Is there anyway to get my date formats looking like Facebook? I'd like to get my articles to have this as a date format: "5 min ago", "yesterday", "3 days ago", "4 months ago" and then once it reaches a full year ago, make it have a date format like "Dec 5, 2016".

If anyone has gotten this working, would you mind sharing with me(and the world) your code on how to achieve this in Twig?

Thanks in advance!


texts: How to do "restricted page/asset"->login->register->"restricted page/asset"?

texts:
That question will almost certainly need to be rewritten, but at the moment I don't have the language to write it well (sorry).

We have a restricted item (asset, in this case) that successfully triggers the login form and then redirects the viewer to the restricted item after login.

What about if the viewer is not registered yet? We have a working registration form set up and auto-activation enabled. How can the referring restricted item be passed from the login form to the registration form and then have that restricted item shown immediately after registering?


texts: How to use Sprig's "Load More" Recipe After Update

texts:
This is a continuation of a previous question I had (Here). I am using Sprig's Load More Recipe. In my category page, I want the load more function to only pull up entries that equals the current category page. In a recent update, the category solution that was in my previous question no longer works, since it has been restructured a little. I cannot figure out how get the relatedTo(category) to work again. I currently have it set up like this (the {'relatedTo': category} does not do anything):
_category.twig
{{ sprig('_layouts/_blog/_categories/_loadMore', {'limit': 6},{'relatedTo': category}) }}
{{ sprig.script }}

_loadMore.twig
{% set offset = offset ?? 0 %}

{% set entries = craft.entries.section('caseFiles').offset(offset).limit(limit).relatedTo(category).all() %}

{% for entry in entries %}
   ------Entry Content-----
{% endfor %}

{% if entries %}
  {# Increments `offset` by the value of `limit` and swaps itself out on click #}
  <button class="orange-button" sprig s-vars="offset: {{ offset + limit }}"
    s-target="this" s-swap="outerHTML">

Load More

  </button>
{% endif %}


texts: Options not rendering on Sprout Reports report

texts:
My Sprout Report I just set up is not rendering the "options" template.

The results and options template both exists, and have been copied from the examples directory that came with Sprout Forms. This options template is rendered on the build in "Users and User Groups" report - but not on mine.

The only difference is my report has a data source of "Custom Twig Template" as opposed to "Users" - but that shouldn't matter.

The docs and the built in examples aren't shedding any light on the situation. Thanks.


texts: Craft 3 CMS How to get all Channel Names/Titles

texts:
I am trying to retrieve all Channel sections' names/titles.
This snippet contains the troublesome part.

{% set allSections = craft.entries.all() %}
    {% for section in allSections %}
        {% if section.getType() == "channel" %}
            {% set navBarLinks = navBarLinks|merge([section.title]) %}
        {% endif %}
    {% endfor %}

allSections contains all entries (I know I am looking for sections but I don't know how to loop all sections. craft.sections returns null, since it's deprecated from Craft 2). ex:

I can see the entry inside a channel 'webshop/overview'. But I want to get only the name of the channel ('webshop' in this case).
Also I have 2 other channels without any entries inside them.

navBarLinks currently returns null. I want it to contain the names/titles of the Channel sections regardless if they contain entries inside them.

P.S. I am doing all this so I can have a dynamic navigation bar(similar to breadcrumbs but not exactly). I know Structure will make my life a lot easier but it doesn't quite fit my needs.


texts: composer.json file not updating when plugins are updated

texts: My composer.json file doesn't update to the latest plugin versions when I update my plugins via the Craft CP or command line.


texts: How to use Class Reference Classes within the Craft framework for plugin development

texts:
I am attempting to lean how to write a plugin but am having trouble knowing how to work with the Class Reference documentation. I understand all of the theory and how object oriented programs work. But I have never actually worked on a real world problem. I have only worked on small programs to learn the concepts.

I am overwhelmed by the Class Reference and don't know best practices for attacking a new project and using the Class Reference documentation. I feel overwhelmed and stuck, and so my question is can an experienced developer or two share some guidance as to their methodology for working with a framework in the real world?

The plugin itself is conceptually simple. I'm working on developing a application similar to tinyurl.com.  I need to store data in a database table and then read it back. I also then need to then figure out how to do a redirect.

My main goal is to get the general guidance on how to approach any new project with regard to how to start. Any guidance on the specific problem is also appreciated.


texts: Good Evening im having issues with the latest version of FreeForm on Craft3.  It appears no return URLs are being generated based on the field within the form builder.  When looking at the form in source view on the browser, it doesnt appear in the form code.  Can anyone suggest what maybe causing this issue? #solspace #freeform


texts: Is it possible to show commerce product id's in the control panel?

texts:
For entries you can show the ID in control panel listings.

I can't find a way to show craft commerce product ID's in a similar way in the control panel.
Commerce 3


texts:
This may be a simple question but I am not sure how to approach it - again trying to work out best practice for these things!

I have a "single" at /our-work, which among other things displays a projects listing - basically a list of links to the full entry for that project.

I now wish to filter that listing by the category they are in. I also wish to update the URL to reflect that filter e.g. /our-work/branding.

I have got the below code - listing out all the projects with their links, and also outputting the category links for the filter. When the links are clicked I currently I get an error - unsurprising considering the page doesn't exist.

How can I best achieve both the filtering and the required url change? Any help or pointers gratefully received by a craft beginner!

{% extends "_layouts/main" %}

{% block main %}

{% set categories = craft.categories.group('projectType').level(1).all() %}

{% for category in categories %}
  {{ category.title }}
{% endfor %}

{% for project in craft.entries.section('projects').all() %}

    {{ project.title }}

{% endfor %}

{% endblock %}


texts: Trouble with buildElementQuery customization

texts:
I’m having a problem modifying an ElementCriteria with buildElementsQuery.
The results elements totally mixes locale results. I can only get english URL for example.

Here is a gist of my code.
https://gist.github.com/nicolasbinet/7e3835b13c3e9c21d2fa754243242b41

is there something particular to do when using buildElementQuery ?

Nicolas


texts: How can I have translations for my subdomain

texts:
I setup Craft with one domain-1, now domain-1 has sites domain-1Global and domain-1NL. On this domain, the translations work perfectly.

But now I added a second domain, domain-2 with the sites domain-2Global and domain-2NL. When I access the base url from the domain-2NL I get the template for the homepage of domain-1NL.

I tried removing the define('CRAFT_SITE', 'domain-1'); in the web folder, this worked for a while but ultimately failed. Does anybody know a different solution?


texts: Using 'replace' with a regex is throwing an error. Any ideas why?

texts:
I am attempting to strip out <p> tags around <img> tags that are automatically getting generated in a WYSIWYG field.

The error: preg_replace(): Unknown modifier '&gt;'

{{ story.html|raw|replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU','\1\2\3') }}

Thanks!


texts:
I have a dynamic navigation consisting out of matrix and entries fields:

This then gets printed on the frontend as a dropdown.

No is it somehow possible to add a active class to the dropdown toplevel button?

Basicaly passing the active state back up to the toplevel button.

{% for dropNavi in block.dropdownNavi %}
   {% if loop.first %}

           {{ block.seite }}

   {% endif %}

    {{ dropNavi.title }}

  {% if loop.last %}
{% endif %}
{% endfor %}

The problem is that this is a matrix field so there could be 3 or 6 or 5 dropdowns. Therefore the {{ loop.index }} does not work as a identifier. I can't see a way. Is this even possible?

I tried things like
 and various versions of this.

But stuff like this aplies an active class to all the dropdowns present. Never on the one containing the current url.


texts: What's the correct way to relate element types to a custom element type?

texts:
I'm working on a custom stock management plugin for a client's Craft Commerce site, and I need to have relations from my custom element type (used to keep a detailed log of stock changes) to the products and variants, and the user or order that modified the stock.

I've looked at the Events plugin, as well as Craft & Commerce's source code, but I'm still struggling to write my modifyElementsQuery in such a way that allows me to access the content of these other elements without directly joining from the content table (which seems like a terrible way of going about it).

What's the right way of relating two element types together? Is there any example code I can look at (either in Craft core, or an open-source plugin)?


texts:
I'm trying to do something like this for all the SEO meta info in my head

{% if entry or category is defined %}
 ...
{% endif %}

What's the right way to code this?

The reason for this is I have archive pages which won't be using some the meta information.


texts: I'm setting up Craft to be used headlessly with a mobile app, and content will be created several days before it is published. I want app admins to be able to see upcoming/pending entries. Is there a way to fetch all entries, not just currently published ones? When I do basic queries with the GraphQL api explorer I only see entries that are past their post date, but I'm a GraphQL newbie, so maybe I'm missing something?


texts: Get entries by custom matrix / date time field

texts:
I want to list all entries in a section by custom date time fields.

A training course has a From field and a To field. These fields are inside a Matrix field.

The field name storing this info is called trainingDateTime.

The Matrix block is called trainingDateTimeDateTime.

The Matrix fields in this block are called and dateTimeFrom and dateTimeTo both datetime fields.

My entries loop so far is:

{% set entries = craft.entries.section("training") %}

I know you can do order entries by a custom datetime field using something like:

{% set entries = craft.entries.section("training").customDateTime.('>= ' ~ now).order('customDateTime DESC') %}

But since I'm using a matrix field I'm unsure how to approach this.

I'm wanting to show all upcoming training courses from the current month up till the next 2 months.


texts: What's wrong when entries appear again after save?

texts: Entries should be live and say so in the CP, but they where gone in a listing in the frontend. But after saving entry by entry they appear again. What could be wrong?


texts: Updating user profile matrix block with plugin

texts:
I've written a plugin to update some user profile fields via ajax. It works great for normal text fields like this 'myWooly' field, ex:

<?php
namespace Craft;

class ProfileUpdateController extends BaseController
{
    protected $allowAnonymous = true;

    /**
     * updateWooly
     */
    public function actionUpdateWooly()
    {
        $this->requireAjaxRequest();

        $post = craft()->request->getPost();

        // get current user's profile info
        $currentUser = craft()->userSession->getUser();
        $profile = $currentUser->getContent();

        $currentUser->getContent()->myWooly = $post['myWooly'];

        if (craft()->users->saveUser($currentUser)) {
            $response = 'success';
        }
        else {
            $response = 'error';
        }

        $this->returnJson($response);
    }

I've created a Matrix field with each block having its own Wooly, ex:

Kids (Matrix field)
 - kid (block type)
  + firstName
  + wooly
 - kid
  + firstName
  + wooly
 - etc.

...and now I need for users to update the 'wooly' within each Matrix block.

I've updated my AJAX call to POST a Matrix Block ID and updated my actionUpdateWooly() action to the following:

    public function actionUpdateWooly()
    {
        $this->requireAjaxRequest();

        $post = craft()->request->getPost();

        // get current user's profile info
        $currentUser = craft()->userSession->getUser();
        $profile = $currentUser->getContent();

        // SAVE WOOLY IN KIDS MATRIX FIELD
        if (isset($post['kidId'])) {

            $kidsMatrix = craft()->fields->getFieldByHandle("kids");

            $kidsMatrixBlocks = craft()->matrix->getBlockTypesByFieldId($kidsMatrix->id);
            foreach ($kidsMatrixBlocks as $key => $data) {
                if ($data->handle === "kid") {
                    $kidBlock = $data;
                    break;
                };
            };

            $block = new MatrixBlockModel($post['kidId']);
            $block->fieldId    = $kidsMatrix->id; // Matrix field's ID, 'Kids'
            $block->ownerId    = $currentUser->id; // ID of entry the block should be added to
            $block->typeId     = $kidBlock->id; // ID of block type, 'kid'
            $block->getContent()->setAttributes(array(
                'wooly' => $post['myWooly'],
            ));

            $response = craft()->matrix->saveBlock($block);

        }

        // WOOLY STORED AT TOP-LEVEL OF ACCOUNT
        else {
            $currentUser->getContent()->myWooly = $post['myWooly'];
        }

        if (craft()->users->saveUser($currentUser)) {
            $response = 'success';
        }
        else {
            $response = 'error';
        }

        $this->returnJson($response);
    }

This is successfully CREATING NEW matrix blocks in the correct field, but it's not UPDATING the one I'm expecting.

I would expect this to get the Matrix block by ID but apparently it's not:

$block = new MatrixBlockModel($post['kidId']);

Yes, I've made sure the Matrix Block ID

Can anybody spot what I should be doing differently to get a specific matrix block and updated it within a user profile?


texts: How to display an entry on frontend with status disabled if admin is logged in?

texts:
Something like this?

{% if craft.session.isLoggedIn %}
    {% set slug = craft.request.lastSegment %}
    {% set entry = craft.entries.slug(slug).status(null).first %}
{% endif %}

{{ entry.title }}

But I get error page not found.


texts: Find structure entries which parents relate to other entries

texts:
I want to select all children of all entries that fulfil specified relation parameter.

I have tried this, but I think .isDescendantOf only supports single entry. Is this even possible?

{% set parents = craft.entries.section('training').level('1').relatedTo(relationParam) %}
{% set children= craft.entries.section('training').isDescendantOf(parents).eventDate('>= ' ~ now).order('startDate DESC') %}

I thought giving more background to this might help, as possibly an entirely new approach will be necessary. Consider this setup in Craft CMS

I have a 2 level structure, where top level is a big matrix describing an event and has quite a big classification section where multiple categories are selected. Then it's children are specific instances of that event with their own date and location.

I don't want to force my client to repeat categorization on each of the lvl2 entries since they've already done it on lvl1.

Can I select all lvl2 entries that have parents fulfilling specific relation param?


texts:
I have a section called reviews and a section called games.
A entry field in games is creating a relationship to reviews.

On my _entry.html entry for reviews, I want to link back to the related game.

My code is below. I understand why it isn't working, but not sure how to fix it.

The template displays the Review entry title, the body some extra fields in reviews.

And then gets to the Game Link, but the link is not to my Games section but to my Reviews section.

In other words, on this review:
http://www.colorcomputergames.com/reviews/1984-01-01/glaxxons

The link at the bottom should be to:
http://www.colorcomputergames.com/games/glaxxons

But instead, goes to:
http://www.colorcomputergames.com/reviews/1984-01-01/glaxxons

{{ entry.title }}

    {% if entry.ReviewsAuthor|length %}
Reviewer: {{ entry.ReviewsAuthor }}
{% endif %}
    {% if entry.ReviewsMedia|length %}
Media: {% for category in entry.ReviewsMedia %}{{ category.title }}{% endfor %}
{% endif %}
    {% if entry.ReviewsDate|length %}
Date: {{ entry.ReviewsDate.format('F Y') }}
{% endif %}
    {% if entry.ReviewsRelatedLink|length %}
Related Link: {{ entry.ReviewsRelatedLink }}
{% endif %}

{{ entry.body }}

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

Game Link:

{{ entry.title }}

As mentioned, in section called Games, I have a field called GamesReview and set it to entries and assign the review entry. Do I need to do the opposite as well t make this work? That is, in my reviews section, create a field called GameReviewed and set it to entries and assign it to Games section.

Thanks


texts: New user has activated account but is getting this message when trying to log in: "you cannot access the CP with that account"


texts: How do I filter entries by month using custom Date/Time field and paginate them?

texts:
Here is how I am filtering entries by a specific month:

{% set filterId = "July" %}
{% set allEntries = craft.entries.section('messages') %}
{% set filteredEntries = [] %}

{% for msg in allEntries %}

  {% if msg.messageDate | date('F') == filterId | date('F') %}
    {% set filteredEntries = filteredEntries | merge([msg]) %}
  {% endif %}

{% endfor %}

{% set messageList = filteredEntries %}

How can I paginate messageList? Do I need to filter by month a different way for pagination to work?


texts:
I have a title field with value: "Nobel Participatie Portefeuille".

On my template I want to trim the word "Nobel", You can do this with twig trim.

so this is my code:

{{ entry.title | trim('Nobel ') }}

But my output is "Nobel Cashflow Portefeui" (missing "lle")

Other words work normal.


texts:
Anyone have an idea on how to incorporate a service mark (SM) into the title of an entry? I've tried just doing SM, tried the code for SM & # 8 4 8 0 ; (without the spaces), and nothing works. I even tried creating a new rich text field so I could do it there and have a conditional to show that field instead of the title field, but that makes it so that it can't be used in different headline tags on different pages, as its auto-enclosed into a pargraph or h3 or whatever.

Any thoughts or ideas are greatly appreciated!!


texts: Is it possible to detach event listeners?

texts:
I've got an event listener hooked up like this:

craft()->on('elements.populateElement', array($this, 'onPopulateElements'));

Is it possible to detach/deregister the listener? E.g. something like this (this doesn't work, but to illustrate):

craft()->off('elements.populateElement', array($this, 'onPopulateElements'));


texts: How do I print the last level of a category?

texts:
Some categories have 2 levels, some only have 1 level.

How can I print the "last" level of an entry if for some it is level(2) and others it is level(1)?


texts: Is it possible to add a Section, Entries in basic/simple HTML page instead of Twig template?

texts: In Craft CMS is it possible to add a Secion, Entries in basic/simple HTML page instead of Twig template?


texts: Craft SeoMatic GTM  disable on 404 pages

texts:
I want to disable google tag manager on 404 templates, I am able to add the additional condition for the script "Google Tag Manager Settings"

It has stopped GTM script code, but <noscript> tracking is still rendering on the page.

Is their way inside plugin options/SeoMatic template variable, soi can hide <noscript> code as well on specific pages


texts: Save same Entry more than once with help of custom relations field

texts:
Is it possible to save the same Entry (red arrow) twice/more than once in one custom relations field?

"Test Playlist" is a entry in a channel.

Background:

I have set up a playlist, where an entry should be saved more than once.


texts: RelatedTo relation - checking matrix block status is enabled

texts:
I need to search for all commerce variants related to a custom element "Account".

The account element is related to a variant through a matrix field with handle
varientaccountmapping, block handle mapping field handle account

{% set allowedVarients = craft.variants().relatedTo({
    targetElement: accountElement,
    field: 'varientaccountmapping.account'
}).all() %}

works, however it returns results whether the matrix block is enabled or disabled - ignoring the status.

How can I get this to return only results where the matrix block it is related to is enabled?


texts: How do I list the tag groups that are actually in use?

texts:
I'm developing a masonry photo gallery with some filters (colors, style, manufacturer, etc) and I want to use tags to filter them by. I need some navigation which should look like this:

Tag Group 1

Tag 1

Tag 2

Tag Group 2

Tag 3

tag 4

I read this article https://craftcms.com/support/active-tags but I can't figure out how to get all group tags and for them all the tags that are actualy in use. I think i should use

{% for tag in craft.tags.group('blogTags') %}

but I want to get all the group handles in a loop dynamically.


texts: How do I import existing products into Craft Commerce with the FeedMe or Import plugins?

texts: I get it that there are hooks, but i can't get enough inside the differences between entries and product, and actually hack together an extension for either of those plugins.


texts:
I'm trying to get data submitted from a form using craft()->request->getPost(), but I'm not sure what to do when the form name is an array element.

For example, I have a form with:

<label for="notes">Notes</label>
<textarea rows="6" id="notes" name="fields[notes]"></textarea>

and want to use:

craft()->request->getPost('fields[notes]');

but when I do this I don't get any data from the form, and I'm not sure what to put in getPost() to let it know its an array.

It will work fine if I change the name to "notes" and use getPost('notes'), but I'd like to be able to get it working with the array.


texts: Setting arbitrary PHP constants in index.php

texts:
I was looking for a way to set arbitrary PHP constants in the index.php that could then be accessed within templates.

This is particularly useful if you have more than one index/domain pulling content from a core Craft install as the additional domains won't have any configuration files to use, just index.php.


texts: Multi-Language Site but the Date should be always in English

texts:
with {{ block.timeLimit|date('M d Y H:i')}} i can get the real Date & Time in always the real Language from the Site.
If the Page is German output is Dez, in English output is Dec.

How can i set the output of this Date always to en? Whatever language the Site has?

Thanks for every help!


texts: Filter Entries by Category fields & refresh URL and list with AJAX

texts:
I'm finding myself stuck with filtering entries that are related to categories using a category field. I'm looking to build a sub-navigation on a page, where I can select from a select field or from a dropdown nav.

I tried following this but no luck. It doesn't work for me.
How to load entries via ajax when a filter is clicked?

I also would love to have 2 or 3 category fields. In the end, I am trying to create something very similar to crafts partner page filtering.
https://craftcms.com/partners/category?locations=&partnerCapabilities=

If anyone could share their filtering snippets, I would greatly appreciate it :)


texts: How to set view path for rendering email templates?

texts:
Trying to send an email

Craft::$app->setViewPath('/Users/stian/dev/site.com/templates/');
Craft::$app->mailer->compose('confirmation.twig', ['orderId' => $orderId, 'customerId' => $customerId])
    ->setFrom('me@me.com')
    ->setTo('me@me.com')
    ->setSubject('hey')
    ->send();

Getting The view file does not exist: /Users/stian/dev/site.com/vendor/craftcms/cms/src/mail/confirmation.twig

Assuming I correctly understand how to render a view for sending as an email, how can I correctly point to its location?


texts: Sort entry titles alphabetically excluding 'The'?

texts:
I need to list the names of all of my entries in alphabetical order excluding 'the' (which could only be at the beginning). I've looked around online, but I was only able to find a code segment (which I've modified to fit my needs). However, it's still incorrectly sorting them as you can see in the attached image.

Current code:

{% for entry in craft.entries.section('partners').featuredMediaPartner('1').order('(CASE WHEN title LIKE "The %" THEN SUBSTRING(title, 3) ELSE title END ) asc') %}

Please help me fix this issue, thanks.


texts: What accurately will set asset paths for multilingual sites?

texts:
This is actually a fairly crucial matter, since relative paths definitely won't work with languages, unless you really want all assets in a given Source to be localized or at least copied to each language folder. As well, hard paths in the CP will fail with multi-environment config where dev, staging, and deployment sites can have different full storage paths.

Things may appear to operate at first with relative paths, for example, and it may feel like a safe way from experience with other systems, but then you'll find that features like automatic generation of image transforms that you've set up (icons, controlled sizes, etc.) will fail.


texts: How to prevent select user groups from reordering structures

texts:
I need to create a plugin that prevents select user groups from reordering a Structure content type in the Entries listing. I could quickly do this by just hiding the a.move.icon element, but I worry about the longevity of this solution. For example, if this class were to change then the plugin wouldn't hide the element any longer.

Is there a better, more long-term fix that someone might recommend here?


texts: Undefined this.$overflowTabBtn.data(...) initTabs Craft.js:11326:51

texts:
I'm getting this error on one Solspace calendar (2.x) event entry form, but not another. The only difference seems to be two asset fields, and one entry reference field. It's the only page the error occurs, and it just cropped up after the 3.4 update.

TypeError: this.$overflowTabBtn.data(...) is undefined in
    initTabs Craft.js:11326:51

Update 2020/02/24:
I confirmed that it was a conflict with the Craft 3.4 update and entry, and asset, reference fields on an event.


texts: How can I create an ElementCriteriaModel with 'and' and 'or'

texts:
In my template, I want to:

Get all the entries in the section 'uploads';
Get all the assets that are related to one of the upload entries, and have a relation to all the tags I provide.

So, that would be:

{% set company = craft.entries.section('company').id(companyId).first() %}
{% set uploads = craft.entries.section('uploads').relatedTo(company).limit(null) %}

{% set relatedToUploads = ['or'] %}
{% for upload in uploads %}
    {% set relatedToUploads = relatedToUploads | merge([upload.id]) %}
{% endfor %}

{% set relatedToTags = ['and'] %}
{% for tag in tags %}
    {% set relatedToTags = relatedToTags | merge([tag.id]) %}
{% endfor %}

But, how would I combine those two relatedTo-arrays to one, usable in the ElementCriteriaModel for the assets?


texts:
I have a template where I would like to pass a search parameter to a craft.entries.section in an included template. The current main template has this:

{% include "_includes/testimonial" with
  { type: "agency" }
  %}

Then in the include I have this code where entry.clientsOrAgency is a dropdown field and I want it to only show results of the "type" passed in the parent template.

{# get one random testimonial entry #}
{% set testimonial = craft.entries.section('testimonials').search(entry.clientsOrAgency,type).order('RAND()').limit(1) %}

{% for quotes in testimonial %}
<div class="testimonial">

  {# matrix field is 'testimonial' - find different quote types #}
  {% for quote in quotes.testimonial %}
    more code here
  {% endfor %} {# quotes.testimonial #}

</div><!--testimonial-->
{% endfor %}{# quote in testimonial #}

The above code results in a template error Undefined index: query

Not sure how to resolve this.


texts: Excluding properties from returned ElementModel in plugin

texts:
We are building a React application for a client, where we are using Craft as the API/Backend. I am building the API as a custom Craft plugin, which will return specific JSON data to React, dependent upon the action route it requests.

I was wondering if there was a way that anyone has managed to prevent the default Entry properties from being included in the response, as it just adds a lot of unnecessary clutter. I have included a visual example at the bottom of this question to further clarify what I mean.

I did try to research if this was answered already, and found this link Ignore fields in search index
I did see it was back in 2016, so was hoping something has changed.

Example:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = "journeys";
$journeys = $criteria->find();

$responseObj = new \stdClass;
$responseObj->journeyOne = $journeys[0];
$this->returnJson($responseObj);

I literally won't be using any of these, as I only require the data from my custom fields(which haven't been created yet).


texts: Breaking one large Craft app into multiple smaller apps

texts:
Some background information:

We use a Craft app that has several modular components that we've put into separate plugins. IE: a purchase plugin, "logged in" plugin, and so on.

I'm thinking of breaking this very large app into multiple smaller Craft apps which would be able to be deployed independently to AWS instances. This way when we make a change to our Purchase flow we no longer need to redeploy the entire app /remove-headaches.

I've been looking around and haven't found much on terms of people doing this with Craft? The instances would all share the same database instance since we don't store any data in the database anyways so that wouldn't be an issue... but is it just as simple as including the /craft and /public folder on every instance? How would these apps access each other's functions? So if the Purchase Plugin needs to access something from the "Logged in" plugin on the other app it would need to be via HTTP request which would hit the other app's index.php and go from there? I guess we would need to build a gateway for these apps to speak to each other if we need to do cross-app talk?

This is what I was thinking it would look like:

Remove "Purchase plugin" from the original repo.
Create a new repo for purchase app
Plug the "Purchase plugin" into the new app which only has the necessary folders for Craft to run. Ie: craft and public folders with only this one plugin.
Create a gateway for requests coming from "Logged in" app and "Purchase app" to correctly direct to the other app for cross-talk. This would route purchase app requests to logged in app if/when it needs to access something.
These craft instances would point to the same database that has data about all plugins. Or would it be better to each have it's own database? Is this something that would become hectic to maintain for business partners?

Essentially I'd be creating an "API" out of these two apps. They would both be ale to stand independently and the implementation can change for either one so long as it fulfills its contract. This would allow me to deploy them separately and have separate teams maintain them without worrying about something in one app being broken because of something in the other app being deployed.


texts: Upload user profile image from custom plugin controller

texts:
Im trying to upload a profile image from a front end form via a controller function

this is what i have but the $image keeps returning null?

<form name="updateProfile" method="post" enctype="multipart/form-data">
     <input type="hidden" name="action" value="salesforce/saveContact">
     <input type="file" name="photo" id="avatarUpload">
     <input type="submit"/>
</form>

and my controller action is

public function actionSaveContact()
{

    $this->requirePostRequest();

    $userPhoto = craft()->request->getPost('photo');

    $user = craft()->userSession->getUser();

    craft()->users->saveUserPhoto('test.jpg',$userPhoto, $user);

}

Not sure what im doing wrong?


texts:
Originally at Include a template that sets variables (global template variables).

I have a number of templates and layouts but every layout includes a global header in which the meta data is displayed.

That data always comes from the entry you are viewing and currently I'm setting the variables the global header needs in each template, such as /news/index.html:

{% extends "_listing_layout" %}

{% set metaTitle = (entry.metaTitle) ? entry.metaTitle : entry.title %}
{% set metaDescription = entry.metaDescription %}
{% set metaKeywords = entry.metaKeywords %}
{% set metaRobots = entry.metaRobots %}
{% set openGraphImage = entry.openGraphImage.first() %}

{% if openGraphImage %}

    {% set ogCrop = {
        mode: 'crop',
        width: 1200,
        height: 630,
        quality: 75,
        position: 'center'
    } %}

    {% set openGraphImage = openGraphImage.getUrl(ogCrop) %}

{% endif %}

{% set listingSection = "newsArticles" %}

{% block content %}

    <h1>{{ entry.title }}</h1>

    {% include '_partials/_isotope.html' %}

{% endblock %}

The layout is super simple:

{% include '_partials/_global_header.html' %}

    {% block content %}{% endblock %}

{% if craft.request.firstSegment %}

    {% include '_partials/_global_footer.html' %}

{% else %}

    {% include '_partials/_home_footer.html' %}

{% endif %}

And then the global header partial:

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en-gb" dir="ltr" class="no-js"> <!--<![endif]-->

    <head>

        {# meta #}
        <meta charset="utf-8">
        <title>{% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}</title>

        {# seo #}
        <meta name="description" content="{% if metaDescription is defined %}{{ metaDescription }}{% endif %}">
        <meta name="keywords" content="{% if metaKeywords is defined %}{{ metaKeywords }}{% endif %}">
        <link rel="canonical" href="{{ siteUrl }}">
        <meta name="robots" content="{% if metaRobots is defined %}{{ metaRobots }}{% else %}index,follow{% endif %}">

        {# open graph #}
        <meta property="og:site_name" content="{{ siteName }}">
        <meta property="og:type" content="website">
        <meta property="og:title" content="{% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}">
        <meta property="og:url" content="{{ siteUrl }}">
        <meta property="og:image" content="{% if openGraphImage is defined %}{{ openGraphImage }}{% else %}{{ siteUrl }}images/og-default.jpg{% endif %}">
        <meta property="og:description" content="{% if metaDescription is defined %}{{ metaDescription }}{% endif %}">

...etc

How can I keep this variable code DRY? I've tried putting direct in the header partial and layouts, but that doesn't work. And putting it in an included partial within each template throws a template error on account of the fact the template extends a layout and can't have a body.


texts: Ajax Post to guestEntries/saveEntries from another domain

texts:
I have a separate Craft install that I am using to communicate to a few different sites. I have a front-end form on another one of these sites (a React.js app) that is looking to post back to this initial Craft install.

My form looks pretty standard:

<form method="post" action="" accept-charset="UTF-8" onSubmit={this.handleSubmit}>
    <input type="hidden" name="action" value="guestEntries/saveEntry"/>
    <input type="hidden" name="sectionId" value="3"/>

    <input id="name" type="text" name="fields[name]" required />
    <input id="userEmail" type="email" name="fields[userEmail]" required/>

    <input type="submit"/>
</form>

handleSubmit() also looks exactly the same as the docs for ContactFormEntries:

handleSubmit(event){
    event.preventDefault();

    var data = $('form').serialize();

    $.post(config.default.apiUrl, data, function(response){
        if(response.success){
            $('body').addClass('success');
        }
        else{
            alert('Sorry, there was an error with your submission. Please validate your submission or try again later.');
        }
    });
}

where config.default.apiUrl = the root url for my Craft app.

My data goes through as a POST request (302 Found) followed by an immediate GET request of '/' (200 OK) where response is the markup from the root of the Craft install.

The kicker is that the data is saved in the database correctly, but the response (and the subsequent GET request) isn't really what I'm looking for. I'd love for it return with a proper json response. I've attempted to include a redirect parameter, but the result is the same.

Is there something I am missing in my ajax request that would throw this off?


texts: Create VanillaForum topic from new piece of Craft content?

texts:
Craft is looking perfect for a new project I'm starting, but I can't find a good way to integrate a key part of the site. I'll be creating content pages for each individual project that I'm featuring on my website. Ideally, Vanilla would be embedded below the page content and showing the relevant discussion thread.

It seems so simple but I'm having a tough time finding a good solution. Can anyone point me in a direction?


texts: Getting Matrix field ID and Block ID for my Custom Field

texts: I have a custom field that will be saving data to its own table. So if my field is in a Matrix field, I need to save the Matrix Field ID and Matrix Block ID to my table so I know what the data belongs to. I’m having a hard time figuring out how to get that data in my fieldtype. I’m using the onAfterElementSave method. I’ve been looking for attributes and types and whatnot on $this, $this->element->getType(), $this->element->getType()->getAttributes() and so far I’m just not having any luck finding this information. Can anyone point me in the right direction here?


texts: Can entries in a category be reordered in a similar way that entries in a Structure can be reordered? If not, how can entries in a category be reordered manually?


texts: Error with database while trying to setup the GeoMate plugin

texts:
I want to use the GeoMate for some country settings, but I'm having this error 'No database found! Please check the settings below, and download the GeoIP2 databases.'. I have generated a license key from the MaxMind. Not sure what's wrong with the setting.

Here is my setting for geomate.php
<?php
/**
 * GeoMate plugin for Craft CMS 3.x
 *
 * Look up visitors location data based on their IP and easily redirect them to the correct site..
 *
 * @link      https://www.vaersaagod.no
 * @copyright Copyright (c) 2018 Værsågod
 */

/**
 * @author    Værsågod
 * @package   GeoMate
 * @since     1.0.0
 */
return [
  '*' => [
      'countryDbDownloadUrl' => 'https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-Country&license_key=license_key&suffix=tar.gz',

      'cityDbDownloadUrl' => 'https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&license_key=license_key&suffix=tar.gz'
  ]
];


texts:
I've got a site-wide search box (based on the example in the documentation). It's doing a good job of searching through the entries, but is there a way that I can include a search through a user group like authors as well and include it in the same list of results?

Currently I just have this but its not getting any results for author searches even though I know they exist. It seems like the authors should be searchable since they're linked to the entry...

{% set entries = craft.entries.search(query).order('score') %}

If I did another search through craft.users.search I could get another list of results, but I'd like to have one combined list. Is something like that possible?


texts: Does Craft enforce a maximum filesize for large files?

texts:
A client we're working with has a requirement to upload one large file (about 320MB) every 2–3 months. Craft has been configured with a local asset source to handle this.

I'm trying to decide the best way to approach this: whether we upload this large file via SFTP for them when required, or if the client can do this through Craft in their own time.

This previous question provides some good pointers. I've increased the necessary settings, however when attempting to upload a test file (315MB), Craft displays an alert ‘The file “testfile.zip” could not be uploaded, because it exceeds the maximum upload size of 128.0 MB.’

I haven't seen any filesize limits of 128MB, so is this value hardwired into the file upload logic? To confirm that the changed settings do work, a test file of 100MB was uploaded fine.


texts:
Im implementing Donate Fast plugin, but its documentation pages don't work (at 30/11/2020), does anyone have a sample code? I just want to know the ids used in the bank card details (in the form), in the repository only the input of the amount is shown.
Thanks!


texts: Install button not visible in Plugin Store

texts:
I added my user to a user group that had every permission checked. I also looked at general.php and there was nothing about allowUpdates, so I added allowUpdates = true, but neither of these things helped.

I was not the person who installed this site, is there anything else that might cause the plugin store to lack install buttons?


texts: Because of some restrictions, some popular software (even Wordpress is a challenge) can't be run on NearlyFreeSpeech.NET. Can Craft be run on NearlyFreeSpeech.NET?


texts: Customise errors when validating model data?

texts:
I’m trying to set a custom message for a specific model attribute. I have something like this:

protected function defineAttributes() {
    return array(
        'attributeOne' => array(
            AttributeType::String,
            'required' => true,
            'label' => 'Attribute One Label'
        ),
        'attributeTwo' => array(
            AttributeType::String,
            'required' => true,
            'label' => 'Attribute Two Label'
        )
    );
}

How can I customise a specific error message for each attribute so that instead of ‘Attribute One Label cannot be blank’, I get ‘Attribute One Label with my custom message’?


texts:
I've created an asset volume to which I can successfully upload jpgs, pngs, static webps etc. But when I try to upload an animated webp I get the alert:
Upload failed. The error message was: “The file “example.webp” does not appear to be an image.”

The file is an image and I've tried various different animated webps. It seems to just be them specifically. Weirdly, if I copy and paste the same animated webp into a redactor field it displays there and animates and saves fine. Does craft not supported animated webps as a file type or do I maybe need to change something in my config?


texts: Newly added child entries not showing on listing/parent page straight away

texts:
I am running into an odd issue where creating new child entries does not bust the cache of the parent page(s) that lists them.

This is the structure I am working with:

I am displaying the Course entries on the Course Landing Pages like so:

{% cache using key craft.request.path %}

  {% set currentPage = craft.entries.id(entry.id).first() %}

  {% set entries = craft.entries({
    type: 'course',
    descendantOf: currentPage,
    with: [
      ['courseThumbnail', {
        withTransforms: [
          { mode: 'crop', width: 800, height: 800, position: 'center-center', format: 'jpg' }
        ]
      }]
    ]
  }) %}

  {% for entry in entries %}
      {% include '_includes/_listing-item-course' with { featured : true } %}
  {% endfor %}

{% endcache %}

When I publish a new Course entry, the cache for the parent page(s) is not busted and the new entry will not show unless I move/drag into a new position. This seems to clear the cache and the new entry shows on the parent page(s).

If I change the craft.entries call to not include the descendantOf part, so it looks like this:

 {% set entries = craft.entries({
    type: 'course',
    with: [
      ['courseThumbnail', {
        withTransforms: [
          { mode: 'crop', width: 800, height: 800, position: 'center-center', format: 'jpg' }
        ]
      }]
    ]
  }) %}

Then newly added Course entries will show up straight away on all the Course Landing Pages.

Why is that?


texts:
Is there any way to include the JSON response from element API in a template. Let's take the following example:

/case-studies.json returns:

{
    data: [
        {
            title: "American Express",
            color: "#0000ff",
            url: "http://localhost:3340/index.php?p=case-studies/american-express"
        },
        {
            title: "Bosch",
            color: "#ffffff",
            url: "http://localhost:3340/index.php?p=case-studies/bosch"
        }
    ]
}

I want to known if I can include this JSON object into my template case-studies/index.html, so it looks like:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <...>

        <script>
            window.data = [
                {
                    title: "American Express",
                    color: "#0000ff",
                    url: "http://localhost:3340/index.php?p=case-studies/american-express"
                }, {...}
            ];
        </script>
    </body>
</html>

I just wanna avoid the first ajax call when I load the page for the first time by including the data in the HTML body. Further on, I will use Ajax calls instead.


texts: Custom ENV Variable for Conditional Stripe Keys

texts:
I'm trying to define the Stripe Keys based on what the current environment is set to, so I can use the test keys when in Dev and the live keys when not.
I dont seem to be able to define the keys using custom variables in the env file. Adding conditionals to the key fields in the setting also doesn't work.
Any solutions?
Not a big deal but seems handy.


texts: Craft 2, MySQL database, Twig, JavaScript files

texts:
I have created in Craft 2 CMS, under the profile of users (ex. parents), new tab for (children), where parents can fill in there children information.

The data is saved in a database under the craft_content

How can I use the dropdown in a Twig file, data for child to be shown?

Can anyone help with the code?

I have installed Neo plugin in Craft CMS


texts: Craft 3.1 Beta - Email settings and categories not working

texts: I'm getting an "UnexpectedValueException" on the pages /admin/settings/categories/new and /admin/settings/email after updating to the beta.


texts:
I'm migrating a Craft 2 site to Craft 3 via rebuild. I've copied the assets over to the new site and indexed the upload directory - that all went well.
However, after doing this and working on other parts of the site I discovered that in the Craft 2 site all the assets had a redactor field attached to them. Is there a way in Feedme to copy over this data when the assets don't have the same asset id?
Sean


texts: How do I get model/record attributes in their proper types, and not just strings?

texts:
Here's my record (model is nearly identical):

namespace Craft;

class Recurly_PlanRecord extends BaseRecord
{

  public function getTableName()
  {
    return 'recurly_plans';
  }

  protected function defineAttributes()
  {
    return array(
      'sortOrder'      => AttributeType::SortOrder,
      'code'           => AttributeType::String,
      'max'            => AttributeType::Number,
      'min'            => AttributeType::Number,
      'annual'         => AttributeType::Bool,
      'base_endpoints' => AttributeType::Number,
      'endpoint_code'  => AttributeType::String,
      'base_cost'      => array(
        'type'     => AttributeType::Number,
        'decimals' => 2,
      ),
      'endpoint_cost'  => array(
        'type'     => AttributeType::Number,
        'decimals' => 2,
      ),
    );
  }
}

In the DB, the column types seem to be set correctly based on this.
What I can't figure out how to do, is actually get data back in the specified types, not just strings.

Here's me using it in a service:

$record = Recurly_PlanRecord::model()->find();
var_dump($record->attributes); // all strings :(
var_dump($record->base_cost); // string '1402.50' (length=7)

$model  = Recurly_PlanModel::populateModel($record);
var_dump($model->attributes); // all strings :(

What I want is float 1402.50. What I get is a string.

I'm having the same problem with AttributeType::Bool.

What am I doing wrong?


texts:
I have an existing CMS website that seemingly has been working fine for several months.  Just recently we have lost the ability to access the admin portion of the site (the rest of the site works well).  To our knowledge, nothing has changed to make the site behave differently.

We have since set up our own dev box with identical code and it seems to behave the same way.  Works one day, next day we can't log in.  No errors in browser or log files.  Browser cache and cookies cleared.  Different browsers all work the same way.  You log in, it blinks a second, then redirects to login.  If wrong password entered, we get the wrong password error.  Even the database seems to show our login was good.

We have multiple environments on the original site, only the production environment has this issue.  Our second environment only has the production environment so i don't think they are conflicting.

Only thing i can think of is nginx cache but we don't cache the admin directories.  I don't see anything different in .htaccess that would do this.

Any ideas?


texts: Localized Environment Variables Based On siteUrl?

texts:
I am setting up a multi-language site so far so good - everything is pretty obvious what to do.

I am curious if there is a way/best practice to have the environmentVariables array configured so that it knows which key to use based on the current siteUrl key?

I realize the syntax is incorrect/wrong but this is just an example:

'.dev' => array(
    'siteUrl' => array(
        'en' => 'http://local.mysite.dev/',
        'fr' => 'http://local.mysite.dev/fr/',
    ),
    'environmentVariables' => array(
        'en' => array(
            'basePath' => '/path-to-mysite/public/',
            'baseUrl' => 'http://local.mysite.dev/',
         ),
        'fr' => array(
            'basePath' => '/path-to-mysite/public/fr/',
            'baseUrl' => 'http://local.mysite.dev/fr/',
        )
    )
)

Or, is that something I just append to any path(s) in my template given the current section/segment etc?


texts: Can someone confirm that when importing entries with Feed-Me, the entrytype can NOT be set dynamically based on a field of the feed?


texts: Is it possible to redirect a certain user type to the entry front-end page once they click on Save from the CP?


texts:
I think my question is simple but may fall outside of the scope of this forum. What is best practices when writing and debugging Craft plugins? Obviously, one way to do so is to create a account on a server, write the code, upload and install it and then trigger the code using twig in a web page. Uggg...

Is there a good (hopefully free, open source) way to write and debug plug in code for Craft, perhaps locally?


texts:
Quote from the {% requireLogin %} docs:

  This tag will ensure that the user is logged in. If they aren’t, they
  will be redirected to the Login page, and returned to the original
  page after successfully logging in.

Quote from the Login Form example in the docs:

  craft.session.returnUrl is set to the original URL that included the {% requireLogin %} tag that initiated the redirect to this login form. By default, users will be redirected based on your postLoginRedirect config setting value after logging in.

That seems to be contradictory - the first sentence saying the return path will be the page that contained the requireLogin tag and the second saying the return path is defined by a config setting.

I want to be able to have the redirect go to the page that calls the login (I have
 a few of them), but do not see a way of doing that. Using a return parameter in the login form does not work for obvious reasons.

Am I missing something here? Any wisdom greatly appreciated!


texts:
I setup HappyLager.devas per these instructions on GitHub, after setting up phpmyAdmin on a local dev box which was no small feat. I want to know why my Images/Assets are missing from the finished install.  Look:

I've checked my database import, which did succeed, in fact, I checked the entries/articles etc, and verified that the images do exist, and I copied the assets folder into apache:

The Article Entry does contain the image, ie skis, and every article/etc I glanced at is like this.  What did I  miss??


texts: Author list limited to first 100 when assigning to entry?

texts: We have more than 100 authors in a user group, but when selecting an author for an entry, only the first 100 are listed in the (a-z) dropdown. Whats the best way to display them all (or up the parameter?)


texts: Update Error: Could not validate update handle

texts: Recently, anytime an update to Craft core or a plugin is attempted on my site that requires a database migration I get an Internal Server Error: Could not validate update handle. Does anyone know what handle Craft is talking about here? Looking for help debugging this issue. My guess is that somewhere in the midst of updates and rollbacks the database got out of sync with the source code. Just need to track down where this faulty handle is.


texts: I have an entry page that lists out specific info for a product. I am using categories to sort the entries. I'm trying to figure out how to write a conditional that pulls in something specific if the entry belongs to a specific category.


texts: Is there a way to format the Asset Size variable to Mb, Kb, etc.?

texts:
I'm trying to display the file size of a file uploaded in Assets. I can get it to display the number of bytes in the file. https://craftcms.com/docs/templating/craft.assets#size

Is there a way to format that number to Mb's?


texts: Help with an Entries field to an array I can use elsewhere

texts:
I have an Entries field so I can select a number of posts to feature in a "Hero" section on the home page, as well as a "most popular" section underneath it.
However, the Hero posts keep showing up in this section, so I'd like to exclude them from the query.
Is there a way I can get the array of entry id's from the Hero section and insert it into the popular query?
Am using the Trendin Posts plugin (https://github.com/madebyraygun/trending-posts) to get the popular posts.
{% set entries = craft.entries().section('news').limit('4').orderBy('popular').all() %}

and I would like...
{% set entries = craft.entries().section('news').limit('4').orderBy('popular').id('not', {array of IDs from Hero}).all() %}


texts: Dynamically iterate over a matrix block's fields?

texts:
Is there a way to dynamically iterate over a matrix block's fields such that the template doesn't need to know the field handles? This doesn't work:

{% for block in entry.myMatrixField %}
    {% for field in block %}
        {# do something with field #}
    {% endfor %}
{% endfor %}

This seems like a simple thing to want to do but I haven't figured out a way to do it.


texts: Smart Map plugin - Get visitor's lat/lng

texts:
I'm using the Smart Map plugin but want to render my own maps. All I need is the lat/lng of a visitor yet I can't find it in the documentation. I don't want Smart Maps to render the map for me, I just want the lat/lng.
I'm currently using the Geo plugin to do this but it seems a bit silly having both installed.


texts: How best to add price tiers based on user group

texts:
I'm new to Craft Commerce.

I wish to add around 10 price tiers to each product. Users are in groups and the group determines which price tier they pay. All the data is to be imported (and kept up to date) via API from an inventory management system. There are around 5000 products.

Sales and Discounts do not seem to be a good option as these are applied to whole groups of products whereas in my case each product has different pricing at each tier - there is no standard formula.

Another SE question,
Multiple Prices based on User in Craft Commerce, uses variants. Is this the best way to go? For me the only difference is price so I feel it is not really a variant and this is a rather cluttered approach, especially as for each variant I will have to repeat a number of other fields. (And I might want to be able to use variants for the real variants rather than have the real variants as separate products to avoid a variants-squared situation).

So, I'm looking for advice on overall direction. It will be Craft 3/Commerce 2. TIA.

UPDATE: I was able to import the price tiers into custom fields on each product, and then on the product page display the correct price based on the user category selecting the right price tier. And then use this in a hidden field - I had to use options because I couldn't get it to work otherwise - not sure what I was doing wrong:

<input type="hidden" name="options[customPrice]" value="{{price}}">

Then (not knowing much anything about OOP PHP, but being a good scrounger who can copy and paste) I was able to modify the line item in the checkout page like so in Plugin class:

public function init() {
  Event::on(LineItems::class, LineItems::EVENT_POPULATE_LINE_ITEM, function(LineItemEvent $e) {
    $lineItem = $e->lineItem;
    if(isset($lineItem->options['customPrice'])){
        $lineItem->price =  $lineItem->options['customPrice'];
    }
});
}

It seems to work, but who knows what sensibility boundaries I have crossed. The OOP side of things may as well be Greek to me.


texts: Creating a related content subpage to a channel entry?

texts:
For a project I'm working on I have set up several channels that are related to each other. What the setup comes down to is the following:

Channels:

Projects
|- News relations (news is a channel and news entries can be related to a project entry)
|- Gallery relations (gallery is a channel and galleries can be related to a project entry)
|- ... and more related content ...

Now I can visit the projects overview on the /projects path and a project entry on the /projects/{slug} path. The project entry page shows a short overview of the related content (i.e. 2 or 3 of the related items for the various channels), but will also contain a link to the full listing of all news items/galleries/etc of the requested projected.

Preferably I would have a url for these subpages to the project on a path like /projects/{slug}/news and /projects/{slug}/gallery.

How would I set this up? I've been looking around, but can't find any solution to this.


texts:
How does one get the total no. of pages for a multi-step form? The following doesn't work.

{% set count = form.pages().count() %}


texts: Is it possible to execute ./craft via cron?

texts:
I'm trying to execute Craft 3.3.X CLI commands via cron. I can execute ./craft from ssh no problem, but the same type of commands triggered via cron do not execute.

These command works via SSH:

# cd /home/USERNAME/CRAFTROOT
# ./craft backup

# /home/USERNAME/CRAFTROOT/craft backup

These commands do nothing via cron:

cd /home/USERNAME/CRAFTROOT;./craft backup

/home/USERNAME/CRAFTROOT/craft backup

Any ideas?


texts:
Currently trying to get the date filter to display 'April' instead of concatenated version 'Apr'. My code below is:

{{ now|date("M, Y") }}


texts: Contact Form plugin - Not receiving emails at separate addresses

texts:
I have implemented the Craft contact form plugin, and have my form set to send to two email addresses. I am receiving messages at one address, but my client is not receiving any messages at the other. Their email address is the same domain as the website.

Any thoughts?


texts: {% cache %} tag creates duplicate entries

texts:
When using the {% cache %} tag on an entry type, it caches the first entry on the page (multiple pages as well), and uses the cached entry for every other instance of that entry type on the page. What am I doing wrong? Here's an example. This one isn't complex so not sure it's worth caching, but I have some entries that have multiple relational fields.

{% for block in entry.contentMatrix %}
  {% if block.type == "copyOneCol" %}
    {% cache %}
        .... output entry type data
    {% endcache %}

  ...next if, etc.
{% endfor %}


texts: How how can I restrict/fail a login using a User::EVENT_BEFORE_AUTHENTICATE hook?

texts:
When a user attempts to login, I check a 3rd-party to make sure they should have access. If they shouldn't, I need to stop them logging in. I have this working, but I could only get it working by setting my own session var and it's hacky and there must be a better way!
I'm using the EVENT_BEFORE_AUTHENTICATE event like so:
use craft\elements\User;
use craft\events\AuthenticateUserEvent;

// ...

Event::on(
    User::class,
    User::EVENT_BEFORE_AUTHENTICATE,
    function (AuthenticateUserEvent $event) {

        //Empty a session var to use.
        Craft::$app->getSession()->remove('myCheckInvalidUser');

        //Do my checks.
        $checksuccess = $this->doMyChecks($event->sender->username, $event->password);
        if (!$checksuccess) {

            // This is where I feel I should be calling some Craft:: invalid login
            // call or something. But instead I'm doing this:

            Craft::$app->getSession()->set('myCheckInvalidUser', true);

        } else {

            $success = Craft::$app->user->loginByUserId($user->id);
            Craft::$app->response->redirect($referrer);
            return Craft::$app->end();

        }
    }
);

Then in a second hook for EVENT_BEFORE_LOGIN I have:
use yii\web\UserEvent;
use craft\web\User as WebUser;

// ...

Event::on(
    WebUser::class,
    WebUser::EVENT_BEFORE_LOGIN,
    function (UserEvent $event) {

        $myCheckInvalidUser = Craft::$app->getSession()->get('myCheckInvalidUser');

        if (!$myCheckInvalidUser === false) {
            $event->isValid = false; //Shuts this down, woop.
        }

    }
);

Any and all suggestions, however brief, appreciated. Even if it's to do with some bad coding that doesn't answer my question, because this event malarkey and knowing which bits to use is doing my head in and I want to learn!


texts:
This is my first try at Craft, was planning on replicating a current site as practice, had a question about the sites architecture.

I have a Brands page:

Brand/Company info
-Brand product line
--individual products within that line

What would be the best way to implement this?
I'm thinking a structure? They are child's of each other?

Thank you.


texts:
I want to list all categories that have an entry assigned to them, but hide the ones that are empty.

In EE I could do this show_empty="no"

But I can't see a parameter in the docs for Craft.

Currently I've found that I could use relatedTo but with passing an object with up to 600 entries it dies with caching tags :(

Is there a better way of doing this? This is what I've got at the moment:

{% set blogPosts = craft.entries({section:'blog',limit:null}).find() %}

{% for cat in craft.categories({groupId:2}).relatedTo(blogPosts) %}

{{cat.title}}

{% endfor %}


texts: Using multiple sections VS a single section with entry types

texts:
I'm just planning ahead for a project and was hoping for a second opinion.

I'm going to be making a site that will have about 7 different types of entry - all of which have different fields/URL's; however on the front-end they will all behave as if they are part of one channel. I will have a single page that lists all of the entries and I will also be giving end-users the ability to perform searches/filtering.

For the sake of easy dashboard management I have currently set them up as separate sections instead of one section with multiple entry types (because using individual sections gives me a nice separated 'Entries' page in the dashboard - it's hard to sort/view by entry type at the moment).

Question: Seeing as I can get the site to work the same regardless of which method I use, is there a dramatic difference between pulling out entries from multiple sections VS pulling out entries from one?

For this example lets just say we are dealing with around 100,000 entries total.


texts: Extend templates from outside templates directory

texts:
I have a setup where I'm using a component library that I have as an npm package. To use these components I need to extend templates that live outside of the /templates directory. So I need to achieve something like:

{% extends "../../../../node_modules/design-system/page-templates/_template.njk" %}

I will be extended from within a template that is located from within the /templates directory but allows for extends from outside of it.

Any help would be great.


texts: When trying to create a new asset volume, I don't have the form line where to put the path

texts:
As per the question, see the included screenshot:

I just don't have the URL form to type where the volume should be on the server.


texts: Upgrading Craft 2 to 3 hits database error

texts:
I'm working on upgrading a site from Craft2 to Craft3. I've run through the steps in the upgrade guide and when I go to /admin and press the button to run the Database upgrade I get the following error.

Integrity constraint violation: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'createfoldersinvolume:bb790fdf-3d6b-46b8-a023-b9f7ffe8aba5' for key 'craft_userpermissions_name_unq_idx'
The SQL being executed was: UPDATE craft_userpermissions SET name='createfoldersinvolume:bb790fdf-3d6b-46b8-a023-b9f7ffe8aba5', dateUpdated='2019-02-04 17:39:32' WHERE id=173

Migration: craft\migrations\m180518_173000_permissions_to_uid

I can restore the database so that's fine but not sure how best to proceed with the upgrade. Any help would be appreciated!


texts: AWS EC2, Load Balancer and Updating Craft

texts:
I have a pretty large Craft site that needs to be load balanced with multiple ec2 instances and one RDS mysql instance. Everything is working great, except for I noticed that if I get to the admin panel and run updates on craft/plugins. The site files only change on the ec2 instance i'm on.

Is there a way to update all my ec2 instances at once on update?

Thanks! Any help is appreciated.