texts: How can I make Sprout Invisible Captcha plugin works using AJAX submission?

texts:
I set up a custom form template using Sprout Forms and added {{ craft.sproutInvisibleCaptcha.protect() }} inside the <form> tag.

I can see there are several captcha tags added by the plugin, but as I am using AJAX submission:

How can I make it works using this submission method?
How do I handle redirect to my 'redirect' location?

I did these tests:

Prevent a form from being submmitted if a user does not have JavaScript enabled ;
Block form submissions by robots who auto-fill all of your form fields ;
Require minimum time to fill out your form ;

All of these tests have failed, spam haven't been caught.

This is the captcha field inside custom Sprout Form template:

{{ craft.sproutInvisibleCaptcha.protect() }}
<input type="hidden" name="redirectOnFailure" value="{{ craft.request.getUrl() }}">

And this is the AJAX post inside JS script:

var postUrl  = 'sproutForms/entries/saveEntry',
    formData = {
    action: postUrl,
    handle: 'test',
    fields: {}
};

formData['fields[minPrice]'] = $scope.results.minPrice;
formData['fields[maxPrice]'] = $scope.results.maxPrice;

formData = $.param(formData);

$.ajax({
    type     : 'POST',
    url      : postUrl,
    data     : formData,
    dataType : 'json',
    encode   : true
});


texts:
Is it possible to configure "Save & Continue Editing" as default mode?
I know there is option to select it when adding entry but I want to configure so that always is the case for one of the channel.


texts: Constant exception.Craft\HttpException.404 in logs

texts:
My log is getting hammered nonstop by the same error about every second (see image). Any idea what's going on here?

Text is:

Level       error
Category    exception.Craft\HttpException.404
Message     Craft\HttpException in /home/folder/public_html/craft/app/controllers/TemplatesController.php:72


texts:
I am making a dashboard widget to trigger the assets indexing action.
I got the controller ready but I do not understand then how to trigger the action.

Should I go with AssetIndexTool? Then performAction()?
Or using ToolsController ?

I am really lost. Thanks for help!


texts: Pass a nested array to the params argument inside Craft's url() function

texts:
I have a list of checkboxes in a GET form which results in a URL with a querystring like ?q=&cat=&city%5B%5D=28&city%5B%5D=26&sort=asc&order=name when submitted. The Object/Array behind this string looks like:

Array
(
    [q] =>
    [cat] =>
    [city] => Array
        (
            [0] => 28
            [1] => 26
        )
    [sort] => asc
    [order] => name
)

I'm trying to create a link with one of those GET params changed, but I can't find a way to update a single value. So now I'm rebuilding the URL by creating an object based on the given query params.

If I pass this object (as shown above) to the second argument inside Craft's url() function to use this URL on a simple <a> tag, I get an Array to string conversion error.

I seems Craft can't handle nested arrays in this function. Is there another method to generate an URL from such an object?


texts:
I need to list out the image options from a specific assets folder for users to select from. Previously, I accomplished that like this:

{% set folder_id = 5 %}

{% for image in craft.assets.kind('image').folderId(folder_id).order('filename') %}

    {# do stuff, like print image.filename #}

{% endfor %}

And to get the folder ID pre-2.5, I could inspect the folders menu when viewing assets in CP. Now, that appears to be gone in Craft 2.5+ and struggling to find the ID. I'm assuming there must be a way to view the folderId as Craft has a folderId() filter for craft.assets.

Does anyone know?

Thanks,


texts: How would you show a specific entry 'and' its children

texts:
I'm creating a footer menu and want to show an entry id and its children, atm I'm just getting the descendants but struggling to show the parent and children as well

        {% set entries = craft.entries.section('pages').descendantOf(8) %}

{{ entry.parent }}

        {% nav entry in entries %}

{{ entry.title }}

            {% ifchildren %}

                {% children %}

            {% endifchildren %}

        {% endnav %}

Appreciate this is the wrong approach any feedback appreciated on how to display the title of id 8 as well as its children, atm parent.entry is not showing


texts:
My installation of Craft Commerce seems stuck after purchasing the Pro license. Im getting similar errors throughout the site:
Base table or view not found: 1146 Table 'craft_xxx.xxx_commerce_customers' doesn't exist.
I've gone ahead and updated Craft to the latest version. Commerce is still on version 2. Updating it to version 3 via the control panel doesn't work (memory limit) and updating via the console yield multiple errors:
Applying new migrations ... error: The command "'/xxx/craft' 'migrate/all' '--no-backup' '--no-content'" failed.
> create table {{%commerce_lineitemstatuses}} ...Exception: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'xxx_commerce_lineitemstatuses' already exists
Not even sure if I need to update things.. Just hoping to get the site up and running and back into development.. :) I can restore the database and leave the files in place for the recent Craft and old 2.2.22 Commerce and try to upgrade again? Would that work?
Any advice?


texts: I'm interested in creating a plug-in that creates a new type of transform. Is there a hook/event related to image transforms?


texts:
I'm having trouble setting the variables of the env.sh file for craft-sctipts.
I getting an error: File /common/defaults.sh is missing, aborting. when I try to clear the cache using a cronjob pointing to the clear cache script.
My variables are set in the env.sh file, which is in the scripts directory.
LOCAL_ROOT_PATH="/domains/mydomain.ca/"
REMOTE_ROOT_PATH="/domains/mydomain.ca/"
The scripts are in /domains/mydomain.ca/scripts/ directory.
Any thoughts?


texts: How can I create a visually weighted tag cloud?

texts:
I kind of want a tag archive page where it doesn't just list all the tags and links to entries based on that tag, but where the sizes of the actual tag link vary based on frequency of use.

Any idea how?


texts: which Sources of asset field are checked

texts:
I have an asset field (craft\fields\Asset), how do I figure out which Sources it can use? (Which of the Sources boxes are checked)?

This is for Craft 3, and I'd like to do it in twig (I have the asset field in twig)


texts:
I need display Stores by Region, by example:

Alabama

Store X
Store Y

Idaho

Store A
Store B

So:

I create two channels Stores and Regions.
In the channel Stores I create a entries field type called storesRegion and check Regions source.

So great! I can create new stores and select where the store is located.

I can display the Regions like this:

{% set relatedRegions = craft.entries.section('regions').relatedTo({
    sourceElement: stores,
    field: 'storesRegion'
}) %}

{% for region in relatedRegions %}
    {{ region }}
{% endfor %}

good but now I need display all the Stores from each Region

this is a good example of what I need: https://www.apple.com/retail/storelist/

this is something related with reverse relations?


texts: Craft's control panel search function returning inconsistent results

texts:
When I search for titles of entries in the Craft control panel, I get odd results:

I have an entry called Fake Story about the Economy.

If I search for that exact title, I get no results.

If I search for Fake Story about, I get no results.

If I search for Fake Story, the entry Fake Story about the Economy is returned.

If I search for Fake Story the Economy, the entry Fake Story about the Economy is returned.

The results are similar for other entries in that channel. For example, I have an entry called Is it still business as usual?. The only way I can find it is if I leave out the word still when I type it (Is it business as usual?).

Other channels seem to be working fine.

This is of course affecting my ability to build a working search form on the front end as well.

Craft 3.3.19

Thanks for any help.


texts:
I have a Craft/Commerce set up with Euro is base (and only) currency and 3 locales are defined in the site (nl_be, fr_be and en_be).

Prices are showing up as:

  0,99 €

instead of

  €0,99

When I print the entry's locale I get nl_be and my preferred language in the CP is also set to nl_be.

The url I'm using is also localised, through /nl/index.php, which sets CRAFT_LOCALE to nl_be.

I'm a bit clueless as to what I'm missing, any help would be appreciated.

Thanks!


texts: postCpLoginRedirect wrong redirect when used with autoLoginAfterAccountActivation

texts:
See below updates and accepted answer for a full solution

I finally discovered postCpLoginRedirect which solves my needs, even though I only need users to access their profile (which includes lots of custom fields, hopefully we'll have a few more permissions options in future for the cp).

Anyway, the issue I'm having is I want to redirect to a front-end dashboard which is at {{siteUrl}}counsellors/dashboard. This page has a {% requireLogin %} tag which redirects to the cpTrigger. And, as cp is enabled for default user groups, I understand activateAccountSuccessPath, postLoginRedirect are defunct settings.

When logging in from the Craft cpTrigger the relative link string /counsellors/dashboard works fine.
But when used in combination with the autoLoginAfterAccountActivation it directs to the wrong path (relative to the admin trigger login/counsellors/dashboard)

Ideally I'd like to keep it separate as eventually the CP will be swapped out for a front-end solution, so any clues as to why this is happening? Or what combination of settings are required to fix it?

settings:

'cpTrigger' => 'login',
'postCpLoginRedirect' => '/counsellors/dashboard',
'activateAccountSuccessPath' => '/counsellors/dashboard',
'autoLoginAfterAccountActivation' => true,
'loginPath' => 'login' # Redirect to cp trigger
// 'postLoginRedirect' => 'counsellors/dashboard',

Updates 28/01/2016:

If you're giving users access to Control Panel activateAccountSuccessPath won't work, regardless of the path — a plugin is required to make this happen.

So it seems for now at least, everything has to be built front-end as @RitterKnight suggests

A big caveat is, no matter what, if a new registered user has access to the CP, activateAccountSuccessPath is ignored. You'll need a plugin to have newly activated accounts forwarded to your success page.
Another nice addition is to use the brilliant Control Panel Nav plugin (which really I think should be built into Craft)

If you're having users login directly from CP login, you can couple this with postCpLoginRedirect if you want to hide the dashboard from users.

So to recap, full settings are now:

Front end registration, front-end success page, front-end login form, front-end dashboard;
A plugin to enforce activateAccountSuccessPath settings
Control Panel Nav plugin with a link to the custom dashboard;
The following config settings:

'loginPath' => 'counsellors/login',
'activateAccountSuccessPath' => 'counsellors/success',
// 'autoLoginAfterAccountActivation' => true, # Doesn't work
// 'postCpLoginRedirect' => 'myaccount#profile', # Optional
'postLoginRedirect' => 'counsellors/dashboard',


texts:
I wanted to know if there is any way to install markhuot/craftql via the command line.

I tried to follow the one-liner instruction here:
https://github.com/markhuot/craftql#installation

composer require markhuot/craftql:^1.0.0

but after installing I don't see the options in the backend.


texts: confused by inconsistent behavior of matrix

texts:
Here's my code block:

{% extends "_layout" %}

{% block content %}

{{ entry.title }}

TEST EDIT 8

        {% for block in entry.blogPost %}

heading - {{ block.heading }}

sub heading - {{ block.subHeading }}

accolade- {{ block.accolade }}

        {% endfor %}

Posted on {{ entry.postDate.format('F d, Y') }}

        {{ entry.body }}

{% endblock %}

And here's the error message I am getting on an inconsistent basis:

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

I've tried to remove the other Matrix fields from the template, and just isolate on the 'block.heading' field, and I get really strange behaviors. Sometimes the template renders fine, and the dynamic value gets rendered by the page. Sometimes, with a different content entry, the same template gives the above error message.

I'm brand new to CraftCMS. Is there an obvious syntax mistake I'm making?


texts: Pixel & Tonic's Contact Form Plugin - POST submissions to Zapier Webhook URL?

texts:
I'm still a beginner with PHP so please bear with me. I've installed the Contact Form plugin for Craft by Pixel and Tonic, and have it configured to work as expected.

However, I'd like to have the form also send the data to a Zapier webhook URL so that it will automatically create a lead in my CRM system.

Putting the webhook URL in the "action" field but does send the data correctly to Zapier, but the user goes to a status page (see screnshot below) and the form isn't mailed out to my email.

Any help or suggestions on the best way to accomplish this?


texts: Adjust all date/times to users current timezone

texts:
I've done a bunch of research and I can't seem to find a suitable answer for this issue without hacking which I'd like to avoid.

My client needs the entries in the DB to always assume they're relative to the users current timezone. So content set to display at 9am on Monday morning will display at 9am Monday in every timezone.

The locale options in Twig only adjust the UTC timestamp to the users current timezone but it's still displaying content based on UTC timestamp in the DB.

Through MySQL I can use the following command per session to accomplish what I'm looking for:

SET SESSION time_zone = '+10:00';

This appropriately offsets the MySQL time to match a users timezone +10 hours ahead of UTC, in this case Australia.

Reading this article it seems that "initSQLs" might be the answer but it's a Yii article that talks about adding that command to the db array within the protected/config/main.php file which I'm unsure of how to tie into.

Nevertheless, I'm hoping someone might have some insight into how I can bootstrap the DB calls per user session or another solution potentially utilizing a plugin.

We're doing timezone lookups by IP address, I realize the potential issue, so the option will need to work for both logged in and logged out users.


texts: Can't backup DB locally with MAMP PRO 5.5.1

texts:
I have followed the instructions for this article (https://craftcms.com/guides/database-backups-in-craft-3-with-mamp) to get local backups working with MAMP. However, when I attempt a backup, I get this error: exit code 127: sh: mysqldump: command not found.

which mysqldump returns /Applications/MAMP/Library/bin/mysqldump and I can dump a db successfully from the terminal using 'mysqldump` but it does not work from the Craft CP for backing up a DB or when Craft tries to backup a DB when running an update.

Is there something else I should be doing?

The help article referred to above seems to make it pretty clear that this should work.

UPDATE:

After further testing, it seemed that those .env variables just did not seem to be getting used after I added...

'backupCommand' => getenv('BACKUP_COMMAND'),
'restoreCommand' => getenv('RESTORE_COMMAND'),

...to my general.php.

So I tried adding this module instead and now DB backups work as expected.

I'd still be curious to hear from anyone at Craft as to what could be missing in that first method they've laid out.


texts:
I am unable to change my password, as an admin in the CP of Craft.
I tried resetting it but it did not work.


texts:
I have a site where I'd like customers to login and be immediately presented with their profile page (and ONLY their profile page).

On this page they can:
1. See progress reports on their jobs (custom fields)
2. Create new jobs and edit existing jobs

I've added a load of custom fields to the user group but I don't actually want the customers to be exposed to the admin?

Any suggestions for the process of creating this scenario?


texts: How call PHP native function in Model/Service/Controller scope

texts:
I need to make a SoapClient new SoapClient call from within one of my Models for a validation rule. When I create the new SoapClient instance class in my Model function I'm getting this error message:

Fatal error: Class 'Craft\SoapClient' not found in...

I get the same error message whatever file Model/Service/Controller i put it in.

public function validateVatNumber()
{
    $client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
}

Could anyone let me know what I should do to be able to make these calls? I'm guessing I somehow need to "break free" from the Craft namespace.

Thank you


texts: Can you store a table field within a matrix field?

texts: I am looking to use a matrix field for my site navigation that has some dropdowns. Using a table field within a matrix field seems like it would work but I don't know how to access the table inside the matrix field in my template. Is this possible.


texts: Can I call a filter on all Rich Text fields?

texts: I'm looking to dynamically replace the ℠ glyph with SM in all rich text fields, since that glyph doesn't exist in the font we're using. I'd like to avoid having to call the |replace filter on every field in every template, and I can't seem to get the customAsciiCharMappings general config setting to work either (I'm not sure if I really understand what it does). Does Craft have something like a global replace function/filter?


texts: help setting up web root to point to /web

texts:
I'm new to Craft 3 and I need help getting the web root to point to /web.

I can't figure it out. If I use the url "mysite.com/web" everything works fine.

Any help would be gratefully received.


texts: FreeForm: Adding attributes to the honeypot field

texts:
I'm using VueJS too process and submit forms, and I would like to utilize the freeform honeypot functionality. The issue is that I am unable to add a v-model attribute to the honeypot field.

I've already got the CSRF token passing into the VueComponent without issue; I need to get an attribute onto the honeypot field.

Is there a way to do this out of the box?


texts: How can an entry type have its own search and categories?

texts: I have an entry type whose content will be separated from the main content. So I was wondering how can we give an entry type its own search and categories? Possible?


texts: How to reference a user related to entry input in if statement

texts:
I am having trouble referencing a user in an if statement:

{% set otherEntry = craft.entries().section('other').userFieldInOtherEntry("{externalVariable}").one() %}

{% if currentUser is relatedTo(otherEntry) %}
    do something
{% endif %}

I've tried using the for loop method described in the Craft 3 documentation, but I get a recursive loop error.


texts: How do you only show children of "active" parent in a Structure section's nav?

texts:
I've got a Structure section where the top level is the main menu. The submenu consists of the children of the active main menu item. This works well.

For the submenu, I'm using this code:

{% set mainEntry = craft.entries.slug(craft.request.getSegment(1)).first() %}
{% set subnav = craft.entries.descendantOf(mainEntry) %}

{% nav page in subnav %}

    {{ page.getLink() }}
    {% ifchildren %}

        {% children %}

    {% endifchildren %}

{% endnav %}

...which shows all children of each page.

How can I only show the children of the active parent? I've tried to wrap the ifchildren block inside another if statement (the same I used to set the class="active" to the
), but that results in a Template error:

  Unexpected tag name "ifchildren" (expecting closing tag for the "if" tag defined near line x)

Putting that if statement inside the ifchildren block also throws a template error.

PS. With the current HTML output, I could also just use CSS to hide/show the
s based on the .active class, but I'd still like to know how to generate that tree without the need for  a CSS workaround.


texts: Existing contents get deleted on Live Preview when adding new content on a matrix field

texts: When I add a new content for a matrix block field on an existing entry, all its previous contents gets deleted from the Live Preview, except for the editor which still has the previous contents. And then, when I try to save the entry, it seems that what is shown in the Live Preview was the only one saved and the previous data were gone.


texts: Is it possible to create composite Primary Keys in Records?

texts:
I've structured my Record as such:

<?php
namespace Craft;

class MyPlugin_MerchantOrderRecord extends BaseRecord
{
  public function getTableName()
  {
    return 'myplugin_merchant_orders';
  }

  protected function defineAttributes()
  {
    return [
      'merchant_id' => AttributeType::Number,
      'order_id' => AttributeType::Number,
      ...
    ];
  }

  public function primaryKey()
  {
    return ['merchant_id', 'order_id'];
  }

  public function defineRelations()
  {
      return [
        'merchant' => [static::BELONGS_TO, 'MyPlugin_MerchantRecord', 'merchant_id',
               'required' => true, 'onDelete' => static::CASCADE],
        'order' => [static::BELONGS_TO, 'Commerce_OrderRecord', 'order_id',
               'required' => true, 'onDelete' => static::CASCADE],
      ];
  }
}

When I install the plugin I get the following error:

Illegal offset type in isset or empty

If I take away the primaryKey() definition, the table is created successfully and the foreign keys are in place as expected.

Any help gratefully received.


texts:
We're currently in the process of migrating web server to a new Ubuntu 14.04 box, and we are running into the same problem across our multiple Craft installations which is majorly affecting our workflow across all projects at the moment.

When we're updating content in Craft, we're frequently clicking 'Save' on categories, entries etc then having the server response timeout on us. The browser says 'Waiting for reply...', but it can take up to 5 minutes for the page to refresh with the saved data, which does appear to eventually being saved correctly.

I've spoken to our hosting company, and they told me that they couldn't see anything unusual in the logs, and advised that I install New Relic to be able investigate the problem further.

I installed the monitoring software along with the PHP service, and added a line at the top of index.php in Craft to identify the individual applications in New Relic.

I've just experienced the problem again on this site, when I was saving a new nested Category.

Going into New Relic transactions, I see in the transaction breakdown for the saveCategory transaction that 300,000 ms was spent in CInlineAction::runWithParams.

I've included the summary trace from NewRelic in the attached image.

Could this is a bug inside Craft, or if there is anything specific to our server which maybe causing this?


texts: How can I link to an Asset from the Rich Text editor?

texts:
I have some content on my entry like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis rutrum dolor.

I know I can link to an Entry or Category, but I would like to link to an Asset. For example, a PDF.

I would like to highlight Lorem ipsum and link that text to a PDF. I can change over to HTML view and manually enter the link, but that seems risky to ask a client who may not know any HTML. Is there a preferred way to select some text and link it to an asset?


texts: A Streamlined Way to Export / Import Entries Between Environments?

texts:
Do any of you have a preferred workflow for exporting entries to be imported into another installation of Craft using plugins or migrations or other processes? I'd think this would be a good job for a plugin, but I'm also curious what works for other Craft users.

Plugins That Work Well with Feed Me?

It seems that Feed Me is the de facto solution for importing as it's been absorbed into Craft, but is there a specific plugin or method that works well with that plugin for exporting?

The most actively maintained export plugin I've found is "craft-export-csv," but it's a paid plugin that hasn't seen any maintenance since last April, and I'm wary to build a process around a plugin that could see deprecation.

Alternate Plugins?

Beyond something that can be chained into Feed Me, is there an all-in-one solution, like Field Manager for exporting fields? Nothing seems to come up when searching the Plugin Store.

If nothing exists out there that fits this criteria, I'd be down to start working on something like this on my own, as it'd save me and my coworkers potentially hours of copying / pasting fields between environments.

Thanks for your time!


texts: Impossible to access an attribute on a null variable - on the one() method - all() works!

texts:
First question - but I think this is a bug (not my fault).

I have entries/pages (a structure) - one parent (product overview) with children (products)

I have one category group with categories - only for assigning some repeating data to the child entries (like properties of products - colors for instance)

Getting the properties (the field data of the assigned category) on the product pages itself works flawless like this:

{% set properties = entry.fieldPropertiesCategory.one() %}
{{ properties.propCatFieldColor }}

BUT on my product's list page (the above-mentioned parent) it doesn't.
I try the following:

{% set products = craft.entries.descendantOf(entry).all() %}
{% for product in products %}
    {% set properties = product.fieldPropertiesCategory.one() %}
    {{ properties.propCatFieldColor }}
{% endfor %}

I get "Impossible to access an attribute ("propCatFieldColor") on a null variable."

But properties isn't null (checked this with dump()) ... it's the same like on the children entries.

My workaround is the use of all() and an additional iteration - this surprisingly works:

 {% set products = craft.entries.descendantOf(entry).all() %}
 {% for product in products %}
    {% set properties = product.fieldPropertiesCategory.all() %}
    {% for property in properties %}
       {% if loop.first %}
          {{ properties.propCatFieldColor }}
       {% endif %}
    {% endfor %}
{% endfor %}

Makes no sense to me ...

I tried everything - getting the category object of the children entries in various ways on the parent entry but this all doesn't work. Always the impossible to access error.

Has anyone an idea on this?


texts: Is there a way to generate a url to an image in the craft/storage/myplugin directory?

texts: I am generating dynamic images to a directory in craft/storage. I need to be able to use these generated images on the front-end inside templates. Is there a helper method for this, or some way to use these images in my templates?


texts:
Just had an e-commerce site go down due to Craft's custom way of handling Sessions. The session directory never gets cleaned up, causing the sessions folder to be littered with tens to hundreds of thousands of orphaned files, causing my server to run out of inodes. PHP has a built in utility to deal with this, but that doesn't work since Craft sets a custom session directory. Looking for a good cron job or other utility that will automatically clean this folder up automatically.

Also, curious if there is work being done on Craft to fix this issue by default. I wonder if the reason it hasn't become as big of an issue as it seems it is (only found a handful of people mentioning it on the Google Plus page), is because Craft hasn't been out long enough for some sites to experience this yet, but they may soon. It took about 4 months for the session directory to get too full on a pretty small hard drive, so I wonder if a number of other sites with bigger hard drives currently have this issue behind the scenes, and haven't experienced any problems yet, but will soon.


texts: Smart Map with multiple different markers based on a matrix field

texts:
I'm having some trouble setting different markers using the smart map plugin and was hoping someone might be able to point me in a direction I might not see.
The different locations are are set through a matrix field with two different block types; one that should return a blue marker and one that should return a green. I've been following the docs at: https://plugins.doublesecretagency.com/smart-map/different-icons-for-different-marker-types/ but have still been getting a javascript error preventing it to be rendered.
The javascript error is "uncaught TypeError: Cannot read property 'setOptions' of undefined. I'm sure this is because the markerId variable isn't getting the address from the matrix field.
Any help or insight would be greatly appreciated, thanks!
 {% set locations = entry.filmMap %}
{% set mapOptions = {
    height: 580,
    zoom: 10,
    draggable: true,
    markerInfo: '_includes/mapInfoBubble',
    markerOptions: {
    icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
  }
} %}

{{ craft.smartMap.map(locations, mapOptions) }}

{# Loop through location entries #}
{% for item in locations %}

  {% switch item.type %}
    {% case 'filmSites' %}
      {% set icon = '/assets/src/images/blue-marker.png' %}
    {% case 'castingCalls' %}
      {% set icon = '/assets/src/images/green-marker.png' %}
    {% default %}
      {% set icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png' %}
  {% endswitch %}

  {% set address = item.address %}

  {# JS: Change marker icon #}
  {% includejs %}

    var markerId = 'smartmap-mapcanvas-1.{{ entry.id }}.address';
    smartMap.marker[markerId].setOptions({'icon': '{{ icon }}'});

  {% endincludejs %}

{% endfor %}


texts: How can I install Craft Commerce 2 alpha release?

texts:
I tried following the installation instructions here: https://docs.craftcms.com/commerce/v2/installation.html

When I run composer install craftcms/commerce, it says:

  Invalid argument craftcms/commerce. Use "composer require craftcms/commerce" instead to add packages to your composer.json.

So I then ran composer require craftcms/commerce, and it says:

  [InvalidArgumentException]   Could not find package craftcms/commerce
  at any version for your minimum-stability (alpha). Check the package
  spelling or your mini   mum-stability

I have added "craftcms/commerce":"@alpha" in the require field in composer.json also changed minimum stability to alpha ("minimum-stability": "alpha").

But it still is not working. Any thoughts? Thanks!


texts: how to concatenate multiple variables and strings

texts:
I am trying to form a url parameter (for Google Maps API) from entry field data. Basically, this is what I would like to do:

{% set street = entry.address %}

{% set  city = entry.city %}

{% set urlParam = street.", ".city.", UT"  %}

Is this possible with Twig and, if so, what is the proper syntax for concatenating multiple variables and strings?

Thanks!


texts: How can I get the id of an unverified user on front-end?

texts:
I would like to build a send activation email form on front-end, for users who didn't get or accidentaly delete the activation email.

I can call the users/send-activation-email action to achieve this, but this action only accept a userId as parameter, not the email address.

As I can't load unverified users from the front-end, it seems that I can't get the id of the current unverified user.

I know I could write a plugin for this, but I was wondering if there's any way to achieve this without?

Example of non-working send activation email form:

<form method="post" accept-charset="UTF-8">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="users/send-activation-email">
    {{ redirectInput('') }}
    <input type="email" name="email" required>
    <input type="submit" value="Submit">
</form>


texts: I'm a little bit stuck using the Element API. I managed to get my JSON file going pretty easily which was great but I've reached a point where I want to include some formatted copy as it would be output using markdown in a .twig template, is this possible?


texts: How to append / prepend into a rich text field

texts: I have a rich text field, e.g. for defining an image caption. Now in my template I would like to prepend some text to the content of the rich text field, e.g. Figure 1: [rich text]. Is this possible? The content of the paragraph-tag of the rich text field should include the prepended text.


texts: How to change/discount total amount before payment

texts:
I want to change the total amount programatically before the payments are processed.

If the total amount is $1000 I want to give a discount based on a point system in the users profile. You can add the desired amount based on his total points. If he adds 20 he gets a $20 discount and only have to pay $800.

What is the best way to implement this? I have tried with commerce_transactions.onCreateTransaction but no luck.


texts: Installation Error "1046 No database selected"

texts:
Summary

I'm getting the following error when attempting to install a new Craft site locally:

CDbCommand failed to execute the SQL statement: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected. The SQL statement executed was: SHOW TABLES LIKE 'craft_%'

Having just downloaded the ZIP, I assume the version of Craft in question is the latest at time of writing (2.1.2563).

Point of failure

After some digging, the error appears to be caused by line 59 in craft/app/etc/behaviors/AppBehavior.php, specifically the call to craft()->db->tableExists():

$this->_isInstalled = (craft()->isConsole() || craft()->db->tableExists('info', false));

If that is indeed the case, it means that the preceding craft()->getComponent('db') and craft()->getIsDbConnectionValid() checks are passing, which leaves me completely baffled as to what is causing the error.

Environment info

The site is (not) running on a local Vagrant VM, which is happily hosting another Craft site with no problems. It's perhaps worth noting that I didn't install the other site from scratch on this server.

The basic server specs are as follows:

Ubuntu 12.04 LTS (64-bit)
Apache 2.2.22
PHP 5.4.30

The database definitely exists, and I can connect to it using Sequel Pro.

Has anybody else run into this?


texts: Change password on user profile (customer account in Craft Commerce)

texts:
I have a customers area as part of the Craft Commerce site I am working on. Ideally I want the user to be able to update their password from their customer profile screen. I have it working and validating for First Name and Surname. I have made the email address a disabled field so this cannot be changed (as email is used t login).

However, I am having difficulty getting validation for the password fields. If I enter the old password correctly and a new password it does work and updates the password. However, I want some feedback/error trapping on the old password box to ensure the old password was correct and to offer some feedback if the passwords cannot be updated for whatever reason.

Is this something we would need to write to validate the old password, or is this baked into Craft?

Anyone able to point me in the right direction on this?


texts: Successfully installed Craft 3 via Composer but can't access site or admin

texts:
I've been Googling around all day looking for answers to this, but I'm actually stuck.

Ok, so basically I installed Craft 3 via Composer into a subdomain on my development server (apache). Everything ran successfully, there are no error logs, and the database has been populated with all of the tables. The problem is that if I go to http://craft.domain.com/index.php?p=admin (or /index/admin or /admin or /) all I get is a 500 Internal server error, and not one with the fancy craft background either. It does say email webmaster@craft.domain.com... on the error screen so I know SOMETHING's clicking, but I can't work my way around this.

I tried installing Craft once before manually by extracting the zip, uploading all the files, and then changing the .env file, and I got a similar result. I still wasn't able to access the admin OR the install page, and that's why I ended up trying it all through Composer instead.

Running the latest version of Apache, PHP 7, MYSQL with InnoDB; I run a ton of wordpress and laravel sites on this server without issue so I'm not clear on what makes Craft so different. I have WHM and shell access. Open to all suggestions.

Directory structure looks like this:

/home/username/public_html/craft (this is also the subdomain path)
  - config
  - modules
  - storage
  - templates
  - vendor
  - web
  - (and then the composer/env files)

Directory permissions are 775, the rest of the files are default Craft 3 installation. I've also made sure my PHP 7 memory limit is at 128MB (it was set to 32MB for some reason).
Thank you for any advice in advance!


texts: How to create a static JSON files with Element API and cache it with Varnish

texts:
Is it possible to create static JSON file using the Element API plugin?

What I then want to do was cache that file probably using Varnish or push it to an S3 bucket.

If I was to cache it I would need to look at purging the URL when an entry is added or edited.
If I pushed it to S3, then I would either need to overwrite the file or manage it another way.

What would be the best way to handle this, and could you easily create a static JSON file with caching and purging abilities?


texts: New entries only searchable by title field

texts:
I've recently done an upgrade of our site and am having issues with finding entries in the admin.
I keep entries for people who register a product so we have fields like registrationSerial and registrationSurname. registrationSerial is special as I use it as the title.
Since the upgrade I can only find new entries if I search with the serial number. If I try to use the surname it only finds entries from before.
As part of the upgrade I moved from using sproutforms to using freeform, they take care of creating the entries from a form on the site. I've ruled out this being the issue as the search isn't isn't fixed if I edit and save an entry in the admin, so at that point it should refresh the index with he new values.
I've also checked the fields and they are all set to "Use this field’s values as search keywords".


texts: What is the best way to deploy a Craft CMS 3 site?

texts:
I'm unclear as to the best way to deploy a Craft CMS 3 site. I'm looking for some best practices and guidance.

I'm currently using Rocketeer to deploy the code from my local environment to my staging site. When I do this I get a ServiceUnavailableHttpException. Do I need to install Craft again once it's been deployed to my staging environment? I don't think I need to but I can't figure out why I'm getting this error.

In the past, I've run Craft 2 sites successfully by installing once on each environment and then gitignoring the common files that I want to share. I have a hook in my Rocketeer file that creates symlinks to the common files/directories.

I've thought about taking a similar approach with my Craft 3 site but am unclear as how I would do that now that the the core craft files are required within composer. Move all the core packages to require-dev in my composer file?

Who can help steer me in the right direction?

Thanks in advance!


texts: Create Plugin to generate PDF files from content

texts:
Rather than render content out as HTML, I need to create PDFs for a project I'm working on. I was planning on using TCPDF in a custom plugin, but having played around with it a little, it does seem very limited it terms of the HTML/CSS you can throw at it.

Are there any better solutions out there? It can either be PHP based or maybe Javascript instead.


texts: Error when trying to update Craft or install any plugin

texts:
When I try to update Craft, or install any plugin from the plugin store, I get the following error):
Composer was unable to install the updates.

Error: The url supplied for the path (plugins/redactor) repository does not exist

Composer output: Package "craftcms/vue-asset" listed for update is not installed. Ignoring.
Loading composer repositories with package information

If I try installing a plugin through the command line, I get a similar error:
 [RuntimeException]
 The 'url' supplied for the path (plugins/redactor) repository does not exist

Here are the contents of my composer.json file:
{
  "require": {
  "craftcms/cms": "3.5.2",
  "craftcms/contact-form": "2.2.7",
  "craftcms/feed-me": "4.2.3",
  "craftcms/redactor": "2.6.1",
  "craftcms/simple-text": "2.0.2",
  "vlucas/phpdotenv": "^3.4.0"
},
  "require-dev": {
  "yiisoft/yii2-shell": "^2.0.3"
},
  "autoload": {
    "psr-4": {
    "modules\\": "modules/"
   }
},
  "config": {
    "sort-packages": true,
    "optimize-autoloader": true,
    "platform": {
    "php": "7.0"
  }
},
"scripts": {
  "post-root-package-install": [
    "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
  ]
},
  "repositories": [
    {
      "type": "path",
      "url": "plugins/redactor"
    }
  ]
}

The redactor plugin is already installed and working properly, so I'm not sure why it's causing an issue. Does anyone know what's causing this issue and how to fix it? Any help is appreciated.


texts: Fetching Existing Users In Users Field Doesnt Work When entries.saveEntry Event Triggerred From Frontend

texts:
As the title says, I can successfully return the "existing user IDs" from an entry field if the "entries.saveEntry" event is called after saving the entry from the CMS admin area; however, if I save an entry via a front-end form, the same code produces empty results.

I've used xDebug to verify that the objects are the same line by line; somehow the data isn't there for $users->ids() for front-end triggered events.

// get entry
$entry = craft()->entries->getEntryById($entryId); // elementType => "Entry"

// get ALL users related to entry
$users = craft()->elements->getCriteria(ElementType::User); // elementType => Craft\UserElementType
$users->status = null;
$users->relatedTo = [$entry]; // elementType => "Entry"
$userIds = $users->ids(); // elementType => Craft\UserElementType

Example result when triggered from backend (good):

array(
    0 => 251,
    1 => 252,
    3 => 257
)

Example result when triggered from front-end (help!):

array()


texts: How do I hook into Capture form onPost event?

texts:
I am writing a new plugin to hook into a POST event from a bespoke form plugin called "Capture". The Capture plugin fires two different events; the code taken from /craft/plugins/capture/services/Capture_SubmissionsService.php

public function onBeforePost(Event $event) {
    $this->raiseEvent('onBeforePost', $event);
}

public function onPost(Event $event) {
    $this->raiseEvent('onPost', $event);
}

I called die(); inside each one so I know they are being called.

My new plugin is very simple. I would like to be able to hook into the onPost event and receive the form data. My plugin is very simple for now as I am just concerned with hooking into the event. The below example has getName, getDeveloper, getDescription, getVersion etc removed for ease of reading. This is the only file in my plugin: /craft/plugins/myplugin/MyPlugin.php

<?php
namespace Craft;

class MyPlugin extends BasePlugin {

   public function init() {
      craft()->on('capture.onPost', function(Event $event){
         die('onPost <pre>'.print_r($event,true).'</pre>');
      });
   }
}

But this doesn't seem to be get called. I am assuming that I need something other than capture.onPost.

I have used the following docs, but would appreciate any help.

https://craftcms.com/docs/plugins/hooks-and-events

https://craftcms.com/docs/plugins/events-reference


texts: Order confirmation emails not being sent to guests

texts:
For some reason, order confirmation emails are being sent to customers who create an account during checkout but not if they checkout as a guest. I also see the error: Email error. No email address found for order. in the commerce.log file. Anyone know how to get the order confirmations to go out to guest users too? The emails are getting captured, as they show up in the backend. I'm using the latest versions of Craft and Commerce. Thanks!

Update: Even changing the order in the admin to another status and back still does not trigger an email to the user.


texts: How can I group entries based on a string value?

texts:
I have been able to successfully group entries via dateTime field. I have been trying to carry over the same type of logic only instead of using .date just key off of the field value.

{# Get all entries from the section. #}
{% set entries = craft.entries.section('mySection') %}

{# Loop through the entries and get the user account associated with each. #}
{% for profiles in entries %}
    {% set users = profiles.userAccount %}

    {% if users|length %}
        {% for year, user in users|group('myYearField') %}

{{ year }}
 {# 2016 #}

                {% for user in users %}

{{ user.name }}

                {% endfor %}

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

Currently what I am getting is:

2016
    User
2016
    User
...

What I am trying to get (I swear I had this working at one point) is this:

2016
    User
    User

2017
   User
   User

EDIT

It seems my trouble comes from not accessing the users field correctly.
Updated (but still incorrect) example:

{% set allProfiles = craft.entries.section('mySection') %}
{% if allProfiles|length %}
    {{ allProfiles|length }} {# 3 #}
    {% for profiles in allProfiles %}
        {% for profile in profiles.userAccount %}
            {% for year, user in profile|group('yearFieldHandle') %}

{{ year }}
  {# No output #}

{{ profile.firstName }}
    {# Bob #}

{{ profile.myYear }}
 {# 2016 #}
            {% endfor %}
        {% endfor %}
    {% endfor %}
{% endif %}


texts:
I am using the normal relatedTo property to find related articles, but I have an issue which is:

craft.entries.section('section').relatedTo("tags").id('not ' ~ entry.id).limit(3)

Lets say THIS article has 2 tags: "cat" and "animal",
then I use the normal relatedTo property to get related articles.
Lets say i want three articles

Sometimes I get these three:

article 1 (tags: "dog" and "animal")
article 2 (tags: "cat" and "food")
article 3 (tags: "mouse" and "animal")

But not this one:

article 4 (tags: "cat" and "animal")

How can i get the MOST related articles always? I want the one that has the most matching tags, not just random ones that has at least 1 tag.


texts:
I'm trying to create a plugin with a controller, but I don't want to render any view but run a script from a cronjob. I can't get into the controller with an url and I'm not sure why.

I already tried everything here but it does not state any way to directly call a controller with an url. Is this possible?


texts: Limit search results for users by tag (and limit to 5 tags)

texts:
I've read as many forum posts and documentation but am a little stumped over a specific use-case. Currently the search page grabs the url segment, loops through a verified user group, and uses the .shuffle() function to randomise order.

I'm looking to limit search results using relations with a customTagsField on a user's profile. It also needs to limit results using only the first 5 tags that the user has entered in customTagField, in the order they are arranged in control panel.

Search Results

    {% set query   = craft.request.getParam('q') %}
    {% set results = craft.users.group('verified').search(query) %}
    {% set users   = shuffle(results) %}

    {% if users|length %}

{{ users|length }} results:

        {% for user in users %}

{{ user.fullName }}

{{ user.intro }}

                            View counsellor

        {% endfor %}

    {% else %}

Your search for “{{ query }}” didn’t return any results.

    {% endif %}

I'm still a bit confused about relatedTo as well as source and target terminology, even though I've read quite a bit about it!

Is it as simple as changing results to:

{% set results = craft.users.group('verified').relatedTo(customTagsFieldHandle).search(query) %}

It doesn't seem possible to limit the tags searched using relatedTo (as you can with craft.tags, so I expect I'll have to edit the for loop somehow. I know about Twig's slice function but I'm not sure how to go about limiting by a user's tag entries.

Does anyone have suggestions for the optimal way to achieve this?


texts: How to make an HTTP request from a plugin?

texts: I'd like to be able to make HTTP requests from within my plugin to hit an endpoint and get a response. How can I do this?


texts: How might I select specific data in an entry to be displayed when selecting an entry?

texts:
I am not sure if i need a plugin to accomplish a specific task or if Craft CMS can natively handle this task.

I created bios for people in a channel of bios. Each entry has a Job Title text field to store a single job title.

So, I want to store a list or array of multiple job titles for each person/entry. Then, I want to choose which job title is rendered when I use the entries field to select a bio to render.

Any ideas? Thank you.


texts: Craft Commerce: Duplicate Input for Address State?

texts:
In the Address section I have been defining UK counties to populate the State field when a Country is selected. I noticed that there is a standard text input when there is no defined states/regions/areas for a country and a drop down field for states when there is defined states.

When a country like the US or the UK is selected both fields are shown however ideally it should only be the dropdown. See image of the problem:

Is there any logic that can be added to toggle it on/off ?

<label for="{{ modelName }}-state">County / State / Region</label>

{% set options = (model and states[model.countryId] is defined ? states[model.countryId] : []) %}
<select id="{{ modelName }}-stateId" data-modelname="{{ modelName }}" class="address-stateId u-full-width {% if options|length == 0 or (model and model.stateName) %}hidden{% endif %}" name="{{ modelName }}[stateValue]">
  {% for key, option in options %}
    {% set optionValue = (model ? model.stateId : '') %}
    <option value="{{ key }}" {% if key == optionValue %}selected{% endif %}>{{ option }}</option>
  {% endfor %}
</select>

<input type="text" data-modelname="{{ modelName }}" id="{{ modelName }}-stateName" class="address-stateName {% if options|length > 0 or (model and model.stateId) %}hidden{% endif %} u-full-width" {% if model and model.stateName %}name="{{ modelName }}[stateValue]" value="{{ model.stateName}}"{% endif %}>


texts: Prescribed way to set cookies (from plugin or Twig)

texts:
From either a plugin or a Twig template, is there a prescribed way to set (and get) cookies?

I've seen https://github.com/lewisjenkins/craft-lj-cookies/, which just uses PHP's setcookie.

Also noticed getCookie in craft.request. https://craftcms.com/docs/templating/craft.request#getCookie

I've noticed the cookies set with setcookie aren't readable by getCookie. How should one set a cookie so that it is readable by getCookie?


texts:
I'm looking to eager load and set another variable within the eager loading. But I can't seem to find out how on numerous guides/tutorials, and the query seems to be slowing the system down a bit.

  {% set entries = craft.entries ({
          section: 'events',
          order: 'postDate desc',
          with: ['eventMainImage'],[''],
          relatedTo: category
      }) %}

  {% for entry in entries %}
    --> {% set venue = entry.eventVenueId.one() %}

As you can see by the arrow, I'm wanting to set this property, is this possible within an eager load?


texts: How can I get the current user who purchased a product from the onOrderComplete event?

texts:
I have a plugin that is listening to the onOrderComplete event within commerce. I am able to get the email address like this:

craft()->on('commerce_orders.onOrderComplete', function (Event $event) {
    $event->params['order']->email;  // name@email.com

});

I can see the Id in the log, but since I'm in the order class, I'm not sure how to get to it. I can see customerId:

$event->params['order']->customerId; // 3

But I've noticed the customerId and the userId are different. I need to be able to get the logged in userId vs. the customerId

When I try getting just the id, I get the product id back (Which is what I would expect).

$event->params['order']->id;  // 123

To relate to the twig side it would be something like this (obviously won't work):

$event->params['order']['currentUser']->id;  // 12

Here is a part of the log:

...
[_attributes:Craft\BaseModel:private] => Array
(
    [enabled] => 1
    [archived] => 0
    [locale] => en_us
    [localeEnabled] => 1
    [itemTotal] => 375
    [baseDiscount] => 0
    [baseShippingCost] => 0
    [totalPrice] => 375
    [totalPaid] => 375.00
    [billingAddressId] => 122
    [shippingAddressId] => 123
    [paymentMethodId] => 1
    [customerId] => 3
    [id] => 12   //  <-- This guy right here
    [orderStatusId] => 1
...


texts:
I have ajax submitting my form everything works except the user image. It works without ajax but not sure why it's not working with ajax. My ajax is and form are shown below.

<form method="post" enctype="multipart/form-data" id="profile-form" action="" class="form" accept-charset="UTF-8">

    {{ csrfInput() }}

    <input type="hidden" name="action" value="users/save-user">
    <input type="hidden" name="redirect" value="account">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">
    {{ redirectInput('my-program/account') }}

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

    <input type="hidden" name="userId" value="{{ currentUser.id }}">

            {% if currentUser.getPhoto != '' %}

            {% else %}

            {% endif %}
            <input type="file" id="userPhoto" name="photo" value="Upload">

Change Avatar

                Name

                <input type="text" id="fullName" name="fields[fullName]" value="{{ currentUser.fullName }}">

                Role

                <input type="text" id="userRole" name="" value="Your Role here">

                company

                <input type="text" id="company" name="fields[company]" value="{{ currentUser.company }}">

                email

                <input type="text" id="email" name="fields[email]" value="{{ currentUser.email }}">

            <input type="submit" value="Save Changes" id="saveProfile" class="dark-btn">

</form>

$("#profile-form").submit( function(e) {
    e.preventDefault();
    var data = $(this).serialize();

    $.ajax({
        method: "POST",
        url: "users/save-user",
        data: data,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        success: function(data, response){
        }
    });
});


texts:
How can I register and login a user in my Controller? I have tried something like this:

$newUser = new User($userName, $userPassword, $userEmail);
Craft::$app->elements->saveUser($newUser);


texts:
I've got a few issues with a site but I'll try to separate in case they're not related.

Firstly I keep getting "Failed task - Deleting stale template caches".

I've looked in the logs and some messages include:

  Encountered an error running task 3 (DeleteStaleTemplateCaches), step 156 of 166: An exception was thrown: CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'dateCreated' in order clause is ambiguous

and

  CDbCommand::fetchAll() failed: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'dateCreated' in order clause is ambiguous. The SQL statement executed was: SELECT elements.id, entries.sectionId, entries.typeId, entries.authorId, entries.postDate, entries.expiryDate


texts: Get random entries from a section but keep the order of these when splitting the array

texts:
So I want to get 9 random entries from a section and I do this like so:

{% set artists = craft.entries
  .section('artists')
  .artistImage(':notempty:')
  .with(['artistImage'])
  .orderBy('RAND()')
  .limit(9) %}

Now I want to split these entries into a row of 4 and a row of 5. I am doing this like so:

  {% for entry in artists|slice(0, 4) %}

      {% include '_includes/_components/image.twig' with {
        image: entry.artistImage[0],
        alt: 'Artists',
        transform: 'square',
        classes:'w-full',
        sizes:'(min-width:576px), 100px, 25vw',
        widthEnd: 800
      } %}
      {{ entry.title }}

  {% endfor %}

  {% for entry in artists|slice(4) %}

      {% include '_includes/_components/image.twig' with {
        image: entry.artistImage[0],
        alt: 'Artists',
        transform: 'square',
        classes:'w-full',
        sizes:'(min-width:576px), 100px, 20vw',
        widthEnd: 800
      } %}
      {{ entry.title }}

  {% endfor %}

However, this seems to randomise the each split and sometimes I get duplicate entries in each split.

Ideally, I want to get 9 random items and then keep this order and split this into to separate rows.

How can I achieve this?


texts: How do I output a file’s URL in a Matrix field?

texts:
I have a Matrix field with Image, Caption, and PDF sub-fields. I can output the Image and Caption fine, but am having no luck with the PDF file.

Here is the code:

{% for block in entry.seriesInformation %}
    {% if block.type == "bladeImage" %}

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

        {% if image %}

        {% endif %}

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

        {{ block.caption }}

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

Download &rarr;

    {% endif %}
{% endfor %}


texts: How do I add a subcategory to the URL slug for a channel entry?

texts:
I'm trying to mimic the URL structure exactly how I have it in my old CMS. If I select an entry to have both a category and subcategory I would like to have the subcategory in the URL along with the category and the entry slug.

For Example

http://example.com/cat1/subcat1/entry

Right now I have the Entry URL Format set to be {category.first().slug}/{slug}, but that only shows the first category. How do I access that optional subcat1 subcategory in that field?

EDIT

I have tried the following but it doesn't work

{category.first.slug }/{ category.first.children.first.slug ? category.first.children.first.slug ~ '/' : '' }{slug}

I have also tried

{category[0].slug}/{ category[1] ? category[1].slug ~ '/': ''}{slug}


texts: Return all cache records, delete caches with prefixed keys

texts:
Does craft()->cache-> have a way of returning all the cache records?
I need to delete some caches, but only if the key begins with a certain prefix, “ranking__getAthletePoints_”. I won’t know the numbers following in the key names. If I could grab all of them, I assume I could check against the key names with something like startsWith() and delete the correct caches that way.

Very much out of my element with php & plugin development! Thanks for any help!


texts: Batch saving a custom field to multiple users via controller

texts:
I have to build a custom plugin for an internal user management system/data export that needs to be able to get triggered from the CP.

I basically have to sort a big amount of users (1500+) in a specific plugin tab in the Control Panel. The sorting is done via Vue/JS. When I am done sorting the users I need to be able to trigger and save a field (a string I will enter in the CP Tab) for all of those users in the same order as it was sorted in the CP.

For now, I have simply sent an array of User Ids to my plugin controller via post request:

public function actionSubmitRef()
{
    $request = \Craft::$app->getRequest();

    $userIds = $request->getParam( 'userIds' );
    $refNumber = $request->getParam( 'refNumber' );

    $response = [
        'userIds' => $userIds,
        'refNumber' => $refNumber,
    ];

    WFWPlugin::getInstance()->saveNewReferenceNumber( $userIds, $refNumber );

    return $this->asJson( $response );
}

The controller passes the array of Ids and the string to save to a function that saves the string to each user:

public function saveNewReferenceNumber( $userIds, $refNumber )
{
    $i = 0;

    foreach ( $userIds as $userId ) {
        $i ++;
        $user         = Craft::$app->users->getUserById( $userId );
        $tableValue   = $user->getFieldValue( 'aktionsRefNumber' );
        $tableValue[] = [
            'col0' => $refNumber . '-' . $i,
        ];

        $user->setFieldValue( 'aktionsRefNumber', $tableValue );
        $success = Craft::$app->getElements()->saveElement( $user );

        if ( ! $success ) {
            Craft::error( 'Couldn’t save the entry "' . $user . '"', __METHOD__ );
        }
    }
}

The problem is that with this huge amount of save requests, PHP either times out or it simply can't be processed. I end up with having a max of 40 saved uses with the right value in the field.

How could i solve the issue? I have recently asked the question in the discord dev channel and using a console command has been suggested, but since the users need to be sorted in the CP, the string has to manually be entered and then triggered via a button, I couldn't get it to work.

Another approach was to push each save request into a yii2 job queue but that didn't help either...

Thanks for the help, much appreciated!


texts: List only Orders containing specific Products

texts:
Each Product has a Merchant field which is standard Craft User. What I'd like to do is list out all Orders which contain one or more Products relating to the currentUser. I was hoping I'd be able to use Relations to accomplish this, so something like this:

{% set products = craft.commerce.products({
  'relatedTo': currentUser
}) %}

{% set orders = craft.commerce.orders.relatedTo({
  'sourceElement': products,
  'field': 'lineItems.purchasable.product'
}).find %}

The first query works fine and returns only the Products relating to the currentUser, but when I try to use it as the basis for the second query, that's where it collapses in a big heap! Am I in the right ballpark, or isn't this possible in the way I'm trying?

Any help gratefully received.


texts: Multi-lingual site navigation made of singles, channels and structure

texts:
Does anyone have any examples of how they've put together the main site navigation for a multi-lingual site set-up made up of singles, channels and structure?

At the moment I've just hard-coded the nav and done and if else on the locale ID but would like to know if there's a more flexible, future-proof method.


texts: Error on updating Craft install with Sprout vendor files

texts:
I was updating an Craft install on Mediatemple server yesterday. Im now getting the following error:

Cannot use barrelstrength\sproutbase\app\import\base\FieldImporter as FieldImporter because the name is already in use

I tried creating a new install but I get the same error - any ideas what I can do to rectify?


texts:
The newer versions of Craft CMS stimulate using environment variables in the CP. It works perfectly. I have set two variables for sites in my .env file:

DUTCH_SITE_URL="http://company.test"
ENGLISH_SITE_URL="http://company.test/en"

One thing that's not clear to me is the right way to request the baseUrl in templates. For example: I'm using a simple language switcher to switch between two languages:

{% set sites = craft.app.sites.getAllSites() | without(currentSite) %}
{% for site in sites %}

{{ site.language }}

{% endfor %}

When viewing the Dutch website the language switcher shows the link to the English website. The problem is that site.baseUrl outputs the environment variables instead of the English site url. The link looks like this:

http://company.test/$ENGLISH_SITE_URL

What's the proper way to deal with this?


texts: Craft 3 Cache Busting for Pending Entries

texts:
So in Craft 2 the following code was required to cache bust if an entry was set to pending or post at a future date.

{% set firstPending = craft.entries({
  section: 'projects',
  status: 'pending',
  order: 'postDate asc'
}).first %}
{% set cacheUntil = firstPending ? firstPending.postDate : now|date_modify('+1 year') %}

{% cache globally using key craft.request.path until cacheUntil %}

content
{% endcache %}

Is this still required in Craft 3 or is there some magic that now happens in the background?


texts: How can I add data from my custom plugin to the Entry Listing table?

texts:
I've built a custom field that stores its data in its own table. How can I get data from MyCustomField to show up as a column in the Entries Table?

A few details:

My custom field is made up of multiple fields, in this case a Date/Time field and a text field.
My custom field is is returned as an array by the prepValue() function in my fieldtype file.
Not every entry will have a record in my custom field's table

How can I check to see if a value exists in my custom field's table for an entry and display it in the Entries Table?

I'm copying this over from the Craft Slack channel so we don't lose the solution.


texts: How do you programatically add a user to a user entry field

texts:
I have created a controller called myPlugin_Controller.php

This is the following code inside it.

 <?php
class myPluginController extends BaseController
{
    public function actionSave()
    {

        $this->requirePostRequest();

        // get all the post variables
        $elementId = craft()->request->getPost('elementId');
        $userId = craft()->request->getPost('userId');

        // set the name of the field you want to update
        $fieldHandle = 'friends';

        // based on the element and field vars, get the models for each
        // using the elements and fields services
        $element = craft()->elements->getElementById($elementId);
        $field = craft()->fields->getFieldByHandle($fieldHandle);

        // store the current ids into a variable
        $currentIds = $element->{$field->handle}->ids();

        // merge the new id into the current ids
        $newIds = array_merge($currentIds, (array) $userId);

        // save the new array of ids, using the relations service
        craft()->relations->saveRelations($field, $element, $newIds);

        // redirect to the redirect url
        $this->redirectToPostedUrl();

    }
}
?>

This is my code in an html file, it is submitting some data however it returns a 404 error.

   <form method="post" accept-charset="UTF-8">
                  {{ getCsrfInput() }}
              <input type="hidden" name="action" value="myPlugin/Save">
              <input type="hidden" name="redirect" value="/success">

              <input type="hidden" name="elementId" value="{{ user.id }}">

              <input type="hidden" name="userId" value="{{ currentUser.id }}">

              <button type="submit" >Submit</button>
          </form>

i'm not too sure where its going wrong now.

Also if your wondering why its called user this is why
        {% set user = craft.users.username( craft.request.segment(2) ).first() %}
Do you know where I am going wrong now any tips or help is all appreciated! :)

Still not working I have looked at craft cms documentation online i've followed your steps and there steps.

Is there anything you can still see that is wrong?


texts: Change the size of a users profile photo?

texts:
I have a website where I am pulling a list of staff members from the Craft users. You can add individual fields to the users element, but it seems the image for the photo is incredibly small is size and lacking in quality.

Is there a way to change the size of the profile photo? Hopefully I can just apply an image transform on the user profile photo. Adding another field for a photograph seems redundant.


texts: Saving new entry via Ajax then immediately showing it

texts:
I’ve created a very simple comments system whereby comments are set us a channel, with each (comment )entry related to a main entry from another section. Works fine. I’ve set up editing and deleting the comment via Ajax, but I’m stuck on saving it.
I’ve got the form submitting successfully via ajax, but I want to be able to display it immediately after it is saved/posted.
The successful response I get gives me the author username, entry id, date etc, but not the actual comment field. I also need to display additional user details.

I’m not quite sure on best way to tackle this. Just looking for a pointer in the right direction. Cheers!


texts: Search for entries where a field value is between multiple ranges of numbers

texts: I currently have this working for a single range of numbers, but I can’t figure it out for multiple ranges. I currently have it set up like this for one range, and it works. myFieldHandle: ['and', '> 0', '< 10'].


texts: adding a block of matrix field from a front end entry form

texts:
I am trying to add a form to the frontend in which a registered user will be able to create and publish new block in a matrix field. I have read the documentation about it but am still failing miserably in achieving it...
The entry is part of a structure section with sectionId movementCoursesEntries. The matrix fieldId is videos. The blockId is video_box and it has two plain text fields videoTitle and videoUrl.
I have used this code but what I am getting is that the after submitting the form, all the old matrix blocks are being deleted and the new one is not being created. Any advice is highly appreciated!
<form method="post" accept-charset="UTF-8">
    {{ csrfInput() }}
    {{ actionInput('entries/save-entry') }}
    {{ redirectInput('/members-zone/{slug}') }}
    {{ hiddenInput('movementCoursesEntries', '2') }}
    {{ hiddenInput('enabled', '1') }}
    {{ hiddenInput('entryId', entry.id) }}

    {% if entry is defined %}
        {# Retain existing blocks + sort order #}
        {% for video_box in clone(entry.videos).anyStatus().ids() %}
            {{ hiddenInput('fields[videoTitle][sortOrder][]', video_box) }}
            {{ hiddenInput('fields[videoUrl][sortOrder][]', video_box) }}
        {% endfor %}
    {% endif %}

    {# Add a new text block #}
    {{ hiddenInput('fields[videoTitle][sortOrder][]', 'new:1') }}
    {{ hiddenInput('fields[videoUrl][sortOrder][]', 'new:1') }}

    {# Prefix the block's input names with `fields[<FieldHandle>][blocks][new:1]` #}
    {% namespace "fields[blocks][blocks][new:1]" %}
        {{ hiddenInput('type', 'text') }}
        <input name="fields[videoTitle]">
        <input name="fields[videoUrl]">
    {% endnamespace %}

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


texts:
I'm having issues forcing an SSL on my website. I think the issue may be that my root folder is my 'web' folder.

I've searched online and tried a few variations of htaccess but none of them seem to work.

Here is the latest I've tried:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

My domain points to my web folder and my htaccess belongs in the web folder.

Thanks,

Joe


texts:
I have a long entry list of authors and I am using global cache to help with the page load, but this global cache prevents the if statement from adding selected to the appropriate option. When I remove the global cache everything performs as intended.

<select name="filter-by-author" onchange="window.location.href=this.value;">
    <option value="/blog">All Authors</option>
        {% cache globally %}
            {% nav author in craft.users({ group: 'blogAuthors', order: 'firstName', limit: null }) %}
                <option value="{{ url('blog/author/'~author.username) }}"
                {% if craft.request.getLastSegment() == author.username %}selected{% endif %}>
                {{ author.name | title }}
                </option>
            {% endnav %}
        {% endcache %}
</select>


texts: Sharing Entry Types Across Sections (or Breaking Them Out Altogether)

texts:
First of all, I'm loving Craft. So refreshing (even coming from EE). Kudos to the team.

I'm curious if anyone has had similar views on Craft's handling of Entry Types. It would seem favorable to allow sharing of them across Sections or, better yet, break them out altogether as a separate entity so that in Settings > Content you'd have the option for Fields, Sections, Entry Types and so on.

For example, to create a 'Common' Entry Type usable across multiple Channels I currently have to rebuild it for each channel. If Entry Types were broken out, I could simply choose from those available.

On the other hand, I admittedly may not be approaching Entry Type usage in the best manner possible. Does anyone have any thoughts?

Cheers.


texts: Response: {"error":"Undefined index: fieldGroup"}

texts:
I've recently had to handle a massive merge on a Craft project which resulted in many conflicts in the project.yaml file. I tried to clean up the merge conflicts as best as I can.

And now I have this error:

Question now is there a way to recover or re-generate the project.yaml?

Also, this my first experience working with Craft in a team. Any suggestions on best approach to keep project.yaml clean?


texts: Using auto-generated titles against entry field type values

texts:
How would you setup a section's entry type to auto-generate the titles based on the title (or slug) of another entry?

For example, we have a Software section with entries. We also have a Releases section. Each release entry has a related software entry, along with a versionNumber text field.

Ideally each release's title would be of the form :

{software.title} {versionNumber}

Where {software.title} is the title from associated entry.

We've looked at all sorts of combinations to get that value out, but any usage seems to either be ignored or throw an error on publish.


texts: Is there any plugin for Blog in Craft 3?

texts: I want to create a Blog website in craft cms. I would like to know, is there any plugin for Blog which we can use in Craft similar kind of WordPress?


texts: Eager Loading Relatedto & Target Elements

texts:
I have quite a substantial amount of queries heading out for this bit of code below. I've tried quite a few things to get it down, but I need to eager load some things just to try and reduce the overhead of this, but I still think it won't do enough. Is there anything I can look at to optimise this?

    {% set brandIds = craft.entries().section('brands').relatedTo({ targetElement: category }).ids() %}
    {% set offers = craft.entries().section('offers').relatedTo(brandIds).limit(6) %}

    {% for entry in offers %}

              {% for asset in entry.relatedBrand.one.brandLogo.all() %}

              {% endfor %}

{{ entry.title }}

{{ entry.body }}

              {{ entry.relatedBrand.one }}

  {% endfor %}


texts: “Service Unavailable” message when not logged as admin

texts:
I am junior web developer I am setting up my first website with Craft CMS. I have been getting the "Service Unavailable" error message on my site every time I try to enter not logged in as admin. I've done some searches on this StackExchange site and tried setting again the permissions for craft/app/, craft/config/, and craft/storage/ as told in the installation docs, but didn't work. I've also tried modifying the .htaccess as told in other thread, but still didn't work.

Any help would be very appreciated. And forgive my ignorance since I'm very new to this CMS :D.


texts: How to get all entries posted within a specific year?

texts:
I am trying to get all entries posted from 2018 and only 2018. All the other methods I've seen are for from a specific date or between two dates. Is there a simple way to get all posts from 2018 without having to specify get all entries between 1 January 2018 and 31 December 2018?

The markup below is where I have got to, but this is getting all entries from 2018 onwards. But when I change the >= parameter to == it appears to break it.

{% set event = craft.entries.section('events').startDate('>=' ~ formYear).one() %}


texts: Craft Commerce Adjuster API/PHP questions

texts:
I've got a module set up to add discounts based on criteria defined in a category group (handle 'productPacks') -> category (which is a "pack").

Now, everything works great for one type of pack, and subsequent counts on that single pack, but as soon as there's other parts in the cart that correspond to other packs from the category group, no discounts are applied.
I'm missing some logic in the code for how to distinguish and override a more expensive pack based on related products and which variants of that product are allowed to apply the larger discount based on said criteria.

I can't seem to get it to work so that each category is pushed as an adjustment into the adjustments array.

What am I missing? I'm checking cart contents against a category’s "related products" commerce product field (handle 'relatedProducts'), and then against which variants in those products are allowed (a commerce variants field with handle 'productVariants');

https://github.com/23d1/productcombos/blob/master/src/adjusters/OrderAdjuster.php

I'm simply checking the contents of the cart against the contents of a products field and a variants field in a set of categories in a specific category group. So no real relational stuff, simply comparing things to apply a discount amount that is a simple number field on the category it finds inside the specific category group (with the handle 'productPacks').


texts: Pull all assets from a specific volume subfolder id

texts:
Is there a way to pull all assets from a volume subfolder id?

{% set entries = craft.entries.section('pages').type('genealogy').search('pageType:stake') %}
{% for entry in entries.all() %}
    {% if entry.id == x %}
        get all assets from volume subfolder a
    {% elseif entry.id == y %}
        get all assets from volume subfolder b
    {% endif %}
{% endfor %}


texts: What is the difference between 'nav' and 'for' for looping?

texts:
I am new to craftcms and did a look through on the documentation just recently.

I am at the part where it explain about the Categories Field and found out that we can loop through the ElementCriteriaModel with the 'nav' keyword instead of 'for'.

I checked the twig documentation but there are no 'nav' keyword :|

So which one should I use?


texts: Check Structure for Entry or Child of Entry

texts:
I have setup a few different navigation lists through the Menus 0.9 plugin by Familiar. Within my website, I have setup several different site sections all through the same structure called, "General". They all share the same page template.

I would like to run a check to see if the page is "About" or is a child of "About" (all within the "General Structure"). If it is "About" or a child of "About", I would like to server it a specific sub-nav.

Here's the code to run that subnav:

{% nav node in craft.menus.getNodes('aboutSubnav') %}

{{ node.title }}

{% endnav %}

How do I do the lookup to see what page it is? I tried the following code, but it did not work:

{% if entry in craft.entries.section('general').descendantOf(42) %}
 {% nav node in craft.menus.getNodes('aboutSubnav') %}

{{ node.title }}

 {% endnav %}
{% endif %}


texts: Remove related / suggested videos from the end of an embedded YouTube video

texts: I'm using the Dukt Videos plugin v1.2.5 on Craft v2.7.2. Is there a way to control or remove the video suggestions that are displayed once my video has played through to the end. Or perhaps have the video restart once it reaches the end ?


texts:
I'm just wondering here if something like this is possible. On a website I'm working on for a photographer, he's in need of carefully selecting focal points on his images.

I'm aware of the focal point plugin, but that is connected to the assets file itself. And not the entry. So basically what I'm asking is

Is it possible to:

Upload the full source image to assets
On an entry, select this
image
Have a separate field with a GUI control of the cropping of
selected image from point 2.

Save the entry. And Craft takes those parameters and generates the new image and puts it in the destination folder. So the new cropped image is not in Assets at all.

The reason for this need is because the photographer wants full control of the focal points of each image.

TLDR:
Is it possible to a use something similar to this gui control on a field where an image has been selected, instead of having it directly on the assets file?


texts:
This has to be something that is easy, but I've been beating my head on my desk for a a few hours with this.  Most solutions I have come across are way to complex - when all I need to do is query a section for all entries that appear in two categories.

I'm pulling in the slugs via url,

ex: domain.com/investigators?t=primary&a=pregnancy-newborn-medicine

Then querying like so:

{% set typeQuery = craft.app.request.getParam('t') %}
{% set areaQuery = craft.app.request.getParam('a') %}

{% set cat1 = craft.categories.group('investigatorTypes').slug(typeQuery).one() %}
{% set cat2 = craft.categories.group('areaOfResearch').slug(areaQuery).one() %}

{% set researchers = craft.entries()
    .section('investigatorBios')
    .relatedTo(['and',
        {element: cat1},
        {element: cat2}
    ])
    .orderBy('bioLastName asc')
    .limit(12)
%}

What am I doing wrong?
Slugs match the respective categories in the groups.  There are only two types in the investigatorTypes I can query for - one returns all of them, and the other returns none.

Am I overlooking something obvious?

Thanks in advance, friends.


texts:
Is it possible to create a matrix block with no fields? I'm using matrix as a page builder and have several scenarios where certain matrix blocks simply act as true/false checks.

As an example, my Horizontal Rule block simply adds an '< hr >' tag to the page. No fieldtype is needed for this block.

I can add a dummy text field to the block that does nothing, but this is not too elegant. Any ideas?


texts: Exclude categories that are not associated to any entry

texts:
I have a set of categories that I would like to display on a sidebar as a way to filter the list of entries displayed. However, some of those categories haven't been associated with any entries yet so clicking on that category with return 0 results.
What is the most efficient way to exclude those categories?


texts: Changes made in home page not displaying

texts:
I am new on Craft CMS and it's the first CMS I am trying. Hey guys, I apologies is this question was asked before. I went through lot of articles and I didn't get anything helpful yet. I added  in home.html, made changes to var.scss and home.scss so that the background color of the  can be gray.

When I open the project in the browser the  is not displaying but it's visible during inspection.

How can I fix this problem?


texts: User activation via email does not work when system status is "off"

texts:
System Status is set to off
Create a new user, with permissions to Access the site when the system is off and Access the CP

As long as the system is off, the activation email sent to the user is broken, and instead goes to the "Service Unavailable" page.

Is this by design? It seems like if those specific permissions are granted when creating the user, they should still be able to activate.


texts: Getting related entries along with entry using the Element API plugin

texts:
I want to list all the related entries to the entry I am displaying using the Element API plugin.

I have a channel called series and another called episodes, the episodes have a relationship with 1 series.

I am pulling in the series ok:

'api/series.json' => [
    'elementType' => 'Entry',
    'criteria' => ['section' => 'series'],
    'transformer' => function(EntryModel $entry) {
        return [
            'title' => $entry->title,
            'url' => $entry->url,
            'jsonUrl' => UrlHelper::getUrl("api/series/{$entry->id}.json")
        ];
    },
],

Then I am pulling in a series:

'api/series/<entryId:\d+>.json' => function( $entryId) {
        return [
            'elementType' => 'Entry',
            'criteria' => [
                'id' => $entryId
            ],
            'first' => true,
            'transformer' => function(EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'image' => $entry->seriesHero,
                    'description' => $entry->seriesDescription
                ];
            },
        ];
    },

In the endpoint above I want to be able to output an array of the episodes related to this series.
The relationship field in the episode channel is called series.

What is the best way to do this?


texts: Is there an easy way to return the total number of entries in a Super Table within a Matrix field?


texts: Is it possible to override the default session notices?

texts:
I couldn't find anything on here about this. Maybe I'm the only one, but for example when you log in there is a session notice with the message "Logged in.", but I want it to display something like "Good to see you" or something.

I can see the notices are set via Craft::t(), so I would assume they are translatable somehow, so can I do this through configuration files or a plugin init method or something?


texts: Populate select input via static values on plugin settings page

texts:
I am attempting to populate a select input on my settings page for a plugin I am working on.

_settings.html

forms.selectField({
    'label': "myLabel",
    'instructions': "My Instructions"|t,
    'required': true,
    'id': 'myInput',
    'name': 'myInput',
    'options': craft.myPlugin.settings.getOptions
})

I am getting the select to render, but it's just not getting any values.

craft.myPlugin.settings.getOptions links to my variable file for my plugin.

MyPluginVariable.php

public function getOptions()
{
    error_log(__FUNCTION__);  // Never gets executed
}

I thought maybe I could just return a name|value array in my getOptions method.

return array('one'=>'one', 'two' =>'two');

The value(s) that this select will have are literally that easy and will never change. That's why I was going this route vs. a db lookup.

I get errors that the value needs to be a string, so I know I can't just have an array right in the settings file. Not exactly sure where to go from here.

Thank you!

EDIT

Well, I may have a solution, i'm curious if there is a better way though.

MyPlugin.php

public function getSettingsHtml()
{
    $options = array(
        '' => 'Select',
        '1' => '1',
        '2' => '2',
        '3' => '3',
        '4' => '4',
        '5' => '5',
        '6' => '6',
        '7' => '7',
        '8' => '8',
    );

    return craft()->templates->render( 'myPlugin/_settings', array(
            'settings' => $this->getSettings(),
            'options' => $options
        ) );
    }

_settings.html

forms.selectField({
    'label': "myLabel",
    'instructions': "My Instructions"|t,
    'required': true,
    'id': 'myInput',
    'name': 'myInput',
    'options': options
})


texts:
I'm working on getting our site set up with Craft Commerce, and I am currently working on a sidebar cart for the site. I've found examples on how to add products to the cart using AJAX and jQuery and have gotten that working successfully. However, I'm struggling to understand how to update the cart listing after a successful response.

I have the sidebar cart template set up as an include. Is it possible to use AJAX and jQuery to reload just the sidebar cart include after the successful response? Or is there a better way to show the updated contents?


texts: Filter Sprout Form entries throwing error

texts:
Based on this very helpful question I'm trying to filter the display of Sprout Form entries based on the value of a form field.

For example, my form handle is 'reportHazardDeficiency' and my field name is 'company'. My template has craft.sproutForms.entries.formHandle( 'reportHazardDeficiency' ).company( 4 ) and I get

Database Exception – yii\db\Exception Unknown column 'reportHazardDeficiency.field_company' in 'where clause'

I'm running craft3 and Sprout Form trial version 3.0.0-beta.16.


texts:
When importing local user assets to a development server with sftp (including a database import), some of the assets are missing (it gives the impression to be random). Even after updated the indexes.

When I try to access them directly in the browser, I get a Page not Found, but they are well present on the server, within the same folder/name.

How It is possible ?


texts: RedactorClips and RedactorStyles plugins not working

texts: I have both Redactor Clips and Redactor Styles plugins installed, but neither seem to affect my rich text editor (i.e., i don't see any extra buttons). Are there known issues?


texts: What's the configuration to enable Craft for free CloudFlare and Railgun?

texts:
This is the host-installed version of CloudFlare/Railgun as offered very successfully at Arcustech.

The arrangement is different from Railgun offered with the $200/month CloudFlare Business plan. It is free, and it takes a different approach to configuring the connection between your site and Railgun's high-speed server.

The configuration needs to operate properly with Locale multilingual features, and with SSL coverage for Craft CP admin and Stripe e-commerce pages.


texts: Failed to instantiate component or class error

texts:
I have a site with a custom module that was working fine until just recently but I tried to do a plugin update via CLI and it returned Failed to instantiate component or class "modules\exifreturn\ExifReturn", even though the update did actually complete. But after that, the front and backend of the site were displaying the same error.
I've seen a similar question already about this but the suggested fix in that question isn't working for me. I've also seen some discussion in Discord and have been looking at how NY Studio set up their Devmode repo and as far as I can tell, I've got things set up the same, so not sure why it's not working.
In config/app.php I have:
return [
    'modules' => [
        'exifreturn' => [
          'class' => \modules\exifreturn\ExifReturn::class
        ]
    ],
    'bootstrap' => ['exifreturn'],
];

In composer.json I have:
"autoload": {
  "psr-4": {
    "modules\\exifreturn\\": "modules/exifreturn/src/"
  }
},

and on the server I have this in the modules folder:

Can anyone see what I might be missing?


texts: How can I only allow authors to edit their own entires via front-end?

texts:
I have a front-end form that registered users can log into and edit entries.

I am checking for the correct user group, then also checking for the permission:

{% if currentUser.isInGroup('myGroup') %}

    {# Get the entry #}
    {% set request = craft.app.request.segment(3) %}
    {% set entry = craft.entries.section('mySection').slug(request).one() %}

    {% if entry|length > 0 %}
        {% if currentUser.can('editEntries:7') %}
          {# user can edit the current entry #}
        {% endif %}
    {% endif %}

{% endif %}

All is fine, but if I change the url to another valid url (where the logged in user is not the author) I am still able to see the entry.

Is there a way to prevent that? Is it as easy as just checking/comparing authors? Or is there a more eloquent way? I do have other permissions disabled...

Thank you for any suggestions!


texts: What is the most adviceable way to combine a staging and live database?

texts:
Scenario:

Live server where customer adds content and articles, which are store
in the database
Staging server where we add new functionality, fields, sections and more

When the development of the new functionality on the staging server is complete, it should be merged with the new content of the live server.

How easy is this to handle? Is it as easy as just importing the staging db server into the live server one? Will not existing content be overwritten?


texts:
I'm trying to display the value/price of the default variant for a product.

This is what I currently have:

{% for variant in product.variants %}
  From {{ variant.price|currency(cart.currency) }}
{% endfor %}

This displays the price of every variant that a product has. How can I just display the default variant price? Or better still, the product variant with the lowest price.


texts:
Is there any known way to bootstrap Craft to use the core functions inside another application? For example, in Magento anyone can include a file, initialize the app and use all the functions from there.
This is exactly what i am trying to achieve but in Craft.
Thank you!


texts: How can I bust a template cached plugin variable in a loop?

texts:
In my base template i set some variables  like currency , currency symbol based on the IP address detected. This is done from a geolocation plugin which caches the result (ip,currency, currency symbol,lang) and makes them available to the template as {{craft.geo.info.currency}}

The problem:

Our site is in UK
When a visitor from overseas eg. USA comes they get dollar prices and conversions etc

However, in the product list template I am caching the entry loop with cache tags and rendering the currency symbol with the plugins global template variable like this:

{{ craft.geo.info.currency_symbol |raw}} price XX

USA ip addresses sees US dollars - great!

However in the UK view of product list, and within the product page template loop, we suddenly see the dollar symbol too.

In my footer i spit out the {{craft.geo.info.currency_symbol}} with no cache tags and I get UK GBP currency as I expect.

I guess Craft/Twig is just showing the template cache regardless of plugin variable?

Is there a way around this?

My solution for now is to remove the cache tags from the product list - its not that many products and performance is still good - but I'd like to know how to combine the plugin currency symbol variable within the cached loop.


texts: Possible to have a single entry page with multilingual slugs and only one index.html?

texts:
How can I be able to have a single section page (so that clients can't create another one of this) that only needs 1 index.html template across different languages AND be accessible through following different slugs:

x.dev/muziektoerisme
x.dev/fr/tourisme-musical/
x.dev/en/music-tourism/

I currently have a setup similar to this one: Add home page to a structure?, which is a structure section 'Pages' with my custom page entry type 'musictourism' under 'craft/templates/_pages/_types/' (so 'musictourism.html' sits in this folder)
This works great, except for the fact that users are able to recreate a page of this entry type, which I don't want.

Does my question make any sense? Or am I missing something fundamental here? :) I'm new to Craft by the way.

Thanks in advance!


texts: Any code fixes for "ini_set() has been disabled for security reasons"

texts:
I have two clients using Craft and their hosts will not allow ini_set as they have it as a disabled function in the global php.ini.  I also can't enable in througth a custom php.ini.  Is there any way to modify Craft to get past the ini_set issues?  I have the site all setup, the pages work locally, when I upload to the server we just see a blank page.

Any advice is appreciated as they both do not want to change hosts.

Thanks.


texts: Extending Craft Commerce Purchasable Nav Items

texts:
I'm looking to extend Craft Commerce with a custom Purchasable.

I'd like to implement this using a module if possible.

I've implemented the base class for my new Purchasable and that's all good.

What I'm wondering is can I add this new Purchasable type to the Commerce cpNavItem list?

My new Purchasable extends the base Purchasable class as follows:
class Donation extends Purchasable and I'm registering using the following Events:

Event::on(Purchasables::class, Purchasables::EVENT_REGISTER_PURCHASABLE_ELEMENT_TYPES, function(RegisterComponentTypesEvent $event) {
            $event->types[] = CustomPurchasable::class;
        });

Event::on(Elements::class, Elements::EVENT_REGISTER_ELEMENT_TYPES, function(RegisterComponentTypesEvent $e) {
            $e->types[] = CustomPurchasable::class;
        });

I know that if I go the plugin route I can register a new control panel nav section but I'd like to avoid that if possible and keep this new Purchasable inside of the Commmerce nav section.

kind regards,

piaras


texts: With two EC2 Craft instances, the Control Panel session keeps expiring

texts:
Things were fine (no session logout for admin from CP) when there was only one EC2 instance for our website.
I created a replica of the existing EC2 instance and now when I go to Control Panel, session keeps getting expired every 30 seconds.
Please help me out in order to resolve the issue.
Also, what are the things I should keep in mind when I'm using multiple EC2 instances for Craft website.


texts:
I'm trying to pull through content based on items within a SuperTable entries field.

After searching around I currently have this:

{% set individuals = craft.entries({section: 'barristers', relatedTo: { targetElement: entry, field: 'specialisms.linkToPage'}}) %}
{% for entry in individuals %}
  {{ entry.title }}

But it's not pulling anything through?

Any help appreciated

Thanks