texts: Inserting Relationship Into Entries Field - Plugin Not Saving Relation

texts:
I was hoping someone could shed some light on this issue I'm having. I'm trying to update a relationship field through a plugin, without much success, the entry looks like this:

I saw a post on here regarding something similar here:  Relation row insertion in DB (plugin) so going from that my code at the moment looks like this:

// The id of the entry i want to attach to the relation
$storeId = $formData['storeId'];

// The entry as shown above
$source = craft()->elements->getElementById($entryId);

foreach($blocks as $blockId => $value)
{
 // The matrix block with the relation
 $matrixBlock = craft()->matrix->getBlockById($blockId);

 // Get the 'stores' field
 $fieldId = $matrixBlock->stores->relatedTo['field'];
 $field = craft()->fields->getFieldById($fieldId);

 // Save the relationship
 craft()->relations->saveRelations($field , $source, array($storeId));

}

$blocks is just an array like: array('1092' => 0) and $value will just be determining whether to set or unset the relation.

When I run the above through a controller, no errors appear but no relation actually takes place on the stores field. Are there any glaring mistakes i'm making? any help would be much appreciated!

Thank you.


texts: Updating Craft to 3.3.19 gives 503 error only for logged-out users

texts:
Working on an outdated client project and updated craft on staging from 3.0.30.1 to 3.3.19

I'm getting 503 errors (site temporarily unavailable) when trying to visit any page on the site -- but only for logged out users. Once I log in, everything works normally.

I've checked that the DB connection is working correctly. When I performed the updates, I got a dialog from Craft to update my database and performed it so the schemas should be up to date.

The stack trace shows where the error occurred but I'm stumped as to why it's happening or how to fix it:

From vendor/craftcms/cms/src/web/Controller.php (starts line 157):

        if (!($test & $allowAnonymous)) {
            // If this is a CP request, make sure they have access to the CP
            if ($request->getIsCpRequest()) {
                $this->requireLogin();
                $this->requirePermission('accessCp');
            } else if (Craft::$app->getUser()->getIsGuest()) {
                throw new ServiceUnavailableHttpException();
            }

The exception at the bottom of this check is what is thrown and causing the error, but why would a visit to the homepage be detected as a CP request? I'm assuming CP means control panel.

Any ideas?


texts: Translate field name displayed within validation error messages?

texts:
I'm adding validation errors to fields using addErrors($record->getErrors()) which then read like e.g. "My Field cannot be blank."

But I'm wondering where I can translate the field name, which I think is generated from the ID attribute myField?

Update:

Template:

<input type="hidden" name="action" value="example/saveExample">

{{ forms.textField({
    label: 'My Field'|t,
    id: 'myField',
    name: 'myField',
    value: null,
    errors: example is defined ? example.errors('myField'),
}) }}

Service function called from actionSaveExample:

public function saveExample(ExampleModel $example)
{
    $exampleRecord = ExampleRecord::model()->findById($example->id);
    $exampleRecord->myField = $example->myField;

    if ($exampleRecord->validate())
    {
        // save
    }
    else
    {
        $rule->addErrors($ruleRecord->getErrors());

        return false;
    }
}


texts:
Was wondering if anyone had looked a a way of saving RSS feed items as an entry into craft.
I imagine this would have to be done through a plugin and a custom field type? Or is there a better way to do this.


texts: How to merge/combine/transfer-entries-between two categories in the CP?

texts:
I’ve got 2 categories each with lots of entries. The client wants to delete one category, and transfer it’s entries into the other one.

If I delete the category, it just disappears, but I somehow need to mass assign all those entires into another category without going through each entry manually.

Any ideas welcome.


texts: Add items to user's cart in Craft Commerce 2

texts:
I'm trying to add items to user's cart from a plugin but I'm stuck on getting cart of a user other then current user.
I have the code for adding items to cart, it's something I used on current user. But I don't know how to get the cart for any user.
<?php
$cart = iHaveNoIdeaHowToGetUsersCart($user->id); // <---
// I used this for current user:
// $cart = craft\commerce\Plugin::getInstance()->getCarts()->getCart();
if ($cart->id == null) {
    // Create cart if it does not exist
    Craft::$app->getElements()->saveElement($cart);
}

$purchasableId = Craft::$app->getGlobals()->getSetByHandle('booking')->breakProduct->one()->id;
$options = [
    'amount' => (float)$something,
    'description' => 'Something'
];
$newLineItem = Plugin::getInstance()->getLineItems()->createLineItem($cart->id, $purchasableId, $options, 1);
$cart->setLineItems([$newLineItem]);
Craft::$app->getElements()->saveElement($cart);
?>


texts: I have one site on my server that's currently using Craft, and I'd like to setup a second one to use Craft as well. Can I rename the craft folder, and then set the $craftPath variable to point to it?


texts: Uncheck "Use this field’s values as search keywords?" by default?

texts:
Is there a way to have the "Use this field’s values as search keywords?" option unchecked by default when creating a new field? Our searchindex table is getting bloated by data that doesn't need to be in there. I'm clearing it out now, but it would be really cool to have that checkbox be unchecked unless someone specifically wants it to be a keyword for search.

Thanks.


texts: How do I add an HTML tag to the formatting drop-down in the rich text editor?

texts:
I would like to add the 'code' tag to the formatting drop-down. My rich text field is using Standard.json and I am able to remove the current tags, but it's not letting me add additional tags. I have tried adding 'code' like this in my Standard.json file:

formattingTags: ['p', 'blockquote', 'pre', 'code', 'h1', 'h2' 'h3', 'h4', 'h5']

Any thoughts?

(I realize 'pre' and 'code' are similar but if possible I would like to use code to be semantic.)


texts: How can I output a list of categories that are not empty?

texts: In other words, categories must have at least one enabled entry assigned to them.


texts: Getting a 503 Error before Craft installs - [error] [exception.Craft\HttpException.503] Craft\HttpException

texts:
In the browser, I'm getting a page that says:

Service Unavailable
Our site is temporarily unavailable. Please try again later.

In my craft.log, I'm getting a 503 error that says:

******************************************************************************************************
2017/03/14 21:31:04 [error] [exception.Craft\HttpException.503] Craft\HttpException in /var/www/site/craft/app/etc/web/WebApp.php:800
Stack trace:
#0 /var/www/site/craft/app/etc/web/WebApp.php(203): Craft\WebApp->_processInstallRequest()
#1 /var/www/site/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#2 /var/www/site/craft/app/index.php(62): CApplication->run()
#3 /var/www/site/public/index.php(22): require_once('/var/www/site...')
#4 {main}
REQUEST_URI=/
---

******************************************************************************************************

It looks like it's an error when trying to run the installation for Craft. When I visit the server's /admin, I get a 404 page from nginx.

Any and all help is greatly appreciated. Thanks!


texts: Get all URLs from a multisite installation

texts:
I have an multisite installation like this:

www.example.com/animal
www.example.uk/animal

Each site has a configuration like so:

'example.com' => array(
        'siteUrl' => array(
            'us_en' => 'https://www.example.com/'
        )
'example.uk' => array(
        'siteUrl' => array(
            'uk_en' => 'https://www.example.uk/'
        ).

I want to print a collection of URLs from all of the locales. For example:

www.example.com/animal
www.example.uk/animal

And check their status as well.


texts: Why are variables persisting inside of my for loop?

texts:
Is anyone able to tell me why variables which I've defined inside of a for loop are persisting and retaining their values on into consecutive iterations? In order to overcome this, I've had to set them back to null each time. I'm relatively new to Craft and Twig but this seems like a bug. Has anyone else experienced this?

    {% for entry in entries %}

      {# I shouldn't have to set these to null for each loop iteration, #}
      {# but they seem to be retaining their values #}

      {% set photo = null %}
      {% set width = null %}
      {% set height = null %}
      {% set orientation = null %}

      {% if entry.photo | length %}
        {% set photo = entry.photo.first() %}
        {% set width = photo.width %}
        {% set height = photo.height %}
        {% set orientation = '' %}

        {% if width > height %}
          {% set orientation = 'landscape' %}
        {% elseif height > width %}
          {% set orientation = 'portrait' %}
        {% elseif width == height %}
          {% set orientation = 'square' %}
        {% endif %}
      {% endif %}

        {% if entry.photo | length %}

        {% endif %}

    {% endfor %}


texts: How can I output a timeframe in fully written notation nicely?

texts:
Let's say you have two dates and want to output the timeframe in fully written "day month year - day month year" notation, but want to leave out the month and year parts of the start date if unnecessary.

Examples:

2014-06-13 to 2014-06-20 yields 13 – 20 June 2014
2014-06-13 to 2014-07-13 yields 13 June – 13 July 2014
2014-06-13 to 2015-06-13 yields 13 June 2014 – 13 June 2015

How can I get the desired notation of the timeframe?


texts: How to implement mailchimp plugin to target different mailists?

texts: I'd like to be able to have multiple (2) Mailchimp subscribe forms on the same web site. Each would target different mail lists so I can use one on a landing page for example. I've noticed that the target mail list is set in the List ID field in the plugin settings. Can I simply add another installation of the plugin at this level to accomplish my goal?


texts: Adding a specific field to search() parameter that contains an object

texts:
I'm currently running a search which contains an object {query:query, subLeft: true, subRight: true}
{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.section('example').search({query:query, subLeft: true, subRight: true}).order('score') %}

But I want to search for a specific field. It seems to yield results when I do something like this
craft.entries.section('example').search('title:*search term*').orderBy('score')

but I want to use the query, subLeft and subRight. So a working version of like the below:
{% set entries = craft.entries.section('example').search({'title:*query*', subLeft: true, subRight: true}).order('score') %}


texts: Merge list of categories related to 'project' entries - not working, a solution

texts:
good to be back)
Helping a friend out with a website for his tiling business. The site contains a 'projects' section which displays category-filter buttons allowing the user to toggle relevant projects.
The CMS also contains a custom field to allow my friend to make a project entry 'sticky'.
I had been struggling to make this work:
{# get all sticky Project entries #}
{% set stickyProjects = craft.entries().section('project').limit(30).sticky('1') %}
{% set stickyProjectEntries = stickyProjects.all() %}

{# get all non sticky Project entries #}
{% set projects = craft.entries().section('project').limit(30).sticky('0') %}
{% set projectEntries = projects.all() %}

{# Fetch, then merge, categories related to both sticky and non-sticky Projects #}
{% set stickyCategories = craft.categories.relatedTo({ sourceElement: stickyProjectEntries }).all() %}
{% set nonStickyCategories = craft.categories.relatedTo({ sourceElement: projectEntries }).all() %}

{% set usedCategories = stickyCategories|merge(nonStickyCategories) %}

Even after using the Merge filter, "usedCategories" was outputting a duplicate category "External" (see image)


texts: Invalid plugin: No plugin exists with the handle - Craft 3

texts:
I had an issue with my site running Craft 3.1.15 where I wasn't able to update the site to the most recent 3.1.16, and also wasn't able to install any plugins. Every plugin I tried would throw this error:

  Blockquote Invalid plugin: No plugin exists with the handle "plugin-slug"

I tried creating a fresh install of craft through composer, this time running 3.1.16, and I'm faced with the same error. All my other craft sites run locally seem to update fine and have no issues installing new plugins. Is there an issue with the latest craft updates? Or is there something I need to do to resolve this?


texts: Advanced search entries relatedTo category and unrelated to any category

texts:
I know the long-form method for achieving my goal, but I'm hitting a wall in trying to keep the conditionals down.

Is it possible to search for entries related to a specific category field AND search for entries with no category selection for that same field?

Right now, I can only do the first part. Here's a snippet of a much larger query.

{# get all categories within specific category groups #}
{% set skillsOptions = craft.categories.group('skillsCategories') %}
{% set durationOptions = craft.categories.group('durationCategories') %}

{# working: find all entries with any category selected #}
{# not working: also find all entries with no category selected #}
{% set opportunities = craft.entries.section('opportunities').relatedTo('and',
    {
        targetElement: ['or', skillsOptions],
        field: 'skills'
    },
    {
        targetElement: ['or', durationOptions],
        field: 'duration'
    }
%}


texts: Moved from local to remote "Service Unavailable Our site is temporarily unavailable. Please try again later."

texts:
I built a site locally and moved it up to a remote host. I am getting a page that says

  “Service Unavailable Our site is temporarily unavailable. Please try
  again later.”

It’s clearly a page coming from Craft so i know the CraftPath is set up right. I have multi-environment variables set up in config/general.php that seem to be working, i.e. it still works locally and there is a stylesheet being called properly in the error page so i think my {baseUrl} is working. I also have them in config/db.php and at least, the local connection is being made. I have devMode => true and it's not giving any hints...

So i uploaded /craft and /public and imported the database. I’m currently using an IP address because the Url is in use and will be moved later on. I had the IP set up so i get to my /index.php and it seems to go out and find /craft OK.

I don’t have to reinstall craft or anything do i?

The /craft, /public, database, and multi environment variables should do it? Is there some other thing i need to do?

Would a DB connection error be clear?


texts: Any problems installing Craft on CentOS with SELinux enabled?

texts:
Seriously considering installing Craft on CentOS w/SELinux.  I currently have it running on Ubuntu.  Anyone have any problems with that type of install?

thanks,

Chip


texts:
Craft 2.x using latest Charge plugin...

When ending a subscription using the Charge area of the control panel I'm unable to  end the subscription because I get the error:

Page Not Found
Unable to resolve the request "site".

I can't figure out where the route "site" is coming from. Does anyone know?


texts: Using the Redactor rich text field, how can I dynamically wrap my images with a fancyBox link (with attributes as parameters)?

texts:
I'm using fancyBox (from fancyApps, http://fancyapps.com/fancybox/), and I need to wrap my images added within the Redactor rich text field with a link that had an href to the image source + some attributes as parameters :

an href attribute to specify the image source to open
a data-fancybox-group attribute to specify in which gallery the image
should open
a title attribute to specify the image title in the fancyBox)

I tried to add formatting tags to Redactor (cf. https://imperavi.com/redactor/examples/formatting-add/) which let me add links with .fancybox class, but there's still missing parameters that are required to open the fancyBox that I'm not sure that can be retrieved.

"fancybox": {
    "title": "Add fancyBox link",
    "args": ["a", { "data-fancybox-group": "images-gallery", "class": "fancybox" }]
}

I also tried the Retcon plugin (https://github.com/mmikkel/RetconHTML-Craft) which is very cool and lets me automatically wrap each image with a link with data-fancybox-group but I still can't retrieve and apply the img src + title to the link.

{{ entry.body | retconWrap( 'img', 'a.fancybox') | retconAttr('.fancybox', { 'href':'', 'data-fancybox-group':'images-gallery' }) }}

is there a way to achieve this with one of this two methods ? Or to do this in another way ? This should be very easy for the end user which is a non-programmer.


texts: How can I set an entry title automatically, based on a related entry?

texts:
If a booking channel contains two Entries fields (one related to a single User, one related to a single 'Event'), how can I get the booking entry title to be set automatically to the following syntax:

"Event Date - Username"

I've set up the entry to not show the title field, but my syntax is wrong. I'm using:

{{eventBooking.title}} - {{userBooking.username}}

but all I'm getting is "-", so it's obviously not recognising the fields. Is this possible?


texts: Disable "dynamic links" in rich text fields

texts:
When we're adding a "link > link to an entry" to a rich text field, this will result in a link to https://www.site.com/page#entry:3962:url and we understand what the purpose is of this additional #entry:3962:url, but is there a way to disable this?

The multi-domain setup we created is not compatible with this feature, so it will create links that are broken. The easiest fix for our customer is to disable this feature all together. Is that possible and how?


texts: Creating / manage content - how is everybody doing it?

texts:
I need some ideas for creating content.
It's a bit of a pain the way i have it now.

I tested this: https://nystudio107.com/blog/creating-a-content-builder-in-craft-cms
But i don't really like it because text and images are all over the place in the backend.
If i could combine certain stuff in blocks that i could move around it would be better.
But it seems like this (like in my example image) is not possible (images is a Super Table):

For example here: https://skulltronics.net/phantasialand-hoerspiel-und-videokassetten

I have the audio tape and video tape.
If i want to add the next tape and want it on top or between then i have to move every text and image block if i can't group them.

Then i have the links to the single view of the images. This are not the same images that you see on the pages. They are hi res and a mix of png and jpg.
At the moment a put them in by hand like:

FHD Ansicht

At the moment I'm using %%image1%% in my content and they are replaced by the code in the template.

Problem is if i want to add more i always need to count the rows.

row 1 = %%image1%%, row 2 = %%image2%%...

For example this: https://skulltronics.net/phantasialand-autoaufkleber-und-sticker
Looks like this when creating the entry:

Phantasialand Aufkleber 1978

%%image1%%

Original Größe: 11.8 cm &Oslash;

%%share1%%

Phantasialand Aufkleber 198?

%%image2%%

Original Größe: 20.3 cm Lang

%%share2%%

Phantasialand Aufkleber 198?

%%image3%%

Original Größe: 20.7 cm Lang

%%share3%%

If i now need another sticker in between i can use %%image15%% because that attachment is row 15 after adding it or i need to change them all when editing if i want it in right order.

Also with the nystudio107 way: If you create a image link then you make a text block with

Then comes the attachment and then another text block with just
 ?

So how do others handle/create/manage there content/entries?


texts:
I'm trying an update on the CLI and get the following error.

If I do it again afterwards I get told that everything is up to date.
If I want to install a plugin then I still get the message that I should update to the current version.

Who can tell me what I am doing wrong or where the mistake lies?

$ php-7.2-cli -d allow_url_fopen=1 craft update all
Fetching available updates ... done
Performing one update:

    - craft 3.1.25 => 3.1.28

Backup the database? (yes|no) [yes]:yes
Backing up the database ... done
Performing update with Composer ... done
Applying new migrations ... error: The command "'/home/lichtebs/CraftCMS-ALL/craft' 'migrate/all' '--no-content'" failed.

Exit Code: 255(Unknown error)

Working directory: /home/lichtebs/CraftCMS-ALL

Output:
================
Content-type: text/html

Warning:  Unexpected character in input:  '' (ASCII=92) state=1 in /home/lichtebs/CraftCMS-ALL/craft on line 16

Parse error:  syntax error, unexpected T_STRING in /home/lichtebs/CraftCMS-ALL/craft on line 16

Restore the database backup? (yes|no) [yes]:yes
Restoring the database backup ... done
Revert the Composer changes? (yes|no) [yes]:yes
Reverting Composer changes ... error: The command "'/home/lichtebs/CraftCMS-ALL/craft' 'update/composer-install'" failed.

Exit Code: 255(Unknown error)

Working directory: /home/lichtebs/CraftCMS-ALL

Output:
================
Content-type: text/html

Warning:  Unexpected character in input:  '\' (ASCII=92) state=1 in /home/lichtebs/CraftCMS-ALL/craft on line 16

Parse error:  syntax error, unexpected T_STRING in /home/lichtebs/CraftCMS-ALL/craft on line 16


texts: Images not saving to images folder in web directory

texts:
I have been following along the Up and Running with Craft 3 tutorial on craftquest.io

I created the assets volume as directed with the absolute file path

/c/xampp/htdocs/craftCMS/craftetest/web/images/drinks

I created the drinkImage field as directed. Put it in the entry type.
Created some entries and uploaded images in the drinks image fields no problems.

The problem is they don't show up in the /web/images/drinks folder at all.
Is there something I am missing?


texts:
I have a site where users move through different groups based on their progress through an eLearning course. On the CP Users page the groups are listed alphabetically down the left. To get them in a meaningful order I have prefixed their names with 1, 2 etc however it would be nice not to have to do this as I re-use these names and in some places the prefix is meaningless.

Is it possible to do something like asset sources where they are 'orderable'?


texts: How can I display a message after login?

texts:
When a user logs in, I want to display the message "Login Success" or an error message "Username or Password is incorrect" if a user enters the wrong details.

What is the best method for displaying these messages when a user logs in and logs out? I am not sure how to write the correct way using getFlash?


texts:
Basically, I have an asset volume called Images, with

base URL: /photos/
file system path: ~media/images

Then I go to upload the asset and I try to view it, it gives me a 404 "Template not Found"

mydomain.com/photos/image.jpg


texts: if entry has specific category, show specific html block

texts:
I have entries, which can have several categories.
These categories are in different categorie groups.
Now if i show an entry page, i want to display i certain html block
based on a specific category, the entry has or not.
i tried this, but its not working, i think i get the relatedTo thing wrong:
//i loop through all the categories in my group

{% for category in craft.categories.group('catGroup1') %}

//the i go to the section my entries are in and relate that to the categories i want to filter

{% set categoryListings = craft.entries({
  section: 'kelims',
  relatedTo: [
    { targetElement: category, field: 'filterThisCategory' }
  ]
}) %}

//if the entry has this category

{% if categoryListings|length %}

  display some html block

{% endif %}
{% endfor %}


texts:
I am able to add/delete matrix blocks from within my plugin without any problems. I would like to give the user the ability to drag & drop any field just as you can within the CP.

I can use jQuery UI Sortable to create the functionality no problem. I am curious what/how to call within Craft that manages order so that it is saved.

Thank you for any suggestions!


texts: Adding new locale - hangs at Step 3 'ResaveAllElements'

texts:
I've looked at every option I can think of so hoping that someone can assist. We're on a dedicated server with full root access.

We've got a relatively small site that now needs a Spanish locale adding. When I go to add it, everything seems to be smooth running until 'ResaveAllElements - step 3' and 'ResaveElements - step 99 (sometimes around 94 ish too).

First thing I checked was the error log and found:

Allowed memory size of 268435456 bytes exhausted (tried to allocate 79 bytes)

So, I then changed this to 1024M - no joy. Changed it to -1 and still get exactly the same issue. These settings are reflected in the phpinfo too so they seem to be in place.

I then phoned our server company and ran it by them who suggested placing .user.ini files in there to be sure and so we've done that and now we're at a loss.

I found another post on here with a similar issue where the suggestion was to examine the craft.log - did that and found:

WHERE (lft = 1) AND (status = :status). Bound with :status='running') 2016/08/12 09:36:53 [trace] [system.CModule] Loading "components" application component in /*/craft/app/etc/web/WebApp.php (593) in /*/craft/app/models/TaskModel.php (81) in /*/craft/app/models/TaskModel.php (39)

Is there anything else we can try to get the locale that we've missed?

Any help would much appreciated.

Thanks!


texts: Saving Form Data to Plugin Record via Javascript

texts:
I am new to Craft plugin development, so I apologize ahead of time for my lack of understanding.

I'm working on a plugin that allows the user to "upload" Excel/csv files via the control panel that then get sent to an API via Javascript. I then want to save the returned data to my plugin's record.

At the moment, I have a JSON object with all the necessary data and a record set up as such:

class GeocodeFile_LocationsRecord extends BaseRecord
{
    public function getTableName()
    {
        return 'geocodefile_locations';
    }

    protected function defineAttributes()
    {
        return array(
            'id'       => array(AttributeType::Number, 'required' => true),
            'type'    => array(AttributeType::Bool, 'default' => false),
            'name'       => array(AttributeType::Name, 'default' => null),
            'address'        => array(AttributeType::Name, 'default' => null),
            'city'         => array(AttributeType::Name, 'default' => null),
            'state'   => array(AttributeType::String, 'default' => null),
            'zip'       => array(AttributeType::Number, 'default' => false),
            'url'     => array(AttributeType::Name, 'default' => true),
            'lat'   => array(AttributeType::String, 'default' => null),
            'lng' => array(AttributeType::String, 'default' => null)
        );
    }
}

Is it possible to save this JSON data to the record directly, or is there a way to create a model in Javascript that could then be saved to the table? Perhaps I can send the data to a service that would handle it instead?

Clearly, I don't know how this is supposed to be handled. Any help with the matter would be greatly appreciated.

Sorry again for my naiveté on this subject!


texts: Get the related entry from an Entries field in a Matrix block within a plugin craft 3

texts:
So I've got this which accurately gives me the desired relation block within my matrix, but how do I actually get the Entry object from a relation field?

$project = Entry::find()->id($projectId)->one();

foreach ($project->location as $locations) {
        if ($locations->getType()->name === 'Locations') {
            // Grab a building from the block.
            // Right now this just returns the relation table ID, I'd like the actual Entry object with it's attributes.
            $buildings = $locations->buildings;
        }

    }


texts:
Total noob here.  Have managed to output entries and paginate them with this:

{% paginate craft.entries.section('woods').limit(5) as entries %}
    {% for entry in entries %}
        ....
    {% endfor %}
{% endpaginate %}

But I cannot figure out how to output just entries of a certain type or entries from a certain category within a category group.

{% paginate craft.entries.section('woods').type('mahogony').limit(5) %}
    {% for entry in entries %}
        ...
    {% endfor %}
{% endpaginate %}

ain't flying me anywhere but into a tree.

I'm sure it is something basic.


texts: Display old entry version content through twig?

texts:
Is it possible to output content from previous revisions of entries in the twig templates?

I need to do a score comparison between say entry 1 and entry 1.1 to see if the value has increased then output an indicator on the front end to indicate the outcome (Up arrow or down arrow most likely) kind of like a music chart style.


texts:
We've got all the max settings set up OK as per https://craftcms.com/support/upload-troubleshooting, but we are still getting errors. The log file just shows this, nothing more:

  2014/10/24 11:26:35 [error] [application] Uploaded file was empty

What else should we be looking for?


texts: Save and log in a user from event callback

texts:
I'm trying to build a plugin wherein after a user is created via the normal means via a front end template, the user is immediately logged in.

My module is watching for the after save event on Elements for a User:

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $event) {
    if ($event->element instanceof \craft\elements\User && !ElementHelper::isDraftOrRevision($event->element)) {
        return Craft::$app->getModule('my-module')->users->handleCreateLogin($event);
    }
});

Then, handleCreateLogin looks like this:

public function handleCreateLogin(ElementEvent $event)
{
    $user = $event->element;
    $isNewUser = $event->isNew;

    if ($user->can('Admin')) {
        // leave admins alone
        return;
    }

    if ($isNewUser && Craft::$app->user->isGuest) {
        // This is a new user, so log in
        Craft::$app->user->loginByUserId($user->id);
    }
    return;
}

The event triggers fine, but after the user is created I'm greeted by this message:

Call to a member function mergePreferences() on null
vendor/craftcms/cms/src/controllers/UsersController.php at line 1139

which is an error from the UserController's sanity check to see if the user is currently logged in.

According to the docs this is the accepted method, and it worked in a similar fashion in Craft 2. I'm guessing the save isn't complete when trying to redirect after logging in? Or some other bit of unfinished business.

Anyone have any tips or suggestions?


texts: Commerce product slug creates duplicates - can they also be autogenerated?

texts:
The slug for products is generated from the Title, for example in my case "Green Shirt". Seems like these are not unique, and if I create a product later on, also called "Green Shirt", they both get "green-shirt" as slug, and causing problem when viewing the products in a template.

Why isn't this creating unique slugs like for Entries?

And I would rather have the slug autogenerated, like the option for SKU. Is this possible?
Have seen threads about this, but has anyone made a solution yet?

Thanks!


texts: Element API -- getting table data from a matrix

texts:
I'm using element API to pull JSON, and I have it working pretty well with a matrix field, but I need to pull a single column out of a table field inside of the matrix, and I don't even know where to start.

We're using this as a headless way to pull data into a game, and I need to pull the flavor text, and just have it output one field in the table, not everything.

'api/locations/<slug:{slug}>.json' => function($slug) {
        return [
            'elementType' => Entry::class,
            'criteria' => ['section' => 'locations', 'slug' => $slug],
            'pretty' => true,
            'one' => true,
            'transformer' => function (craft\elements\Entry $entry) {
                $bodyBlocks = [];
                foreach ($entry->dataMatrix as $block) {
                    switch ($block->type->handle) {
                        case 'theData':
                            $bodyBlocks[] = [
                                'zone' => $block->zone,
                                'zoneName' => $block->zoneName,
                                'alternateZone' => $block->alternateZone,
                                'zoneBanner' => $block->zoneBanner,
                                'backgroundAsset' => $block->backgroundAsset,
                                'propAsset' => $block->propAsset,
                                'flavorText' => $block->flavorText,
                            ];
                            break;
                    }
                }
                return [
                    'data' => $bodyBlocks,
                ];
            }
        ];
    },

This is currently giving me this output for the table field:

"flavorText": [
            {
                "col1": "1",
                "col2": "Arbitrary flavor text here",
                "col3": "",
                "title": "1",
                "text": "Arbitrary flavor text here",
                "icon": ""
            }
        ]

All I want is the stuff in the 'text' field, nothing else. There is no documentation anywhere on how to deal with Table Fields in the Element API, much less how to do it within a matrix. I'm also not sure how to loop through fields inside of a matrix that require loops to pull the data normally.

Anyone have any idea how I can get this output?


texts:
I currently am developing a plugin to gather XML restful data.
At one point in the file, I need to reference another PHP file, which will process various data.

As a test, the code in the included file should return output, as well (see code below).

I've tried to utilize the following code, but it doesn't work.  There is no error message, but again there is no data output.

Craft::import('plugins.aifeed.resources.Date_Formatting');

I've been looking here, but it wasn't clear to me how or if the 'included' file could be utilized.
Thanks for any leads.

Here is my code:

in Variables folder:
AiFeedVariable.php

<?php
namespace Craft;

class AiFeedVariable
{
        public function XmlVariable($optional = null)
    {
....
$strSampleDate = '2015-12-23';

Craft::import('plugins.aifeed.resources.Date_Formatting');

}
}

in Resources folder:
DateFormatting.php

<?php
namespace Craft;

class DateFormatting
{
$strDate_A=$strSampleDate;
echo '$strDate_A test...'.$strDate_A.'<br>';
}


texts: .htaccess as a Craft template for 301 redirects?

texts:
The Reroute plugin is great for a handful of 301 redirects, but we have hundreds of entries and each entry has a legacy URL. Dumping this into a template as normal works fine, but thinking about if it could work with the .htaccess file directly. Has anyone tried, or would be a dangerous path?

Thinking along the lines of NSM htaccess for EE.


texts: Config for devMode not showing when true

texts:
I am using .env to set environment to local:

# .ENV The environment Craft is currently running in ('dev', 'staging',
'production', etc.)
 CRAFTENV_CRAFT_ENVIRONMENT="local"

My general config looks like:

 // Dev environment settings
'local' => [
    'devMode' => true,

    // Base site URL
    'siteUrl' => getenv('CRAFTENV_BASE_URL')

],

My staging site is :

 // Staging environment settings
'staging' => [
    // Base site URL
    'siteUrl' => getenv('CRAFTENV_BASE_URL'),

    // Dev Mode (see https://craftcms.com/support/dev-mode)
    'devMode' => true,

    'baseUrl'  => getenv('CRAFTENV_BASE_URL'),
    'basePath' => getenv('CRAFTENV_BASE_PATH'),
    'aliases' => [
        '@assetBaseUrl' => getenv('ASSET_BASE_URL'),
        '@assetBasePath' => getenv('ASSET_BASE_PATH'),
        '@baseUrl' => getenv('CRAFTENV_BASE_URL'),
        '@basePath' => getenv('CRAFTENV_BASE_PATH')
    ],
    // Custom site-specific config settings
    'custom' => [
        'craftEnv' => getenv('CRAFTENV_CRAFT_ENVIRONMENT'),
        'staticAssetsVersion' => 1,
    ]
],

Why wont my local site show the dev mode settings in CP ?


texts:
I have an odd problem.

When I render a simple HTML template without any link to the Control Panel, I get the following message on random pages:

  An error occurred when rendering a template

Whenever I change I can't seem the remove this error or find the problem / solution.

Also I cannot access the Control Panel.

Can you please help me?

Thanks!


texts:
Craft 3.0.16.1

I have a relationship that is outputting entries, but the entries are not in the order as selected.

{# not sorting correctly  - **fieldName** is a variable passed via include #}
{% set relatedEntries = publications.relatedTo(
  {sourceElement: country, field: fieldName}
) %}

I copied this code from the documentation and change field names to work

{# copied from docs but template errors #}
{% set relatedEntries = craft.entries({
    relatedTo: { sourceElement: country, field: fieldName },
    orderBy:     "sortOrder",
    limit:     null
}) %}

but this throws a database exception error

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sortOrder' in
  'order clause'

How do I get related entries to sort on the order as selected in the entries field?

********************UPDATE**********************

HERE IS THE FULL TEMPLATE

      {{ categoryTitle  }}

      {# start tabbed content #}

       {# inside categories list countries #}
      {% for country in countries.all() %}

{{ country.title }}

      {% endfor %} {# end countries loop #}

        {% for country in countries.all() %}

            {# finally output entries that are in the category and country #}

            {# not sorting correctly #}
            {% set relatedEntries = publications.relatedTo(                   {sourceElement: country, field: fieldName}
            ) %}

            {# error about method ('all') on an array #}
            {# {% set relatedEntries = country[fieldName].all() %} #}

            {#
            // copied from docs but template errors
            {% set relatedEntries = craft.entries({
                relatedTo: { sourceElement: country, field: fieldName },
                orderBy:     "sortOrder",
                limit:     null
            }) %} #}

            {% for entry in relatedEntries.all() %}

              {% for block in entry.Documents.all() %}
                {% if block.externalLink|length %}
                  {# use external link field #}
                  {% set link = block.externalLink %}
                {% else %}
                  {# use uploaded file #}
                  {% set link = block.pdfOrFile.one().url ?? null%}
                {% endif %}

{{ entry.title }}

              {% endfor %}{#end link #}

              {% else %}
              {# output nothing for no results #}
            {% endfor %}

        {% endfor %}

      {# end tabbed content #}


texts:
I am not super fluent in Twig and I inherited a website from a company that built the site in Craft v2. The site was upgraded to version 3 of Craft recently and one of the template pages is throwing an error where on version 2 of Craft it was not. Code:
{% set faqs = craft.entries.section('FAQ').search('slug::' ~ entry.slug).first() %}

{% if faqs.questionsanswers|length > 0 %}
  FAQs
{% endif %}

This is throwing an error: Impossible to access an attribute ("questionsanswers") on a null variable.
So since it was returning null I changed the code to this which seems to be working:
{% if faqs is not null and faqs is not empty %}
  FAQs
{% endif %}

My question is why would this code not work for version 3 when it was working correctly for version 2? Why would the length return null instead of 0? I did not do the upgrade but maybe something was missed? (This is a template page and some of the entries do have FAQs and some don't) Or perhaps something with the structure of the version 3 of Craft has changed? Lastly if there is a better way to do/code what is being done I would love to hear it.


texts: Rich Text field is producing weird space character instead of

texts:
Example from the frontend

Example in dev tools

If I "view-source" on the page

Example from Rich Text Field

Example from Rich Text Field HTML

This is a Rich Text field within a matrix, it's output in the template like this: {{ block.text }}

If I pass the "|raw" filter I get the same.

If you notice, the Rich Text Field has a   before the closing </p>, which isn't output in the markup, instead I get this strange character.

I had a similar thing with hacksaw recently bringing up this character here:
https://github.com/ehousestudio/craft_hacksaw/issues/16

Any ideas on how to resolve this?


texts: Adding additional attributes to modifyEntryTableAttributes()

texts:
Using the example code from the docs, I'm attempting to add a value from my custom field to the Entries listing.

public function modifyEntryTableAttributes(&$attributes, $source)
{
    if ($source == 'index')
    {
        unset($attributes['expiryDate']);
        $attributes['id'] = Craft::t('ID');
    }
}

How do I go about accessing additional attributes on the Entries? The custom field data is stored in MyPluginName's table and doesn't appear to be available in the attributes of the EntryElement.

Thanks for any pointers you may have!


texts:
I have a section for holding calendar entries stored by postDate in the CMS.
On the front end I want to basically display these in a calendar.

I have code which displays the calendar looping through each day of the month.
For each day it currently queries if there is any entries for this day.

Is there a better way to do it? - my current method had a query for each day?

Current code is:

      Sun
      Mon
      Tue
      Wed
      Thu
      Fri
      Sat

    {% set time = "now"|date("U") %}
    {% set daysInMonth = time|date('t') %}
    {% set startDow = time|date('F 1\\s\\t Y')|date('w') %}
    {% set dow = startDow %}
    {% for day in range(1,daysInMonth) %}
        {% if loop.first and startDow != 0 %}

        {% endif %}

                {{ day }}
                    {% set today=thisyear ~ "/" ~ thismonth ~ "/" ~ day %}

                    {% if (category is defined) and (category is not empty) %}
                    {% set params = { section: 'calendar', status: null, postDate:today|date('Y-m-d'), relatedTo: category } %}
                    {% else %}
                    {% set params = { section: 'calendar', status: null, postDate:today|date('Y-m-d') } %}
                    {% endif %}
                    {% set entries = craft.entries(params)%}
                    {% if entries|length %}

                    {% for entry in entries %}
                    {{ entry.title }}
                    {% endfor %}

                    {% endif %}

        {% if loop.last and dow != 6 %}
            &nbsp;
        {% endif %}
        {% if dow == 6 %}
            {% set dow = 0 %}

        {% else %}
            {% set dow = dow + 1 %}
        {% endif %}
    {% endfor %}


texts: Problems Securing Database Connection Over SSL

texts:
I used to connect to my database over SSL by directly modifying the createDbConnection method in Craft's AppBehavior.php:

$dbConnection = new DbConnection();

$dbConnection->connectionString = $this->_processConnectionString();
$dbConnection->emulatePrepare   = true;
$dbConnection->username         = craft()->config->get('user', ConfigFile::Db);
$dbConnection->password         = craft()->config->get('password', ConfigFile::Db);
$dbConnection->charset          = craft()->config->get('charset', ConfigFile::Db);
$dbConnection->tablePrefix      = $dbConnection->getNormalizedTablePrefix();
$dbConnection->driverMap        = array('mysql' => 'Craft\MysqlSchema');

// additional attributes to connect over SSL
if (getenv('DB_SSL_ENABLED') == 'true')
{
    $dbConnection->attributes   = array(
        PDO::MYSQL_ATTR_SSL_CIPHER => 'DHE-RSA-AES256-SHA:AES128-SHA',
        PDO::MYSQL_ATTR_SSL_CA     => CRAFT_CONFIG_PATH . 'rds-combined-ca-bundle.pem',
    );
}

$dbConnection->init();

But as of a new Craft release there is a native Craft way to do this by setting a new "attributes" key in the database config file. Unfortunately, Craft won't make a connection when I connect using this new method. I get the dreaded Craft can’t connect to the database with the credentials in craft/config/db.php error. My revised db.php looks like this:

$url = parse_url(getenv("DATABASE_URL"));

define(SERVER, $url["host"]);
define(USER, $url["user"]);
define(PASSWORD, $url["pass"]);
define(DATABASE, substr($url["path"], 1));

return array(
    'server' => SERVER,
    'user' => USER,
    'password' => PASSWORD,
    'database' => DATABASE,
    'tablePrefix' => 'craft',
    'attributes' => array(
        PDO::MYSQL_ATTR_SSL_CIPHER => 'DHE-RSA-AES256-SHA:AES128-SHA',
        PDO::MYSQL_ATTR_SSL_CA     => CRAFT_CONFIG_PATH . 'rds-combined-ca-bundle.pem',
     )
);

Not sure what could be going wrong here. Are there additional attributes that need to be set when doing this the Yii way?


texts:
Internal Server Error
Unexpected token "name" of value "name" ("end of statement block" expected).

Getting this error on my commerce/products template.  What am I missing?

{% extends 'shop/_layouts/main' %}
{% block main %}

{% for product in craft.commerce.products.limit(5).find() %}

          {% include "shop/_images/product" with { class: 'u-max-full-width' } %}

{% if product.url %}{{ product.link }}{% else %}{{ product.title }}{% endif %}

            {% if product.variants|length %}
                <form method="POST">
                    <input type="hidden" name="action" value="commerce/cart/updateCart">
                    <input type="hidden" name="redirect" value="shop/cart">
                    <input type="hidden" name="qty" value="1">
                    {{ getCsrfInput() }}

                    <select name="purchasableId" class="purchasableId">
                        {%- for purchasable in product.variants -%}
                            <option {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %}
                                    data-info="product-{{ product.id }}-purchasable-{{ purchasable.id }}"
                                    value="{{ purchasable.purchasableId }}">
                                    {{ purchasable.description }} {{ purchasable.salePrice|commerceCurrency(cart.currency) }}
                            </option>
                        {%- endfor -%}
                    </select>

                    {% if product.unlimitedStock or (product.unlimitedStock == false and product.totalStock > 0 ) %}
                  <button type="submit">{{ "Add to cart"|t }}</button>
                    {% else %}
                        {{ "Out of Stock"|t }}
                    {% endif %}
                </form>

                {% if currentUser %}
                {% set order = craft.commerce
                <select name="options[giftWrapped]">
                  <option value="no">No gift wrap.</option>
                  <option value="yes">Gift wrapped.</option>
                </select>
          .orders.user(currentUser).hasPurchasables(product.defaultVariant).find() %}
          {% if order|length %} I already own this product:  Order #{{ order[0].shortNumber }}
                {% endif %}
                {% endif %}

                {%- for purchasable in product.variants -%}

                        Regular Price: {{ purchasable.price|commerceCurrency(cart.currency) }}

                        Now: {{ purchasable.salePrice|commerceCurrency(cart.currency) }}

                        {% if purchasable.salesApplied %}Sales Applied:
{% endif %}

                            {% for sale in purchasable.salesApplied  %}

{{ sale.name }} {{ sale.description }}

                            {% endfor %}

                {%- endfor -%}

            {% endif %}

{% endfor %}
{% includejs %}
    $( ".purchasableId" ).change(function(e) {
        $(".purchasableInfo").hide();
        $("#"+($(this).find(":selected").data('info'))).toggle();
    });
{% endincludejs %}
{% endblock %}


texts:
It occurred to me that in every case I was using Element API, I wanted a standardized way of requesting, as the only thing that needed to change was my transformers.

It seemed helpful to standardize the way the input requests were made, and rely solely on transformers for customization.


texts: This is a simple question but I haven't been able to find the answer. Does the Image Transform Quality setting "Auto" mean that no compression will be applied to the transform?


texts: Is it possible to localize Freeform fields and labels?

texts: Is it possible to localize labels and other params of Freeform form fields on the multilingual site? Thanks


texts:
We just have experienced a massive hit (traffic) on our site due to a campaign and have noticed that the craft caching solution is not really working well for the templates/html. We are wondering if there is anything else and how we can set it up to cache to MEMCACHED or any other system instead of the database.

I found some interesting posts on Is there a way to override the template caching system?

Thanks!

PS also the render controller is not performing and is taking over 1s to complete. Any suggestions.


texts: Help with understanding how to structurally build a sermon catalogue

texts:
I'm currently working on a website for a church and I thought that Craft would be perfect for the project and a great way to learn it. However, I'm having a hard time wrapping my head around how to structurally build sermons into a craft cms site.

I want it to look something like this.

Sermons > Series > Series Title, Series Artwork, Series Bio, Message Title, Date, short Bio, artwork, links to watch, links to listen, social links,

Similar to this website. https://newspring.cc/sermons

Could anyone provide any insight into what ways they'd build this? I guess I'm getting hung up on if I have to create 2 channels to make this work? One for Sermons, and one for each series?

Edit: I want to be able to add a sermon series as and entry. And then go in and add each week's message as a separate entry under that particular sermon series. Does that make sense?


texts: Generating pending image transforms stuck

texts:
My image transform task always gets stuck halfway through so that I have to "repair" the task as per this guide. Im trying to convert about 150 images (amounts to ~300 steps). Resetting the task within the database does work but it's not a permanent solution.

I've upped the php memory limit to 1024M, execution time is 0 and Apaches timeout is set to a ridiculously high number. Disk space is available and it's happening with imagemagick as well as gd. It also happens both on my local dev VM running Ubuntu 14.04 as well as on my Debian server. PHP and Apache error logs are empty on both machines. I'm running the Personal edition and the latest version of Craft.

I also tried to set ini_set('max_execution_time', 0); in craft/app/services/AssetTransformsService.php but it didn't change anything.

Some more info:

Some image transforms are missing after restarting the task until it's complete. That renders the workaround by resetting the task in the db basically useless because not all images are transformed by the time it's complete.
It's not a specific image that is preventing the task from completing, as it's always a different image that it's stuck on.
There are usually 75-85 images converted until it's stuck.
Update Asset Indexes doesn't help.
Clearing all caches makes Craft convert all images again. It doesn't delete the old files, it just overwrites them (and gets stuck, as usual).


texts: What is the best way to include an Element's content?

texts:
I'm creating a HTTP RESTful API plugin for Craft. In this case, I'm trying to return Elements (based on criteria), and include their content (via $element->getContent()).

By default, if I return just the Elements collection returned by craft()->elements->getCriteria($type)->find(), the content is not included.

I'm also running each Element through a Transformer which uses ModelHelper::packageAttributeValue($value), and converts attributes to their proper PHP type using attribute configs.

I'm not sure the best way to go about including content in my responses dynamically. Suggestions?

Edit:

I've just found out that $element->getContent() returns fields that aren't even associated with that particular element. Weird. Anybody know anything about this? I've instead resorted to using:

$fields = array_map(function (FieldLayoutFieldModel $model) {
    return $model->getField();
}, $element->getFieldLayout()->getFields());

Not sure what's best here.


texts: Is there a way to see the total number of entries in a channel in the CP?

texts: Is there a plugin or something I'm missing in the CP to just see how many entries are under any given channel or structure?


texts: Can no longer get the ElementType a field is attached to

texts:
I wrote a simple fieldtype that checks that the field value is unique for a specific entry type: https://github.com/fuel-digital/Craft-Unique-Text-FieldType

This worked fine initially but after the recent core updates, $this->element in the valueExists() method is null on new entries, where previously it was an instance of ElementType::Entry or whatever else the field was attached to.

While I could instantiate a new ElementType::Entry object if one doesn't exist, this limits the field's use to Entries, and not Assets, Users etc.

Is there some other way of getting the element's value now? I can't see anything when inspecting the field class.


texts:
If I have three environments; local, dev, and live, and want assets to be setup like this:

local: stored in a local directory (/public/uploads)
dev: stored on S3 dev bucket
live: stored on S3 live bucket

What's the best way to set this in a multi-environment config?


texts: Set default order of Custom Fields inside Layout Tab

texts:
I'm writing a custom plugin, and I want to specify a custom order of the Fields in a tab. My plugin installs several fields, and I want the user to be able to simply add the tab that contains my fields, and not worry about shuffling the fields into their proper order.

Right now it's ordering my fields alphabetically. Is there a way to specify this?

Any help is greatly appreciated! I think it might have something to do with creating a Field Layout Model for my plugin, but I'm not sure.

For reference, I'm talking about specifying a custom order this area:


texts: Edit/overwrite entries content dynamically using module

texts:
Is it possible to edit the content of entries from a specific section "on the fly" using module or plugin? I don't mean to edit database content, I mean to overwrite specific fields/properties during program execution.

For example - I have a website that has a catalogue of products (section "products") and reviews of these products (section "reviews". Reviews have their products attached using entry field. And I want to make reviews disappear (as if they were disabled) if their products disappear.

I am imagining something like that - when reviews are requested from database, module checks each returned review and modifies its status "on the fly". Maybe there is some kind of event for that?

I know I could probably attach an event to deletion/disabling of products (cascade delete), to disable their reviews in database  along with them, but I also wanted to know if another approach is possible.


texts: Output all translation strings to javascript object

texts:
How can I output all translation strings to a javascript object?

Of course I could do it one by one like this:

<script>
translations.string = {{ "string" | t }};

...
</script>

But I want to just loop through all translation strings. Is there some kind of twig object containing all these strings?


texts:
I have a contact form that works using Postmark and Contact Form plugin.

I'm trying to find a way to edit the format of the email that I'm getting when someone sends a message via the website contact form.
E.g.

Subject:
Message from: {{ name.field }}

Full name:
{{ name.field }}

Email:
{{ email.field }}

Department:
{{ department.field }}

Message:
{{ message.field }}

I can see that there's a "HTML Email Template" option in Settings > Email. But I couldn't find any documentation.


texts: Only execute twig block if a Matrix radio has a certain value

texts:
I have a scenario where I'm using a Matrix to store and output 'sponsored links' for a page. Each link also has a radio button to select whether to display in a left hand column or a right hand column group.

Filtering like this is simple enough:

LEFT COLUMN TITLE

{% for sponsor in sponsors.sponsors %}
    {% if sponsor.grouping == "Left column" %}

    {% endif %}
{% endfor %}

...

RIGHT COLUMN TITLE

{% for sponsor in sponsors.sponsors %}
    {% if sponsor.grouping == "Right column" %}

    {% endif %}
{% endfor %}

This works, but it will always spit out a wrapping div and section heading, even if there is no content. How do I test to see if there's anything to spit out first?


texts: Sprout Forms - Can't save front end entry edits

texts:
This this might be a bug but want to ask here first in case I'm missing something minor.

Description

Trying to front edit a Sprout Form entry that was created in the front end. I'm using the same form code with additional <input type="hidden" name="entryId" value="###"> field. But it doesn't save the entry, it creates a new entry.

I compared my form fields with plugin backend and think I have everything I need:

<input type="hidden" name="action" value="sprout-forms/entries/save-entry">
<input type="hidden" name="handle" value="handle_name">
<input type="hidden" name="entryId" value="275">

Steps to reproduce

Create form entry
Edit in front end
Submit form
Original entry is unchanged and there's a new entry

Additional info

Craft version: Craft CMS 3.0.18
PHP version: 7.2.1
Database driver & version: MySQL 5.6.34
Plugins & versions: Sprout Forms 3.0.0-beta.20


texts:
Had a quick search online and I can't find a way to disable entry versioning.

Is this possible? There's some plugins that do this but I'm hoping there's some config I can set somewhere?


texts:
I am having a difficult time understanding how to output even a simple variable using a module. Ultimately I have PHP code that I need to execute to generate a PDF. I managed to do this in V2.5. I'm following all the tutorials that I can find, bu none I feel aren't clear. Any recommendations on the simplest of examples, even if it's just outputting a variable.

Thanks


texts: Why are my template filenames showing up in Google Analytics

texts:
This is very odd to me. I am using this in my templates.

{% extends "_layoutGist.html" %}

My layout is showing up in my Google Analytics. GA is showing showing traffic to

/craft/templates/_layoutGist.html

This seams very peculiar as I would think the file would be fully rendered before Google got ahold of it. Is my tracking code in the wrong place?


texts:
I have a navi on which one entry consists of a random channel entry from one section among standard singles:

Single 1
Single 2
Random Channel entry
Single 3

I thought about something like this:

{% set randEntry = craft.entries.section('channelX').order('RAND()').first() %}
{% for navi in craft.entries.section(['single1', 'single2', randPortrait]) %}

{{ navi.title }}

{% endfor %}

This does not work. (no error, but the variable is simply ignored).

I found a solution to pass in the variable when looping trough the array

{% set randEntry = craft.entries.section('channelX').order('RAND()').first() %}
{% for navi in craft.entries.section(['single1', 'single2', randPortrait]) %}

{{ navi.title }}

  {% if loop.index == '2' %}

{{ randEntry.title }}

  {% endif %}
{% endfor %}

But that's ugly. Is it possible to pass the whole thing into one array without conditional trickery?


texts:
I am using a RichText field type of my site content and I am inserting blocks of code within some <pre> tags which I add in the HTML view of the editor, however when I leave the HTML view, all of the empty lines within the <pre> block are stripped out.

I've tried turning off the clean up HTML option etc with no luck. Is there a way to keep the empty lines (multiple consecutive newlines).


texts: Optimize queries with list of image thumbnails

texts:
I have a list of entries with a thumbnail (Image Asset) added to the entry. Within my entries loop I check if there's any image (thumbnail) added for the entry.

{% set thumbnail = entry.thumbnail.first() %}

Since each check requires one new query the queries keep adding up if the list has for example 100 entries. That's 100 queries just for displaying one thumbnail next to my entry.

Is there a better way of doing this? Could I for example get the URL to the image asset some other way then running a query on the AssetModel?


texts: How to include asset fields in query in php?

texts:
I am trying to figure out how to return asset field(s) in a PHP entry query. Also if I could learn how to return "custom fields" when returning an Object that would be great too! Right now I am having to specify asArray() to even get access to most of my "custom fields"

As as example: I have a Vehicle Entry which has a custom field with the handle of price (number field) and another custom field (asset field) with the handle of images. When I execute the query without specifying the asArray() param I cannot find the custom fields included in the results. But if I specify asArray() then they are all there with the exception of my images field which I think is because it is an asset field or possible because it can be a collection of images? How can I make sure all the fields tied to an entry are returned in my query?

Here are some examples of queries and the corresponding results:

PHP Query without asArray():

$entry_query = Entry::find()
->section('inventory')
->all();

Returns:

PHP Query results with asArray():

$entry_query = Entry::find()
->section('inventory')
->asArray();

However even when specifing to make the result set an array I still cannot figure out how to include the 'images' field.

The images is a field added to the section (see below)

I am having a difficult time finding an answer via the documentation or an example of someone doing the same. All the examples i find are for the template side in twig.

Thanks!


texts: sendEmail messages not being received by Exchange server

texts:
I've been able to get this to work with my gmail address but not my work's Exchange email account. How can I make this receivable by exchange mail servers?

    $email = new EmailModel();
    $email->toEmail = 'EMAILADDRESS';
    $email->subject = 'test';
    $email->body    = 'test';

    $sent = craft()->email->sendEmail($email);


texts: Cloudinary thumbnail creation for assets

texts:
I realized Craft 3 generates its own thumbnails and does not use Cloudinary to do this on the CP. My question is, how and where should I modify the JavaScript code, or what is the best practice to use external generator.

What I would like to do is really just utilize the query string of Cloudinary instead of doing this on Craft side...?

So somehow I would like to overwrite this call, and change it:

SITE/cpresources/4c875891/thumb-30x30.jpg?v=1522966431

And I also would like to avoid the generate thumbnail:

http://tr3nds.test/index.php?p=admin/actions/assets/generate-thumb&uid=7b78d4ed-9c3d-4193-89c0-f20e0d3c35be&width=30&height=30&v=1523244927


texts: How to set CRAFT_PLUGINS_PATH when invoking a console plugin action

texts:
I have an install where I've moved the plugins/ directory outside of the craft/ directory. I've set CRAFT_PLUGINS_PATH in index.php and for web requests everything works fine.

Now I need to run a console command defined in a plugin. When I invoke the console from my shell, the default (incorrect) value for CRAFT_PLUGINS_PATH is set and my plugin's console command is not available.

I've currently worked around this by wrapping craft/app/etc/console/yiic.php, setting the constant before requiring yiic.php like so:

#!/usr/bin/env php
<?php

define('CRAFT_PLUGINS_PATH', realpath(dirname(__FILE__) . "/../plugins").'/');

require_once(dirname(__FILE__).'/../craft/app/etc/console/yiic.php');

Is there a better way to do this / am I missing something?


texts: How do I wire my form action to my controller action?

texts:
I'm writing my first Craft CMS plugin.

I have the following tag in my form:

<input type="hidden" name="action" value="clientnameDonation/donateForm/donate">

And then I have the following controller code to handle the action:

namespace Craft;

class ClientnameDonation_DonateFormController extends BaseController
{
    protected $allowAnonymous = array('actionDonate',
        );

    public function actionDonate()
    {
        // stuff
    }
}

When I try to submit the form, I get the following error:

  Unable to resolve the request "clientnameDonation/donateForm/donate"

Is there a piece I'm missing, or is there a casing error somewhere?

I also tried just using a raw action URL like this:

  http://URL/index.php?p=actions/clientnameDonation/donateForm/donate

I get the same routing error.


texts: Automatically link to entries in rich text field

texts:
Has anyone implemented auto linking of words within a redactor field? For example, a rich text field would contain this:

  A small boat surrounds a large island

In a channel there are entries titled boat and island. I would like to automatically link to these without the editor having to manually link them.

Not sure how approach this so any hints to get me on my way are most appreciated.


texts: What does the Before compile event inside the Contact Form plugin do?

texts:
I see there is an undocumented event called onBeforeMessageCompile in the Contact Form plugin source:

Craft::import('plugins.contactform.events.ContactFormMessageEvent');
$event = new ContactFormMessageEvent($this, array('postedMessage' => $postedMessage));
craft()->contactForm->onBeforeMessageCompile($event);

My questions are:

How does one use this event? What can it be used for? and
Why is an $event object being instantiated at this point in the controller?


texts: How to import LinkIt (custom) fieldtype with Feed Me into Super Table

texts:
I'm trying to import a LinkIt fieldtype into a Super Table with the Feed Me plugin. I've tried several ways but doesn't seem to be working. The part in my json which gets mapped to the Super Table looks like this:

"links": [
              {
                "url": "https://imaginehome.canvas.be/en",
                "description": "Imagine Home website"
              }
          ]

I've managed to register LinkIt as a Feed Me fieldtype, but no matter what I seem to be returning in the prepFieldData function, it will not import it. I have another Super Table field with just some rows with a text input in it and that works just fine.


texts:
I'm running the ElementAPI but would like to take advantage of some functionality provided by another plugin, to return these results in the API. Is this possible? Should all functions available in the main templates be available to the ElementAPI?

To be specific about what I'm trying to achieve--I'm trying to access the Imager plugin to handle optimised transformations of an uploaded image. Here's how the code looks in a regular Twig template

{% set transformedImage = craft.imager.transformImage(image, { width: 200 }) %}
<img src="{{ transformedImage.url }}">

And my attempt to do this inside elementapi.php is:

$sizerOptions = array( 'width' => '202' )
transformedImage = craft()->imager->transformImage( $asset->url, $sizerOptions );

My PHP is not brilliant so I may just be doing something silly here, but wondering if it's my fault, or if I'm attempting to do something impossible!


texts:
First time working with Craft. I've got a Matrix field for team member profiles, title, name, image, etc.

I've got all the info pulled into the page but can't get the image. Here is my code, any help is appreciated!

{% for block in entry.teamMember %}

{{ block.memberName }}

{{ block.memberTitle }}

hometown: {{ block.memberLocation }}

{% endfor %}


texts:
I want to expand functionality of perform plugin with generating pdf from message submission data and attaching it to email this plugin sends.

I can't use events for this, because this plugin doesnt emit any. Can i somehow overwrite specific method in craft cms plugin, without resorting do directly changing code in vendor directory?


texts: List Categories AND their associated entries

texts:
I'm trying to create a category driven gallery. My setup (right or wrong) is this:-

Users create a new entry within a Structure, title it, add photos and then assign the entry to a pre-defined gallery category.

My idea is that when a visitor lands on the 'Gallery' page they see a 'grid' of latest photos (this is a question which might appear here later), with a navigation on the side which allows them to browse the other galleries (categories).

So, how do I list out the categories and associated entries for this navigation?

Example:

Category Title One

Title of the entry1
Title of the entry2
Title of the entry3

Category Title Two

Title of the entry4
Title of the entry5

Category Title Three

Title of the entry6
Title of the entry7
Title of the entry8

Category Title Four

Title of the entry9

I don't want the Category Titles to be links, just the entries within them.

I hope this makes sense and someone can provide a solution.

Many thanks

Martin


texts:
I can get the current year in this way:

{% set currentYear = now.year %}

How do I get the next year?


texts:
I'm trying to query for certain products but only ones that have stock (the products just have defaultVariants):

{% set earliestDate = now | date_modify('- 1 days') %}
{% set latestDate = now | date_modify('+ 10 days') %}
{% set products = craft.commerce.products({
    hasVariants: {
        hasStock: true
    },
    type: 'class',
    date: 'and, > ' ~ earliestDate ~ ', < ' ~ latestDate,
    order: 'date',
    limit: 5
}) %}

The above returns 5 products, all of which happen to have no stock left as identified by them not showing when I use:

{% if product.defaultVariant.stock > 0 %}
    {{ product.title }}
{% endif %}

I'm currently getting products to show by setting the limit to 25 and then it only shows 1 product in stock. Meaning the query is returning 25 products, of which 24 have no stock so shouldn't be returned.

Running Craft Commerce 1.2.1337 so am up-to-date.

Could be related to: Commerce products returning different results on page load

Someone else mentioning it in comment to answer of this: How do I check if a product has stock in any of it's variants?


texts:
What is the best method to organise products, and subsequently the order of these products within a group?

Currently I have setup a product type of Canine. I can access each of these products via a URL of /canine/productslug/ but I am unable to change the order of these products when viewed at /commerce/products/.

The shop will consist of two sections Canine and Equine. I don't think I need to have two product types as they contain the same structure/layout/format. So I can perhaps change the product type to general.

However, being new to Craft, I am unsure how I should be structuring these products? Presumably I need to create either categories or structures and then assign products to these?

I have done some searching but can't find anything to direct me over how I should be setting up the shop for product listings.

Can anyone offer some direction, advise or pointers for this?


texts: Craft CMS on LEMP Stack (mcrypt not detected)

texts:
I have a LEMP droplet on digitalocean that I am trying to get working with Craft CMS.
Strangely it does not seem to play nice with NGINX. Or maybe it's just me.

After installation I am receiving the below message;

I do have php5-mcrypt installed and it appears in phpinfo()

Can anyone help? Thanks.

-- NGINX config for craft (craft.conf)

server {
  listen   80;

  root /var/www/public;
  index index.php index.html index.htm;

  server_name ger1-riverrun.mydomain.com;

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

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

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

  error_page 404 /index.php;

}


texts: How to disable plugin Disable and Uninstall?

texts:
I am developing a site with a customer logged in area. I don't want anyone to access the section if they are logged out and instead redirect them to the login form.

I could just add {% requireLogin %} to the top of all the member templates, but its open to error, especially if we have loads. I am concerned we may forget to add it, accidentally delete the line one day. Then private pages are public, not good.

So I thought I would add the function to a plugin I have created for this site, to remove it from the template, and I can also target the whole /account/ segment where member templates are located.

BUT, the plugin can be uninstalled or disabled. Various people will be Admins, and there is always the possibility someone could disable this for some reason, and then all private pages become public!

So can we disable the ability to disable and uninstall plugins in the CP? The plugin will contain this and other site essential functions that we cant just have someone delete. They need to be fixed into the system to prevent accidental disabling.

If not, is there an alternative way to add functions without using a plugin or controller, so we can override core actions like this without any CP control.

Thanks!


texts:
Can anyone tell me if the Tax Code field in Craft Commerce is able to be validated? I'd  be using it for UK VAT Reg numbers.

I just want to check how it can currently be used. Is it just a field to store the tax code information or can it be used to perform validations.


texts: Output DateTime in that timezone related to the current locale?

texts:
Is there a way to loop through a day in 15-minute intervals, with the output of said intervals being localizable? This (cringe-worthy) snippet should help explain what I'm trying to accomplish:

    {% for hour in 0..23 %}
        {% for min in [0, 15, 30, 45] %}

            {% set foo = [hour, min]|join(':')|date('H:i')|date_modify('+0 days') %}

{{ foo.localeTime() }}

        {% endfor %}
    {% endfor %}

For me, that snippet results in the unusual error Method "localeTime" for object "DateTime" does not exist.

(This question was asked on g+ by Chris Davis. I copied it to SE, as I didn't want to answer it there!)


texts: Image transform not working with different locales

texts:
Working on a site that has a bunch of different locales, I'm bumping into the following issue:

On an entry in locale X, I have an image that is displayed with a transform applied to it. However, getUrl()on the asset returns the following url: /benl/cpresources/404?x=6obDEISgU.

But, when I add that exact same image to an entry in the site's main locale and view it on the front-end, the transform is generated and the image is displayed correctly.

When I then go back to the other entry in locale X (that has that same image), it uses the generated transform (from the entry in the main locale) and the page works.

So it looks like the transformed images can't be generated on the entry in the none-standard locale.

Some settings/parameters:

locales live in their own subfolder as per https://craftcms.com/docs/localization-guide
basePath is set to the main site's document root, without the locale folder
baseUrl is set the main site url, without the locale segment

Any pointers as to how to troubleshoot and/or fix this would be appreciate :)


texts:
I guess this is no big issue, but I'm pretty new to Craft Commerce :)
I'm trying to code a dynamic template for the product variants page.

This is the scenario: In the shop overview you see every product and all there variants. If you click on a variant image a detail page opens, showing you detailed information about this variant.

How can I access data of the variant (like title, description, asset) dynamically? Based on what the user clicked on?

I've already tried these two answers:

How do I select a specific product variant by element/field/entry?

Display image asset of a variant

The thing is, I can't use lineItem because the variant is not added to the cart yet. And I didn't manage to get the specific variant over getSegment and the url.


texts: Deploying Craft on Apache Server - Error code 255

texts:
I'm trying to deploy our Craft 3 site on an Apache server. When running composer install I get the following error.

  @php nys-setup update
  Script @php nys-setup update handling the post-install-cmd event returned with error code 255

Does anyone know what the reason could be or where I could get more detail on the error?


texts: Show a list of recently used tags only from the current locale

texts:
I'm having trouble outputting a list of tags that only includes tags from the current locale.

Here's the setup:

I have a site with two locales: english and spanish
I have a section with handle newsAndEvents
I have a tag field with handle newsTags on entries in that section that is set to translatable to allow my clients to assign locale-specific tags to the entries
I have an entry in that section created with a published version for each of my locales. In the english version, I've added a tag "Turtles" to the entry. In the spanish version, I've added a tag "Tortugas" to the entry.
On the landing page of my news section, I am displaying a list of recent tags in a sidebar. Here's the code I'm using to do it:

{# grab the entries in the specific locale #}
{% set entries = craft.entries.find({section: 'newsAndEvents', locale: craft.locale}) %}

{# Grab the related tags for those entries #}
{% set tags = craft.tags.relatedTo(entries) %}

{# Build the list #}
{% if tags | length %}

  {% for tag in tags %}

{{ tag.name }}

  {% endfor %}

{% endif %}

The problem is, when I'm looking at the english version of my landing page, I get both "Tortugas" and "Turtles" in the list output by the code above. What I want is to only see the tags on english versions entries on the english landing page; and the tags on spanish versions of entries on the spanish landing page.

Some additional info:

If an entry has only one published version, english for example, any tags I assign to that version do not appear on the spanish landing page, as would be expected.
On my entry detail pages, I'm using similar code to generate a list of tags assigned to the current entry, and the output is what I expect: english versions only show tags assigned to english versions, not to both english and spanish like on the landing page.

What am I missing?


texts: How can I display related entries selected within a Matrix field?

texts:
Consider an employee listing...

I have 2 sections: 1 for companies, 1 for personnel.  In the personnel section, there is a matrix field within which one field is a relational one to relate the staff member to his company.

On the front end, I'm attempting to display a listing of all staff associated with a particular company.

I can't seem to get the relational fields to work in the way that I want. I know I'm missing something basic here.

{% set employer = craft.entries.section('companies').slug(segment) %}
{% set personnel = craft.entries.section('people').relatedTo(employer) %}

{% for x in personnel %}
    {{ x.title }}
{% endfor %}

// Output: nothing

Is there something particular to Matrix fields that changes how I might do this?  I've tried using the targetElement parameter but still can't seem to get it to work.

Thanks for the help!


texts: Getting 'signed out' after exactly 1 minute of inactivity

texts:
I've launched a site recently which is being hosted on Vidahost's Cloud servers. After exactly 1 minute of inactivity, anyone using the control panel is signed out. Except that if you refresh the page when you're "signed out", you're actually still signed in (but you lose any changes you were making).

So far I've tried changing the config setting overridePhpSessionLocation to auto, false and true, and nothing has changed. I've also tried changing the PHP version from 5.4 to 5.5 to no effect.

How can I stop this from happening?


texts: How to apply a "without" filter in a plugin

texts:
I have and array of with allEntries and an array with alreadyUpdatedEntries. I would like to filter out all the alreadyUpdatedToEntries to end up with an array of notUpdatedEntries. Like how it is done in Twig.

{% set notUpdatedEntries = allEntries|without(alreadyUpdatedEntries) %}

Is there a similar Craft PHP method to do this in my plugin? Can I maybe include this in my elements criteria query?


texts: Create default password for new user registration in CP

texts:
I have a situation where I want to assign a default password when a user is registered in the CP, but only if they are assigned to a specific user group. Plugin code looks like this:

craft()->on('users.onActivateUser', function(Event $event)
{
    $user = $event->params['user'];

    // Test to see if a user is in group
    if ($user->isInGroup('groupName'))
    {
        $user->newPassword = 'Password123';
        craft()->users->saveUser($user);
    }
});

I've tried latching on to both the users.onSaveUser and users.onActivateUser events, and in both situations, there are no groups are assigned to the user. Is there an event that is at the absolute end of user registration that I can watch to access their user groups?


texts: How can I prevent Redactor italicising text within asterisks?

texts:
In my Rich Text field,  I've got some text that looks like this (it uses an unordered list):

• Line 1
• Line 2*
• Line 3

* Here is some more text

The problem is that the "Line 3" text is appearing in italics, and neither of the asterisks display in the page preview.

Is there a way I can stop this from happening? Perhaps there's an escape character to use in this situation?


texts: Extra spaces appearing in Rich Text fields after 2.5 update

texts:
In addition to the inability to resize images in the rich text fields (mentioned elsewhere), I'm having issues with rich text fields, particularly in Matrix blocks, inserting extra spaces between paragraphs.

While an entry may be rendering normal on the frontend, opening up the entry will show the paragraphs with large spaces between them. Looking into the HTML, these appear as a series of tags like

Strangely, when switching back and forth between the normal and HTML view, more and more of these spaces are inserted between the paragraphs. Do I have the option to rollback to the earlier version of Redactor? Any help or suggestions are appreciated!


texts:
We just found out that in the database birthday field, all dates has 1-day difference than what is shown on the front-end.

On the front-end, it is the correct date by the way.

Question: Is it a bug and if not, why is this?


texts: Disable Stripe email notifications from Commerce

texts:
When a customer completes an order using Stripe they get an email notification from Stripe. I have configured notifications to be sent from Craft and would like them to only get those emails. After looking into this for a bit, it seems like I need to stop Commerce from passing the receipt_email to Stripe to stop this from happening?

https://craftcommerce.com/changelog#build1323

Commerce now provides Stripe with the customer’s email address to support Stripe’s receipt email feature.

https://support.stripe.com/questions/email-receipts

If you charge a customer that already has an email address attached to it, passing in a receipt_email with a charge will override the customer’s stored email address, and we’ll send the receipt to the email address specified in your charge request’s receipt_email regardless of your email settings.


texts: Using a plugin, how can I manipulate entry data?

texts: I am trying to develop a plugin and what I want to do in this plugin is to be able to access the contents table that is already defined in the database and get and update entries in this table. What would be the best practice to do this? I know records can create new tables but how can I access or manipulate an already created table that is not part of my plugin but is created in the database by default?


texts: Utilizing/ Converting another database with craft

texts:
(First off, I apologize for the really long question, but any help I can get would be appreciated!)

Hello!
I am taking over a bunch of sites that a developer had created for a company (I am not a developer, but I have some coding knowledge and wordpress experience).  Anyway, I want to switch over the site from just php and sql to a CMS and I feel like Craft might be the one.  However, I feel like it might just be over my head.

Basically the cms needs to manage an event (or if 1 instance of Craft can handle multiple events, each with its own website, even better!)
Each event visits up to 40 cities a year and has up to 3500 attendees at each one.  And all information regarding attendees, venue, host hotel, faculty, schedule, etc. is all stored in a data base.  And all that information is displayed on the site on pages that are created dynamically by the cities name, year, etc..

My question is: How would I transfer all of that into Craft and organize it appropriately?  And would this be possible for someone with limited knowledge of coding?

I am willing to do all the research necessary, or if its way out of my league, hire a developer to do it for me.  I just need a nudge in the right direction.

Thanks for your time!
-Alex


texts:
I'm outputting fields from a Matrix block, how do I then wrap all outputted fields from 'artworkFile' that are available with some HTML. Not individually wrapped, but all outputted fields.

Current Code:

{% case "artworkFile" %}
{% for asset in block.downloadUrl %}

{% endfor %}

Desired Output

Matrix Setup


texts: Error with Craft CMS set up and composer: failed: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)

texts:
Hi I am trying to set up craft CMS with composer. I am using MAMP on a mac and I just cannot get it to connect. I get this error even though I know the password is correct.
failed: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)

I have tried setting up a new user with new password and ensure full access privileges are set up on that database but I get the same error. I have tried setting up a separate host but when I try and run the Craft CMS set up with that I get this error:
Testing database credentials ... failed: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known

Any help with this would be much appreciated as I've wrestled with it all day now. Thanks.


texts: How to update stock on a product variant? Setting unknown property error

texts:
I am trying to update stock of product variants using a custom plugin on our Craft 3 eCommerce site (its a sync process with an external database). But I can't figure out how to update stock, I get an unknown property error for the field stock.
use Craft;
use craft\web\Controller;
use craft\helpers\ElementHelper;
use craft\commerce\elements\Product;

$productEntry = Product::find()->hasVariant(['sku' => 'mysku'])->first();
if($productEntry)
{
    if (!$productEntry->hasUnlimitedStock)
    {
        $productEntry->setFieldValue('stock', '10');
        echo Craft::$app->elements->saveElement($productEntry);
    }
}

But I get a "Setting unknown property: craft\behaviors\CustomFieldBehavior::stock" error:-
2021-01-18 11:21:33 [-][1][9319132c27bbf8aa77f29e2606c2b4ea][error][yii\base\UnknownPropertyException] yii\base\UnknownPropertyException: Setting unknown property: craft\behaviors\CustomFieldBehavior::stock in /home/mysite/craftcms/vendor/yiisoft/yii2/base/BaseObject.php:163
Stack trace:
#0 /home/mysite/craftcms/storage/runtime/compiled_classes/CustomFieldBehavior_zmbofhbcdvie.php(895): yii\base\BaseObject->__set('stock', '10')
#1 /home/mysite/craftcms/vendor/craftcms/cms/src/base/Element.php(2672): craft\behaviors\CustomFieldBehavior->__set('stock', '10')
#2 /home/mysite/craftcms/plugins/mysite/src/controllers/SyncController.php(225): craft\base\Element->setFieldValue('stock', '10')
#3 /home/mysite/craftcms/plugins/mysite/src/controllers/SyncController.php(90): mysite\mysite\controllers\SyncController->updateEntries(Array)
#4 [internal function]: mysite\mysite\controllers\SyncController->actionSyncStock()
#5 /home/mysite/craftcms/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#6 /home/mysite/craftcms/vendor/yiisoft/yii2/base/Controller.php(180): yii\base\InlineAction->runWithParams(Array)
#7 /home/mysite/craftcms/vendor/craftcms/cms/src/web/Controller.php(190): yii\base\Controller->runAction('sync-stock', Array)
#8 /home/mysite/craftcms/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('sync-stock', Array)
#9 /home/mysite/craftcms/vendor/craftcms/cms/src/web/Application.php(274): yii\base\Module->runAction('mysite/sync/sy...', Array)
#10 /home/mysite/craftcms/vendor/craftcms/cms/src/web/Application.php(577): craft\web\Application->runAction('mysite/sync/sy...', Array)
#11 /home/mysite/craftcms/vendor/craftcms/cms/src/web/Application.php(253): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#12 /home/mysite/craftcms/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#13 /home/mysite/public_html/index.php(23): yii\base\Application->run()
#14 {main}
2021-01-18 11:21:32 [-][1][9319132c27bbf8aa77f29e2606c2b4ea][info][application] $_GET = [
    'p' => 'actions/mysite/sync/sync-stock'
]


texts:
Currently my editors do not know when new content submitted by a user without publishing permissions is ready to be reviewed. The status of "disabled" could refer to an in-progress draft or a completed draft ready to be reviewed by an editor. There is no way the user can flag their article as ready and for this to be easily exposed to the editors in the admin panel.

How could this be addressed.


texts: Ordering entries based on an eager-loaded element's custom field

texts:
I have a query that loads a set of movies, and eager-loads corresponding shows, which are related elements. For now, the movies are sorted by startingDate, which is a custom field in the movie entry:

{% set currentMovies = craft.entries({
        section: 'movies',
        type:    'movie',
        order:   'startingDate asc',
        limit:   null,
        with: [
            'shows',
            'poster',
            'stills'
        ]
    })
%}

What I actually want is to sort the movies by whichever film has the first upcoming screening. That basically means I would like to order the set by something to the effect of order: shows.showTime or order: shows[0].showTime, but that doesn't seem to work.

Is there a way to order by a field on a related entry, or is that variable simply not yet accessible at the point of ordering?

I tried to eager-load the shows.showtime field, but realised that doesn't work either, as eager-loading only makes sense for relations, not fields themselves.


texts: Front end entry dropdown with null option

texts:
I have successfully implemented a front-end form that allows the user to add new "blocks" to a certain matrix field. This matrix field has one text field, two date fields, and one entry field that links to one specific entry type: sites.

How can I add an option to the dropdown list that would allow the user to "ignore" this field as if they left it alone when adding data in the admin area?

Here is what I have tried:

<select name="fields[scriptLots][new1][fields][lotSite][]">
    <option value="">No Site</option>
    {% for site in sites.order('title') %}
        <option value="{{site.id}}">{{site.title}}</option>
    {% endfor %}
</select>

I figured just adding an option tag ahead of the for loop with no value would do the trick. However this just responds in a major error:

CDbException: CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`dsi_craft_vetscripts`.`craft_relations`, CONSTRAINT `craft_relations_targetId_fk` FOREIGN KEY (`targetId`) REFERENCES `craft_elements` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `craft_relations` (`fieldId`, `sourceId`, `sourceLocale`, `targetId`, `sortOrder`, `dateCreated`, `dateUpdated`, `uid`) VALUES (:row0_col0, :row0_col1, NULL, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7). Bound with :row0_col0='54', :row0_col1='3382', :row0_col3='', :row0_col4=1, :row0_col5='2017-11-07 15:26:00', :row0_col6='2017-11-07 15:26:00', :row0_col7='06895bfe-d902-49f6-a085-bd080f68cdef'

So that empty value attribute seems to be breaking something. How can I add a null option?

Thanks!


texts:
Has anybody implemented an affiliate program system ? If yes, how ?
I saw that Superbig has a plugin in his pipeline, but it's not out yet.
Thanks a lot for your feedback !
Antoine


texts: Sub-Entries: Adding new Entries on Entries field

texts:
I'm trying to write my first CraftCMS-Plugin.
It should behave like the "Entries" field, so I inherit from it.

The difference is:

I don't want to allow the user to select existing entries.
They should just add "news" to the "team".

The user visits his team
There are no news assigned to the team yet
He clicks the "add" button
A new News-Entry is generated (see Screenshot, i like the Quick-Add widget)
The News-Entry is automatically "linked" to the Team

I just don't know how to start.
The field is already in place and it inherits from "Entries".

But how can I "move" the "Quick-Add" Button from the "Select-Modal" (see screen) to my Field-Type. It seems to just trigger a POST-Request.

Is there an event i can trigger manually or how does this work, how can I hook in?


texts: Default Upload Location needs matrix field and entry info... How?

texts:
I have a towns entry with a matrix field: townAlbums.

This matrix field has just one block type: photoAlbum.

This one block type has two basic text fields (the important one being albumName and one asset field for uploading images to the gallery: albumPhotos.

I want the Default Upload Location for this matrix subfield albumPhotos to be dynamic, taking both the parent entry slug (slug of the town entry) and the name of the album: albumName. I'm not sure how to accomplish this.

Desired url:

http://sitename.com/uploads/towns/town-slug/album-name/filename.jpg

What should I be entering for my Default Upload Location?

Thanks!


texts: I've inherited the Craft website and the developer is long gone. How do I access the templates used to initally build the site?

texts: Our website was created by someone who is no longer with the business. I can edit existing data, however am trying to access the original templates used when the site was originally built in order to change a few things. Where would I find these?


texts: Apply inline styles to selected text in Redactor

texts:
I'm aware, that this question is a little bit out of scope to Craft, but It relates, when redactor is part of Craft.

I was playing around and I must tell, that it's horrible to create a text with  redactor. Especially, if you need insert a htmlTag within paragraph.

In myredactor.json file all formatting features are set according to documentation, but I found out, that redactor by default, doesn't support highlighting text, only through API

Update

Example: Here at stackexchange, you can highlight text to code or bold or ...etc. in very lovely and clever way. To do it in redactor by highlighting text and selecting a type format from dropdown menu, imposible ... yet.


texts:
I'm building a customer portal for work, and we are storing customer-facing files on the site in an Amazon S3 bucket. I currently have it all set up as a Structure section with an Asset field. I query for each entry using its uri, and for Folder Entry Types I pull and output its children.

My hope is that I can instead query for Asset folders and files directly, and then add a few fields to Assets (through the usual methods). Querying for files is fine, but I can't see any variables to pull folders. Would I need to write a plugin for this?


texts: Image Transforms: Is there a way to detect portrait or landscape?

texts:
I'm looking to setup an image transform via the control panel but I only want to resize the image (scale - not crop or fit). The trouble is that I don't know whether the uploaded image will be a portrait or a landscape. Is there a way to set it to just scale to a maximum bounding box?

For example, if I want images to be a maximum 1000px width or height (whichever the longer edge is), how can I set that and maintain aspect ratio?


texts: Craft Commerce - empty cart.adjustments data

texts: I'm having a Craft Commerce issue receiving cart.adjustments data in my twig templates. I've created a shipping category and shipping method with a rule to add a base rate of $10 to every order, but am not receiving any data from the front end; cart.adjustments is shown as empty. could someone please help me with resolving this issue? thank you


texts:
I have that simple variable in my javascript

var toLoad = '{% "include _views/reviews.twig" %}';

and on a page load I get template error that is defined in the title of question.

That variable is defined in template, that includes another template and in that included template is called some 'class' to load reviews.twig from our variable defined in parent template.

Any thoughts?