texts:
Is it possible to serve a file in a Twig template? I need to get a file (asset) from a global setting, and serve it at a particular URL.

This code is close, but it seems that source() is the wrong method to get the file contents with.

{% header "Content-type: application/pdf" %}
{% header "Content-Disposition: inline" %}

{% set filePath = [craft.config.environmentVariables.assetPath, filesImages.deliveryCalendar[0].filename]|join('') %}

{{ source( filePath ) }}

The variable filePath contains the correct system path to the file (/var/www/site.com/html/assets/file.pdf), but source() is clearly for templates and not files.

How can the contents of a file be streamed out to the browser?


texts:
I downloaded a database backup from the craft back-end. I've tried to restore it via PHPMyAdmin and MySQL workbench, and I get the following errors:

ERROR 1227 (42000) at line 18: Access denied; you need (at least one of) the SUPER, SYSTEM_VARIABLES_ADMIN or SESSION_VARIABLES_ADMIN privilege(s) for this operation

At line 18 in the SQL file:

SET @@SESSION.SQL_LOG_BIN= 0;

Is there any way I can get around this so I can restore this database? I'm desperate right now.


texts: Is there a rich text editor for Craft CMS which supports both HTML source code edit as well as adding images by URL (not uploading to assets)?


texts: Get all available fields in plugin setting page

texts:
I am trying to get all the fields created by admin in my custom plugin setting page.

As we can get entries , in same way can we have option to get the available fields.

 {{ forms.elementSelectField({
    label: 'Entry Select Field',
    id: 'entries',
    name: '',
    elementType: 'craft\\elements\\Entry',
    elements: [craft.entries.one()],
    selectionLabel: 'Select an entry',

}) }}

  I tried to look in core file :/vendor/craftcms/cms/src/services/Fields.php

$fields = Craft::$app->fields->getAllFields();

But there is no such method which return the list of existing fields.

Update:

Now i am able to get the list of all the existing fields.

$fieldsData = [];

$fields = Craft::$app->fields->getAllFields();

foreach ($fields as $field)
{

    $fieldsData['name'][] = $field->name;
    $fieldsData['handle'][] = $field->handle;
}

In setting the template of plugin I want to give admin an option to select multi fields (handles ) on the plugin setting page. For this, I am trying to fetch all the created fields first and then pass that array to form micro so that it can populate the multi-select.

  But can we populate multi-select like?

{{ forms.multiselectField({
    label: 'Multi Select Field',
    name: '',
    options: {
      fields['handle']: fields['name'],
    },
    values: '',
}) }}

  Or if we create our custom multi-select fields how we can save the user ( admin) input? as in micro, it saves by itself.


texts: I'm trying to sort the entries. Is there a way to do this without using the filters given? Can this be done manually?


texts: Display X number of characters from an entry

texts:
I want to display just a short blurb from each blog entry. I dont know how to display my { entry.blogentry } without having all of the text show up.

Is there a way to just show the first 100 characters OR first few lines?


texts: Is there a Zendesk plugin to fetch order information from Craft Commerce?

texts:
I'm looking for the same functionality as https://wordpress.org/plugins/mwb-zendesk-woo-order-sync/ but for craftCMS's Commerce plugin and not Wordpress's Woocommerce plugin.
Basically, it would use the reporter's email from the zendesk ticket to get the order or orders from Craft Commerce and display the order information in a zendesk widget.
I've looked, and all I can find are plugins for creating tickets.
Does anyone know of an existing plugin for zendesk that does this?


texts:
I hope anyone can help me to get started. I think I have a brain freeze or something.

I have created a section (structure) that is called "House".
I want this section to use a template. In craft/templates/ I have created the folder "house" with the file index.html in it. I have also tried _entry.html.

When I then go my URL (for example): project.com/house it can´t find anything. Could not find the path on the server.

Is there something "wrong" on the server that don't allow access to that URL?


texts: Sprout Forms: Passing Checkbox variable in url parameter

texts:
I'm trying to create a "teaser" form in Sprout Forms.
First form has radio buttons and a group of checkboxes, and it's easy to pass the radio value (via redirect), but I'm not finding the documentation on how to pass checkbox fields as URL params.
Redirect: /contact/?radio_button={radio_value}&checkbox={fields-goals-1}
The second form will accept those params and ask for contact information.
Anyone got an example of how this?


texts: Get random entries, excluding an array of entry IDs, where a relational field is not empty

texts:
I'm trying to pull a set of 3 random entries from a Section. The entries need to have a certain Assets field not empty, and I also have to exclude entries already pulled (these entries are stored in the variable entriesA).

The issue is that with my current query, the ID exclusion doesn't work – i.e. I'm getting back entries found in entriesA.

Here's how the query looks:

{% set entriesB = craft.entries({
    section : 'someSection',
    assetsField : ':notempty:',
    limit : 3,
    order : 'RAND()',
    id : 'and, not ' ~ entriesA.ids()|join(', not ')
}) %}

The problem appears to be the assetsField : ':notempty:' statement – when I remove that, I get no duplicates. When it's included, Craft appears to ignore the id parameter and I get back duplicates.

Anyone know what's up? Is it not possible to query using :notempty: statements and id?


texts: How to display all entries within a given category

texts:
I've got a category group called allcategories, inside of this is two categories called design and photo.

I'm trying to filter all entries in the section projects by the category `photo' but none of my permutations are working :(

    {% set category = craft.categories.group('allcategories').find('photos') %}
    {% set projects = craft.entries.section('projects').relatedTo(category).find() %}

    {% for entry in projects %}

{{ entry.title }}

    {% endfor %}


texts: Are there any Craft 3 plugins yet? They would be useful as examples for porting/writing other Craft 3 plugins.


texts:
Is it possible to store partial dates? EG i want to create a document that covers a date range, sometimes that range could be Jan/2013 to JUN/2014 other times we may need it more specific EG 20/JAN/2013 to FEB 2014 and sometimes even less specific like 2013-2015.

Would i need to create a new custom field type?


texts: Updated Information Requested | Craft CMS & MariaDB

texts: Is Craft stable atop MariaDB? The last update concerning MariaDB was October of 2014.


texts:
Craft\WebApp and its behaviors do not have a method or closure named "getInfo".

appeared today, nothing has been updated or changed.

Any ideas?


texts:
Bit of an odd one here I can't quite work out. It's late and my brain is melting.

I am creating an Artist listing page. It is a Single where the client can pick which category of Artist they want to be listed. They do this via a category field on the Single.

I have a channel of Artists, and each artist has a Category field where they can be listed as playing in a given category. All simple enough so far.

The categories look like this:

My problem: how do I loop through the artists and group them by their sub-categories? For example - the client has decided that on the listing page they want to list Ymuno Summer 2011. I need to then spit out all related artists, grouped by Friday and Saturday. An artist may be performing on more than one day.

So far I've stripped things back as far as:

{% if entry.featuredLineup | length %}
    {% set artistsInLineup = craft.entries.section('artists').relatedTo(entry.featuredLineup) %}

    {% for artist in artistsInLineup %}
        ...
    {% endfor %}
{% endif %}

But even that isn't spitting anything out at all, other than getting into the outer conditional. I feel like I'm making a rookie mistake, but everything I've seen in the docs is hard-coded relations rather than pulling from an entry field. I'm not even sure I'm thinking straight about the problem anymore.


texts: Installing Craft CMS 3 on hosting - Unsupported DB driver value

texts:
i am trying to instal Craft CMS 3 on hosting and everytime it is going to fall on:

  2019-07-05 16:33:55
  [-][-][-][error][craft\base\ApplicationTrait::getIsDbConnectionValid]
  There was a problem connecting to the database: Unsupported DB driver
  value:  2019-07-05 16:33:55
  [-][-][-][error][yii\base\InvalidConfigException]
  yii\base\InvalidConfigException: Unsupported DB driver value:  in
  /data/web/virtuals/136413/virtual/www/subdom/duetback/vendor/craftcms/cms/src/config/DbConfig.php:188

On installation page i can se:

  An internal server error occurred.

I have no idea, what is going on.

On localhost everthing goes fine with same settings.

Thank you!

Ondrej


texts: Setting channel url format to include value of entries fieldtype URL

texts:
I have a channel with an entry type which has a simple dropdown for {region} and an entries fieldtype which links to a channel of destinations.

I'd like the URL format for the channel to be /region/destination/slug. If I do /{region}/{destination.url}/{slug} the output is /region-name//entry-slug, i.e. nothing is output for the destination.

What should I have where I currently have {destination.url}?


texts: How do I combine search for categories and entries into one set of search results?

texts:
I have a search page. I can search either categories or entries using

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

I have added quite a bit of content in each category i.e. what it's all about etc. and I would like this content returned like a standard search result going to the category URL (it works when I search categories only)

I've tried to merge the above two arrays

{% set results = categories | merge (entries) %}

But that's obviously not how you do it because it throws a craft error.

Now, I guess I could return the results of one, and then the other, but I was hoping to have the score create a more sensible order of relevant results.


texts:
Anyone using the "Store Hours" plugin know how to print out day open and close hours details?

I have tried this but not outputting anything.

{% for openTime in entry.openTimes %}
    {{openTime.day.open}}<br>
{% endfor %}

Note: openTimes is a field of StoreHours type.

Any help will be appreciated.


texts: How can I add a dynamic "active" CSS class to the navigation on any given page?

texts:
Just wondering how people approach setting a class of current in their navigation. Is there anything in Craft or Twig where you can set a conditional to check if a page is the current page. Or do you just need to set classes/ids on the body tag based on the segment?

Any ideas appreciated, Gareth


texts:
I'm building a project with a lot of photo assets organized into sub directories of the main photos asset source. I'm trying to add tags to these assets so they are searchable when I try to use them in my entries.

With native features of Craft, this process seems to be very manual, I just have to click on each of these asset files and add the tags that I want.

Is there a way, either using a plugin or make a MySQL query, to bulk add tags to all the asset files under a certain sub directory?


texts:
I haven't made a new single in a few years, it seems. Now when I try to create one, there is no option to do so. Normally, the New Entry button seems to be split, with the left part directly creating a new entry in the currently selected channel or structure, and the right part giving a drop-down with the various channels and structures available. However the drop-down does not include Singles, and if I have Singles highlighted, then the New Entry button doesn't have the left part, just the drop-down.

Also, if I try to edit an existing single, there is no option to save as a new entry or save and add another. Any thoughts?


texts: Upload images bigger than 1MB not working

texts:
I am trying to upload jpg assets to Craft. As long as the files are smaller than approx. 1MB it's working, even in bulk upload. As soon as there's a file bigger than 1MB Craft gets stuck like this:

You can see on the image that files smaller as the 1MB have been uploaded successfully.

The file doesn't show up in the assets directory on the server file system.

I enabled devMode to take a look at the logs but no error level log entry shows up that is related to the upload request. JS console shows no errors as well.

So my question is: What is going on? How can I fix this so I can upload files within the limits I specified in php.ini?

Some info:
I am using Laravel Forge + DO
Web server: nginx/1.11.5
PHP Ver: 7.1.0
post_max_size = 14M
upload_max_filesize = 12M

PS: I say approx. 1MB because I was able to test with files that are roughly below/above 1MB file size.

Update
I noticed Imagemagick was not installed. After installation: no difference. I even disabled GD: no difference.


texts: Best practices of converting an already created site into Craft CMS?

texts:
We have various clients who already have websites but would like us to optimize them a little bit and set them up on craft.

Is there a more efficient way to do this than just hand coding all of the PHP and blocks for every page to align to be editable on craft?


texts: Sort entries by custom date in Matrix field / Super Table

texts:
I currently have numerous Super Tables with date fields inside and I am trying to get all table items to list themselves together in date order depending on what the user inputs. I have tried using the Super Sort plugin but haven't had any luck.

Not sure if there is somewhere below where I have gone wrong or misunderstood the documentation. The plugin I am trying to use can be found here

Does anyone know if this is possible with Super Tables or Matrix fields?

The error I'm currently getting is:

  Object of class Craft\ElementCriteriaModel could not be converted to string

protected function doDisplay(array $context, array $blocks = array())
{
  echo $this->getAttribute($this->getAttribute(($context["object"] ?? $this->getContext($context, "object")), "tourDates", array()), "tourDate", array());
}

if (version_compare(PHP_VERSION, '7', '>=') && $code === 2 &&
strpos($message, 'should be compatible with') !== false)
{
    return;
}
parent::handleError($code, $message, $file, $line);

protected function displayWithErrorHandling(array $context, array
$blocks = array())
{
    try {
        $this->doDisplay($context, $blocks);
    } catch (Twig_Error $e) {
        if (!$e->getSourceContext()) {
            $e->setSourceContext($this->getSourceContext());
        }

This is the code I current have:

{% set artists = craft.entries.section('artists') %}
{% set entries = artists | supersort('sortAs', '{ tourDates.tourDate }') %}

{% for entry in entries %}

    {% if entry.tourDates %}
        {% for row in entry.tourDates %}
            {{ row.tourDate|date("d/m/Y") }}
        {% endfor %}
    {% endif %}

{% endfor %}

I have also tried:

{% set entries = artists | supersort('sortAs', '{ tourDate }') %}

and

{% set entries = artists | supersort('sortAs', '{{ artists.tourDates.tourDate }}') %}


texts: Problems transferring updates back to live server

texts:
For quite a long time i've updated and amended Craft by taking a copy of the files and database (.zip) from the live server, making the updates/changes/amendments locally and then transferring everything back (.zip).

Just recently i've had a couple of instances where i've made amendments and updates to an older site (Craft 3.1x to 3.4x) and everything has been fine locally. I then deploy the updated version back to the live environment and immediately get the error Craft can’t connect to the database with the credentials in craft/config/db.php.

I know this is a familiar error for some but i've only recently started seeing it.  I've spent a long time looking for and trying fixes but nothing seems to work for me!?

Mac OS Catalina
MAMP Pro 5.7
PHP 7.2.22
MySQL 5.7.26

Like I say, this is actually quite a new problem for me and I don't know what has changed?  Any help is very much appreciated.


texts: What is the recommended Nginx configuration for Craft?

texts:
I'm looking for the recommended way of how to configure Nginx server to run Craft.

Currently, I use the following configuration, it works, but I don't know if it could be better:

server {
    listen 80;
    server_name example.com;
    root /home/vagrant/craft/public;

    index index.html index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

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

    access_log off;
    error_log  /var/log/nginx/example.com-error.log error;

    error_page 404 /index.php;

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

    location ~* (?:^|/)\. {
        deny all;
    }

    location ~* (?:\.(?:bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$ {
        deny all;
    }

    location ~* \.(?:manifest|appcache|html?|xml|json)$ {
        try_files $uri /index.php?$query_string;
        expires -1;
        access_log /var/log/nginx/example.com-access.log;
    }

    location ~* \.(?:rss|atom)$ {
        try_files $uri /index.php?$query_string;
        expires 1h;
        add_header Cache-Control "public";
    }

    location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
        try_files $uri /index.php?$query_string;
        expires 1M;
        add_header Cache-Control "public";
    }

    location ~* \.(?:css|js)$ {
        try_files $uri /index.php?$query_string;
        expires 1y;
        add_header Cache-Control "public";
    }

    location ~* \.(?:ttf|ttc|otf|eot|woff)$ {
        try_files $uri /index.php?$query_string;
        expires 1M;
        add_header Cache-Control "public";
    }
}


texts:
I'm getting the following internal server error message when I try and make a change on my website. It is only happening on one page!

file_get_contents(https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=610+Bunker+Ave.+Kellogg%2C+Idaho+83837): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden


texts: When onAfterElementSave is called check for save as draft or publishing?

texts: Is there a way to detect if a entry is being saved as a draft vs being published so when onAfterElementSave is called, so I don't save data to the database when it is a draft.


texts: How to redirect an entry's URL to a specific URL?

texts:
Say I have a custom field "URL" for each entry and I want them to be redirected to these specific URLs instead of Craft's.

Similar to WordPress "Page Links To" plugin. http://wordpress.org/plugins/page-links-to/

Can I do this in Craft?


texts:
My template has this line that I want to update from a field in craft:

{% set form = craft.formBuilder2.getFormByHandle('schoolTrip') %}

I want 'schoolTrip' to be replaceable by a plain text field in craft. My plain text field is named 'formName'.

{% set form = craft.formBuilder2.getFormByHandle('block.formName') %}

just gives me errors.


texts: How to retrieve the mode of an image transformation from its name?

texts:
I work on a portfolio with a large number of images with very high sizes and a lot of images transforms. The server on which this site is hosted reach these limits (images generations process are generally blocked), so I would like to experiment with imgix in order to move the transformations of images in the cloud.

I need to tell imgix how to crop images and I prefer to define my transformation types in the Control Panel rather than in the templates. How can I retrieve the mode of an image transformation from its his name?

Is there something like {{ craft.assets.getMode('myTransformName') }} ? I haven't found a method for this in the documentation.


texts: How do I fetch all categories under a category group using the Element API?

texts:
I am not too familiar with PHP and am just learning the Element API.
How do I turn this craft query into an element api query?

craft.categories.group("brands").level(1).all(),

In categories this is what it looks like

Brands
    -Luxury
        -Gucci
        -Chanel
        -Louis Vuitton
    -Streetwear
        -Supreme
        -Bape
        -Off White
OtherCategory
    - ...
SomeOtherCategory
    - ...
    - ...


texts:
When rendering the output of a single Star Rating field using the default Flexbox form, the output creates its own styling, overriding what I put in the element it's in... and adds a "float: left" pushing the star rating to the left. What I want is for it to be centered like the other content in the div. I'm fine with the default styling of the form before submitting, but why is it floating this content left when I'm just calling that one field in the "thanks" page displayed after they submit?

Thank you for your feedback!

{% set submission = craft.freeform.submissions({
  form: 'giveFeedback',
}).one() %}

        We have received your submission.

       {% if submission %}
     {{ submission.starRating.renderInput()}}
     {% endif %}


texts: Available updates not displaying on local copy but show up on live site; instead displays "You're all up to date!" with 5 pending updates

texts:
When I attempt to display available updates on my local copy, Craft is unable to display them and instead shows “You’re all up-to-date!”.

Available updates do display on my live copy, as well as on the “updates available” badge on the local copy CP.

I’ve cleared the cache to no avail and I’ve checked the logs and can’t see any errors. I'm running an nginx server and am starting to wonder if this problem arose when switching from apache -> nginx.

I am currently running version 2.6.2996 and am trying to update to 2.6.3001 as well as update a few plugins.

Has anyone run into this issue while trying to display updates on their local copy CP?

The responses coming back when I hit the updates page were all 200s and allowAutoUpdates was set to true using the default setting.


texts: How to use a plugin to add own fields, values, forms,...?

texts:
in short:
Can you please point to some (working?) sample of implementing a barebone default / dev setup (css, js, basic templates, custom fields, groups, users, matrix forms, front-end forms,...) using a plugin?

Also: Is there a way to "enforce" presence (installation and activation) of "related" plugins ("must use" plugins) so I can develop a theme with functions/features related to other plugins I do not own?

Background:
I am starting over (again) with craft, simply as I am fed up managing plugins (i.e. with wordpress). One thing that I am really missing - which may be due to limited coding experience with craft - is a simple way to add my "defaults" (css, js, fields, forms, groups & related (test)users,...) to the system to proceed creating templates (internal as well as customers). In wordpress I could simply extend the functions.php or use a custom site or template related plugin providing me the basics I want/need to proceed developing themes or plugins. In craft I don't get the point / simply don't understand where to start just to add custom fields and relations. I also don't see how I could use a plugin to create t theme / copy the related files and have them "managed" by my plugin.


texts: Select entries starting with same letter from alphabet list

texts:
I have a list of all my games using pagination. It works great:
http://www.colorcomputergames.com/games

However, I'd like to add links at the top of the page like:
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z

And so I want to be able to click on any letter and display only entries starting with that letter.

I was was going to make a template for every page but that seems inefficient.

How should I tackle this?


texts: Load entries based on category field value while multiple categories are selected

texts:
I have an activity calendar (more like a weekly schedule) which filters per day and per category. Because there are so many activities I can't just load them all in at once so I use some sort of Ajax pagination kind of way which grabs the category handle.

The problem is, it will always use the first category that has been selected for the event instead of going through them all.

So everything works fine as long as 1 category is selected.

Here is my code:

{% if craft.request.getParam('cat') == '' %}
     {% set selectedCat = 'startingCategory' %}
{% else %}
     {% set selectedCat = craft.request.getParam('cat') %}
{% endif %}
<div class="row activiteitenRow" id="tegelContent">
     {% for category in craft.categories.group('leeftijdsGroepen') %}
          {% set query = {
                 section : 'sportidEvenementen',
                 order : 'evenementDatum desc',
                 limit : null,
                 relatedTo : category,
           } %}
           {% set entries = craft.entries(query) %}
           {% for entry in entries
                  if entry.categories[0]|camel == selectedCat
            %}

            {# activity display code here #}

            {% endfor %}
      {% endfor %}
</div>

I think the problem is in the final forloop:

{% for entry in entries if entry.categories[0]|camel == selectedCat %}

I used .first() Before but it was obvious that would only grab the first category but it needs to use an array but, really can't find a way to fix this.


texts: Craft redirects to domain.tld/domain.tld/ on logout

texts:
I have a logout button on my site that points to the logoutUrl.

While the logout works and ends the user session, the user is brought to a page with the URL similar to domain.tld/domain.tld/ where domain.tld is my test-server's domain.

Naturally, this results in a 404 since I don't have a template to render a matching URL.

Any idea how to fix this or what could be causing it?

Thanks!


texts: Randomly listing entries in more then one section

texts:
I have created 12 sponsorship ads for my website using a “sponsor” category.

On my home page I have four sponsorship sections, each holding three sponsorship ads.

How can I randomly distribute those 12 sponsorship ads among the four sponsorship areas with each homepage load?


texts: How do I set my siteURL instead of having http://localhost:8888/?

texts:
I downloaded and installed Craft Personal on my computer and choose /websitetest/ as my website name. I used MAMP and phpMyAdmin to create a database.

Still to access my website the url is http://localhost:8888/ and when I try to access http://localhost/websitetest/ I get the following error message: Forbidden
You don't have permission to access /websitetest/ on this server.

Moreover in my index.html file, when I call for an URL entry:

href="{{ entry.url }}"

by default it redirects towards /websitetest/_entry , which displays me the same error message, while localhost:8888/_entry works when I test it manually!

Some ideas where can this come from?

Thanks!


texts: Can I open templates/routes other than 503 when Craft is offline?

texts:
I've set Craft offline (System status). Is it possible to "open" URL routes so it can be accessed even though the website is offline? Right now every request gets routed to my 503.html page.

For example the routes: /impressum and /about


texts: Recommended CPU/RAM VPS settings to query 50,000 entries

texts:
I'm running a very simple query on a text field...

{% set query = craft.request.getQuery('email') %}

Locally, with one entry on my machine, I'm getting a response time of 332ms. We were assuming around 3,000 total entries, but 3 days in, I'm at 15,000 and climbing by hundreds per hour.

What would be a good starting point for CPU/RAM on a VPS if I assume that we could hit 50,000?


texts: What is the correct way to attribute FreeForm submissions to users?

texts:
I'm using FreeForm and need to create a relationship between form submissions and the user that submitted them.

To accomplish this I created a hidden variable on my form called userId.  I use overridesValues to set the userId to the current user before I render the form.  This "feels" wrong to me .. is there a better way to do this?   Is this userId already stored in the freemform data model (making what I'm doing uncessesary)?

{% requireLogin %} {#check user is logged in #}
{{ craft.freeform.form("employeeForm", {
  overrideValues: {
    userId: currentUser.id,
  }
}).render() }}


texts: Checking permission for editing entries from inside template

texts:
How do I check permission for editing entries belonging to a specific section?

When I try {{currentUser.can('editEntries:'~entry.sectionId) }}, it returns false - and I am sure that currentUser can edit entries from this section.

edit:
Its craft 3.1


texts:
I would like to be able to save multiple records at once. What is the best way of doing this? I can of course iterate over my records and use the save function for each one. However, this is not very good for performance. The other option I can think of is to create my own database query using the insertAll command. This would be better for performance.

Is there any built in function to batch save multiple records at once or is the insertAll alternative the way to go?

Thanks for your time.


texts: Composer Error Updating Craft CMS 3 from RC13 to 14/15

texts:
PHP 7.0.28 / MySQL 5.6.38 / Craft Pro 3.0.0-RC13

While trying to update I get this error:

Error: An error occurred

Output: Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package codeception/codeception could not be found in any version, there may be a typo in the package name.
Problem 2
- The requested package codeception/mockery-module could not be found in any version, there may be a typo in the package name.
Problem 3
- The requested package codeception/specify could not be found in any version, there may be a typo in the package name.
Problem 4
- The requested package codeception/verify could not be found in any version, there may be a typo in the package name.

Potential causes:
- A typo in the package name
- The package is not available in a stable-enough version according to your minimum-stability setting
see for more details.
- It's a private package and you forgot to add a custom repository to find it

Read for further common problems.
Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.

My composer.json file:

{
  "name": "craftcms/cms",
  "description": "Craft CMS",
  "version": "3.0.0-RC13",
  "keywords": [
    "cms",
    "craftcms",
    "yii2"
  ],
  "homepage": "https://craftcms.com",
  "license": "proprietary",
  "support": {
    "email": "support@craftcms.com",
    "issues": "https://github.com/craftcms/cms/issues?state=open",
    "forum": "https://craftcms.stackexchange.com/",
    "source": "https://github.com/craftcms/cms",
    "docs": "https://github.com/craftcms/docs",
    "rss": "https://github.com/craftcms/cms/releases.atom"
  },
  "require": {
    "php": ">=7.0.0",
    "ext-curl": "*",
    "ext-dom": "*",
    "ext-json": "*",
    "ext-mbstring": "*",
    "ext-openssl": "*",
    "ext-pcre": "*",
    "ext-pdo": "*",
    "ext-zip": "*",
    "composer/composer": "~1.5.2",
    "craftcms/oauth2-craftid": "~1.0.0",
    "craftcms/plugin-installer": "~1.5.0",
    "craftcms/server-check": "~1.1.0",
    "creocoder/yii2-nested-sets": "~0.9.0",
    "danielstjules/stringy": "~3.1.0",
    "elvanto/litemoji": "^1.3.1",
    "enshrined/svg-sanitize": "~0.8.2",
    "guzzlehttp/guzzle": "~6.3.0",
    "league/flysystem": "~1.0.35",
    "league/oauth2-client": "~2.2.1",
    "mikehaertl/php-shellcommand": "~1.2.5",
    "pixelandtonic/imagine": "~0.7.1.2",
    "seld/cli-prompt": "~1.0.3",
    "twig/twig": "~2.4.4",
    "yiisoft/yii2": "~2.0.14.2",
    "yiisoft/yii2-debug": "~2.0.10",
    "yiisoft/yii2-swiftmailer": "~2.1.0",
    "yiisoft/yii2-queue": "~2.0.1",
    "zendframework/zend-feed": "~2.8.0",
    "craftcms/cms": "3.0.0-RC15",
    "bugsnag/bugsnag": "v3.9.0",
    "craftcms/redactor": "1.0.1",
    "dolphiq/redirect": "1.0.15",
    "nystudio107/craft-cookies": "1.1.9",
    "superbig/craft3-bugsnag": "2.0.0",
    "superbig/craft3-templateselect": "2.0.0",
    "topshelfcraft/supersort": "3.0.1"
  },
  "require-dev": {
    "codeception/codeception": "~2.3.3",
    "codeception/mockery-module": "~0.2.2",
    "codeception/specify": "~0.4.6",
    "codeception/verify": "~0.3.3"
  },
  "provide": {
    "bower-asset/bootstrap": "3.3.* | 3.2.* | 3.1.*",
    "bower-asset/jquery": "3.2.*@stable | 3.1.*@stable | 2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable",
    "bower-asset/inputmask": "~3.2.2 | ~3.3.5",
    "bower-asset/punycode": "1.3.*",
    "bower-asset/yii2-pjax": "~2.0.1"
  },
  "suggest": {
    "ext-imagick": "Adds support for more image processing formats and options.",
    "ext-iconv": "Adds support for more character encodings than PHP’s built-in mb_convert_encoding() function, which Craft will take advantage of when converting strings to UTF-8.",
    "ext-intl": "Adds rich internationalization support."
  },
  "autoload": {
    "psr-4": {
      "craft\\": "src/"
    }
  }
}


texts:
I'm new to Craft template development and one of the first things I'm trying to do is create a Variable that renders a template into the template its called from.

My directory structure looks like this:

/craft
  /plugins
    /test
      /templates
        _headers.html
      /variables
        TestVariable.php

Here is the Variable:

<?php

namespace Craft;

class TestVariable
{
    /**
     * Get header for test code
     *
     * @return string
     */
    public function headers()
    {
        return craft()->templates->render('test/_headers');
    }
}

And I'm calling it in the template with a simple: {{ craft.test.headers }}

My template is erroring with Unable to find the template “test/_headers”.

What am I misunderstanding here?


texts: Admin resources are accessible without being logged in

texts:
Should the /admin/resources/assetthumbs/{assetid}/200 be accessible without being logged in?

I’ve just noticed I can access thumbnails that way, and with some fiddling even let it generate huge images for me

This is on v2.6.3002.


texts: How to reference controller action from hidden action? Correct path?

texts:
I have seen a number of different paths, but, it is a bit confusing to me. What should be in my value in the HIDDEN input action below?

I have a twig page at my root:

<form method="post" action="" accept-charset="UTF-8">
    <input type="hidden" name="action" value="psychEmail/pubRequest">

    <!-- ...-->

    <input class="btn submit" type="submit" value="{{ 'Submit'|t }}">
</form>

and then I have a plugin PsychEmailPlugin.php class file with
class PsychEmailPlugin extends BasePlugin

and then I have a controllers subdirectory with a PsychEmailController.php file that contains an action:

class PsychEmailController extends BaseController
{
    public function actionPubRequest($emailAddress)
    {
        $email = new EmailModel();
        $email->fromEmail = $emailAddress;
        $email->toEmail = 'myemail@gmail.com';
        $email->subject = 'Publication Request';
        $email->body    = 'Your requested publication is attached.';

        craft()->email->sendEmail($email);
    }
}


texts: How to temporarily disable entries of one site version within a site group?

texts:
A client asked me to temporarily disabled all of its entries of one of its Site in a specific language. This entries should not be accessible anymore from their URL.
The quickest and cleanest way to hide them would be to delete this Site version, but this would result in deleting all related entries.
As far as I know, the only way to hide them temporarily is to visit each Entry, then disabled the Enabled for site option, and after that make some changes in menu template to hide this Site version.
As there's a very large number of Entries, this will be very  time consuming. Is there any cleaner or faster way to do that?


texts: How can I call a controller method from the front-end using ajax

texts:
I would like to call an action method from within my plugin via ajax but I am always getting a 404 response.

I have a controller method that matches the ajax url:

jquery

$.ajax({
    'type': 'post',
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cache': false,
    'data': data,
    'url': 'pluginHandle/checkStatus',
    'dataType': 'json',
    'timeout': 50000
}).done(function (response) {
    // Success
}).fail(function (error) {
   // Total fail.
});

MyPluginController.php

...

/**
 * Checks what the current status is RIGHT. NOW.
 *
 * @throws HttpException
 *
 */
public function actionCheckStatus()
{
    $this->requireAjaxRequest();

    $response = [
        'status' => 'open'
    ];

    $this->returnJson($response);
}

...

What am I doing wrong?


texts: Commerce 2: View all orders of a specific product?

texts:
I'm looking to generate a sales report for a specific product

It should not be linked to a user's orders but just a general list of sales for that product and its variants

Is this possible?

Thanks


texts: How can I set an entires status via ajax from a front-end form?

texts:
I am trying to set an entires status to disabled from a front-end form.

Here is the click event listener I am using:

$(document).on('click', '.delete', function (event) {
    let $this = $(event.currentTarget);
    let verify = confirm("Are you sure you want to remove this?");

    if (verify) {
        let params = {
            'entryId': $this.data('id'),
            'sectionId': $this.data('section'),
            'enabled': 0
        };

        // append CSRF token.
        params[window.csrfTokenName] = window.csrfTokenValue;

        onSetEntryStatus(params, function (res) {
            console.log(res);
        });
    } else {
        console.log('do nothing');
    }

    event.preventDefault();
});

Here is my ajax method:

function onSetEntryStatus(data, callback) {
    $.ajax({
        type: 'post',
        contentType: 'application/json; charset=UTF-8',
        cache: false,
        data: data,
        url: '/actions/entries/save-entry',
        processData: false,
        dataType: 'json',
        timeout: 50000
    }).done(function (response) {
        console.log('response', response);
    }).fail(function (error) {
        // Total fail.
    });
}

(also tried posting to actions/entries/save-entry)

Request payload is coming across as: [object Object] so clearly I'm having a brain-fart moment there.

Everything I have commented out, are things that i've seen in the console when setting the status from the CP. Currently, I am getting a 403 error back. I am able to verify that I am passing in the csrf token, so I am guessing it is because of the (incorrect) way I am sending data.

Grateful for any suggestions!

EDIT

When logging out what params I'm sending to the ajax method:

enabled: 0
entryId: 1465
sectionId: 5
_token: 'really-long-string'


texts: How can I search for Craft Commerce orders with a specific product?

texts: Is it possible to narrow the order query from the default order listview in the CP from Craft Commerce? Because I’ll want to show all orders with a specific product so I can export them.


texts: Query entries from two sections, check date field for one section and include pagination

texts:
I'm having a page that shows entries from two sections: news and events.

The page has the following layout:

All current event entries

Current event entry 1
Current event entry 2

All upcoming event entries

Upcoming event entry 1
Upcoming event entry 2

All news entries and all past event entries combined including pagination

News entry 1
Past event entry 2
Past event entry 3
News entry 4
News entry 5
Past event entry 6

To query the current events i use the following query

{% set entries = craft.entries()
  .section('events')
  .startDate('<= ' ~ now|date('c'))
  .endDate('>= ' ~ now|date('c'))
  .orderBy('startDate asc')
  .all()
%}

To query the upcoming events i use the following query

{% set entries = craft.entries()
  .section('events')
  .startDate('> ' ~ now|date('c'))
  .orderBy('startDate asc')
  .all()
%}

I have no idea how to query all the news and past event entries.

The query should include:

Query all entries from section news
Query all events from section events where entry.endDate < now
Sort all entries by post date
Limit to 9 and include pagination

I came this far with the query:

{% paginate craft.entries()
  .section(['events','news'])
  .limit(9)
  .orderBy('postDate asc')
  as pageInfo, pageEntries
%}

What is missing: checking the event entries to see if the endDate < now.

I can't just add .endDate('< ' ~ now|date('c')) to the query. That would hide all the news entries, ofcourse.

I did search and read a lot of posts on stackexchange. Couldn't find a solution.

Anyone that could help me with this?


texts: How do I display the index of the asset in assets loop?

texts:
Looking to do something like this:

{% for image in block.images %}
    <img src="{{ image.url }}" data-index="{{ image.index }}">
{% endfor %}

This seems like it should be easy and I feel like I've done it before, however I can't seem to figure it out. Thanks


texts: Multi-language, how Craft determines the CopyFrom after adding website and Section

texts:
The question is admin (backend only), not Twig :

Where to Manage "copy from" site when adding new website and add section to this website. The "Copyfrom" takes place in the background after activating the section.

When adding a new (multilanguage) website and setting the section to that language it copies data to this new website or language.
I did a test and exported the "content" table as csv to see what happens.

When adding a new website, it copys the structure to that language  (more lines in csv)
When activating a section on the new website it copies the content to that language (more lines in csv from that section)Looks logical so far....But "What" determens the "copyFrom" content ?Introducing a new language now copies always "German" content.I really want to choose that part (when adding the Sections).

This is the structure in websites:

website.at  websiteAt   de-AT    https://website.at/        website.eu
website.com websiteCom  en-US    http://website-comdev.nl/  website.eu
website.de  websiteDe   de-DE    https://website.de/        website.eu
website.eu  websiteEu   en     V https://website.eu/        website.eu
website.fr  websiteFr   fr       https://website.fr/        website.eu
website.nl  websiteNl   nl-NL    https://website.nl/        website.eu
website.sk  websiteSk   sk-SK    https://www.website.sk/    website.eu

Example:  If i add website.zz and activate the section, the content is filled with german content (? maybe the first in the list). I want to manage the copyFrom and now we don't know wich default content is taken by introducing a new website/language.


texts: "Unknown package has no name defined" composer error on upgrade

texts:
Upgrading from Craft 3.4.20 running Composer 1.10.17 on PHP 7.2. Running ./craft update all returns the following error:
error: Unknown package has no name defined. [followed by JSON object related to GuzzleHTTP]

The error appears to be related to GuzzleHTTP. For testing I did the following:

Deleted the /vendor directory.
Deleted the composer.lock file.
Removed all composer.json dependencies except craftcms/cms, vlucas/phpdotenv and ext-json.
Ran composer install.
Ran ./craft update all.

Yielded same error.
Unfortunately, I am unable to find any information about this error from Composer documentation or bug reports.


texts: How do you apply a sale/discount to digital products?

texts:
When using the digital products plugin, is there a way to apply a sale or discount to these products?

This answer mentions a digital product only has a price property and not a salePrice property. Does that mean that it is impossible for a digital product to have some sort of discounted price?


texts: I am pulling in a feed I know that has two items. When I add caching to craft.feeds.getFeedItems(feedurl, limit, cache) the first items is not pulled in.  However if I remove caching or add "0" that item is pulled in. Would this have something to do with the feed or craft?


texts: What's the difference between "is defined" and "is not null"?

texts:
{% if var is defined %}

and

{% if var is not null %}

Is there a difference in usage of them?


texts: Advanced filtered search: Matrix fields and arrays

texts:
Having scoured the forums for similar questions of which there are a few, I'm still struggling to figure out my specific usecase. I have 4 filters and a search box (which searches a custom tag field) to filter craft.users in a group. 3 of the filters are matrix fields, 2 of the filters are posted as an array.

Gender seems to be working fine:

The first option’s gender value is empty “”, which seems to work and return both genders if selected. Is this fine, or should I be checking if a value has been posted? And if so, would I need to use a ternary operator to set a default array for both male and female values?

How do I add a Matrix field into the craft.users object syntax?

Is this even possible? I can imagine setting something like maxPrice: "<= #{maxPrice}" for a standard number field, but have no idea how I'd do so for a number field within a Matrix block:

i.e. craft.users.profilePricing.type('details').session

I'm using matrix fields as they separate related chunks of data better, the specific ones I need to search are limited to number fields, dropdown and checkboxes. All of which only allow 1 block. For now at least, the filters should match all criteria with and logic.

Filters

Here is an example of the filter options:

<select name="gender">
  <option value="">Male and female</option>
  <option value="male">Male</option>
  <option value="female">Female</option>
</select>

  <input id="maxPrice" type="number" name="maxPrice" min="0" max="100" step="5">
  Maximum session price

    <input type="checkbox" value="skype" name="sessions[]" checked> Skype

    <input type="checkbox" value="chat" name="sessions[]" checked> Live web chat

    <input type="checkbox" value="phone" name="sessions[]" checked> Telephone

    <input type="checkbox" value="email" name="sessions[]" checked> Email

    <input type="checkbox" value="office" name="hours[]" checked> Office hours

    <input type="checkbox" value="overtime" name="hours[]" checked> Out of hours

    <input type="checkbox" value="weekends" name="hours[]" checked> Weekends

Results

And the unfinished code for the search results:

Search Results

{% set tags = craft.request.getParam('tags') %}
{% set gender = craft.request.getParam('gender') %}
{% set maxPrice = craft.request.getParam('maxPrice') %}
{% set sessions = craft.request.getParam('sessions') %}
{% set hours = craft.request.getParam('hours') %}

{% set results = craft.users({
  group: 'verified',
  search: "tagsSpecialismSearchable:#{tags}",
  gender: gender,
}) %}

{% set users = shuffle(results) %}

{% if users|length %}

{{ users|length }} results:

  {% include '_includes/counsellors/profile.html' %}
{% else %}

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

{% endif %}


texts: How can I rename an asset file on upload when an entry is saved (Craft 3)?

texts:
I have an entry type that includes an Assets field. When this entry is created/saved via the CP or a front-end form, I want to rename the Asset file as follows:

Entry's author id. E.g: 148
01, 02, 03 based on how many entries the author has already submitted.

So files would look like: 148-01.jpg 148-02.jpg, 148-03.jpg.

At some point, I would also like to add the value of a custom field.

Also, I would like to limit this to entry for a certain type in a certain section: Section name: "Competitions", Entry type: "Submission".

Screenshot: https://cl.ly/a526f40c6d58

So far In my Craft 3 Module I have this. I can get the Asset id, but I can't get the Entry's Author Id:

Event::on(
    Elements::class,
    Elements::EVENT_AFTER_SAVE_ELEMENT,
    function (ElementEvent $event) {
        $asset = $event->element;
        $id = $event->element->getId();
        if ($event->isNew && $asset instanceof craft\elements\Asset) {
            $newFileName = "new-file-name-" . $id . ".jpg";
            Craft::$app->assets->moveAsset($asset, $asset->getFolder(), $newFileName);
        }
    }
);

I found this answer https://craftcms.stackexchange.com/a/13199/298, but it's for Craft 2:

craft()->on('entries.beforeSaveEntry', function(Event $event)
{
    $entry = $event->params['entry'];

    if (($entry->section['handle'] == 'friends') && ($entry->type['handle'] == 'friends'))
    {
        $title = $entry->slug;
        $assets = $entry->imgdir;

        if (count($assets) != 1)
        {
            $event->params['entry']->addError('imgdir', Craft::t('Exactly 1 asset has to be selected.'));
            $event->performAction = false;
        }
        else
        {
            $filename = $title.'.'.$assets[0]->getExtension();

            craft()->assets->renameFile($assets[0], $filename);
            craft()->assets->storeFile($assets[0]);
        }
    }
});

How can I do this in Craft 3?


texts:
I created a simplistic Console Command class in my plugin folder containing this function:

public function actionTest () {
    craft()->templates->renderString('index');
}

When I run the command:

./yiic < plugin > Test

I get the follwing error message:

Property "Craft\ConsoleApp.session" is not defined.
exception 'CException' with message 'Property "Craft\ConsoleApp.session" is not defined.' in /Users/< username >/Sites/< project >/craft/app/framework/base/CComponent.php:130

Thoughts? The end goal here is to be able to render HTML emails and them at specific intervals, but for some reason when using craft services, I get session errors.


texts:
I wrote a PHP script to deploy data to live-cdn and included a "deploy" button on the dashboard. the script returns ?success=true, and i need to show div element with "Congratulations"

i tried this with no success:

{% if app.request.query.get('success') %}
  <div>
    Glückwunsch! Deployment läuft.
  </div>
{% endif %}


texts: Avoiding initial load for image transform

texts:
I'm using the element API to get the url of an asset from angular with:

'image' => $entry->playerImage->first()->getUrl("square"),

Problem is until i visit that image in the browser the url doesn't work, does someone know of a nice way of dealing with this?


texts: Fetching "Pending" Users Related To Entry Within Plugin

texts:
This works (but only obtains the active users):

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

// get existing users in field
$entry->customUserField->ids();

So in attempting to get the non-active users I've switched to using the ElementCriteriaModel but have been unsuccessful:

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

// get field model
$field = craft()->fields->getFieldByHandle('customUserField');

// get all users for entry+field
$getUsers = craft()->elements->getCriteria(ElementType::User);
$getUsers->relatedTo([
    'targetElement' => $entry,
    'field' => $field,
    'status' => null  // user status null
]);

$users = $getUsers->find();

I'm certain I'm doing something wrong within my relatedTo parameters. Help!


texts:
I’m on Craft v. 2.6.2983 and am encountering the well flagged issue of the control panel logging me out after 60 seconds. I've tried most of the solutions posted here and have had no success in resolving the issue.

We're three months into a Craft deploy this issue has only begun to arise in the last number of weeks.

I’m using redis for session storage and my sessions are remembered when I refresh or open a new tab. Using redis-cli monitor I can see sessions are being stored with the correct TTL.

I've set the following in my config/general.php:

'appId' => 'itmaapp123',
'defaultCookieDomain' => '.itma.ie',
'validationKey' => [REDACTED],
'overridePhpSessionLocation' => 'tcp://redis:6379',
'cacheMethod' => 'redis',
'userSessionDuration' => false

I've also set the relevant variables in config/rediscache.php (including timeout => 300).

Any insights on what might be causing the issue? My stack is Craft 2.6.2983 on nginx with php7.0-fpm and redis for session storage. nginx, php and redis are all running in docker containers behind an nginx reverse proxy. I'm using Cloudflare with SSL for cache and CDN.

Any help much appreciated.


texts: Dealing with existing data in a separate database

texts:
I'm creating a site with Craft that needs to communicate with an existing database, which is separate from the database Craft will be installed on. My client is already using an existing online database to manage a bunch of their internal work, but I need to fetch some of that data for public display on the site. I don't need any relational queries between the two databases, so it's fine that they're separate.

My plan is to create a plugin that will create a new Record. Because BaseRecord extends Yii's CActiveRecord class, I should be able to override the getDbConnection() method to return a new CDbConnection object, which will connect to the external database.

So my first question is: Will that work, in theory? Or will Craft try to use my site's table prefix in this external database (which wouldn't work)?

My second concern is that Craft will associate the table returned by getTableName() in my new record as a table specific to this plugin, and will delete that table if the plugin ever gets uninstalled. Obviously since I'm dealing with an external database, I don't want that to happen. Is there any way around that?

EDIT:

I just came across this question: Query table in a different database, and the solution there seems like it's a simpler option for me. I am still interested in learning the answers to my above questions though.


texts: Element API unable to get all() of matrix field

texts:
I'm getting matrix block content from an entry type which works fine for the most part. It's probably clearer to just paste in the code:

Current element api code:

$relationsData = [];
if($entry->relatedContent){
    $index = -1;
    foreach ($entry->relatedContent->all() as $block) {
        switch ($block->type->handle) {
            case 'relateContent':
                $index++;
                $relatedFeaturedEntries =  $block->featured->first();
                $relatedSubEntries =  $block->related->first();
                $relationsData[$index] = [
                    'title' => $relatedFeaturedEntries->title,
                    'url' => $relatedFeaturedEntries->url
                ];
                $relationsData[$index]['subItems'] = [];
                $relationsData[$index]['subItems'][] = [
                    'title' => $relatedSubEntries->title,
                    'url' => $relatedSubEntries->url
                ];
            break;
        }
    }
}

Which outputs:

      "relations": [
        {
          "title": "Testing workflow",
          "url": "http://localhost/blah",
          "subItems": [
            {
              "title": "Help & Guidance",
              "url": "http://localhost/help-guidance"
            }
          ]
        },
        {
          "title": "Taking part in the blah",
          "url": "http://localhost/blah",
          "subItems": [
            {
              "title": "blah timeline",
              "url": "http://localhost/blah"
            }
          ]
        },
        {
          "title": "Testing workflow",
          "url": "http://localhost/blah",
          "subItems": [
            {
              "title": "Completing on paper",
              "url": "http://localhost/blah"
            }
          ]
        }
      ],

There should be more subItems in each subItems array but I am only getting the first because I'm fetching them using $relatedSubEntries =  $block->related->first(); But nothing else works and just errors i.e. all() or removing first()


texts: CBdException: Column 'id' cannot be null

texts:
I receive the following error only when I clear the cache:

When I try to rebuild the image index, all of my image paths go missing.
I'm not sure what caused this error but I do need to fix it.

I've checked my image transforms and everything is named correctly. I even tried to delete and re-add and still nothing. I'm getting this same error on another one of my craft sites when I empty the cache.

I have no idea what's causing it.

I did come across this post:
CDbException: Column not found

I read through the comments but no solution has been posted. I did a db search for CONSTRAINT or FOREIGN KEY and have both.

Any and all help is appreciated.
Thanks in advance.

UPDATE!!!

Things I tested and found:

I looked at the assettransformindex in the database and it was empty.

I ran an INSERT statement to populate the rows with proper information - it inserted successfully.
I refreshed the site, the CBd exception was gone.

I cleared the cache, minus the image transform index and the site still worked perfectly.

I cleared the cache with image transform index selected and it stripped everything from the DB.

If I try to upload an asset that uses the transform, it throws the CBd exception again and clears the DB.

I hope this information helps...
Thank you in advance.


texts:
public function init()
{
    craft()->on('assets.onBeforeSaveAsset', function(Event $event) {
        $asset = $event->params['asset'];
        $asset->setAttribute('filename', 'new name');
        craft()->assets->storeFile($asset);
    }
    );
}

Here is the code I use in the primary plugin class. This is just a test as i'm learning. I know it should better be in service.
This is supposed to change the filename upon uploading.

Anyway this does nothing, when I upload an asset in the cp, the dialog with progress bars pops up but get stuck.
How should I modify this for it to work ?


texts: How can I restrict tags that are able to be used?

texts:
Just downloaded and am setting up Craft. Super excited! I would like to know the following:

At the moment, I am assigning tags to entries in the hopes of using them as an organizational/navigation tool at some point in the future. My question is, how—if at all—can I create a list of tags that can be used IN ADVANCE? In other words, restrict the possible tags that can be assigned to now and future entries?

So, the admin can only choose/use: "branding", "design", and "identity", for example. And not "copywriting." Thanks in advance!


texts: Why am I getting "Variable "entry" does not exist"

texts:
This seems random to me, as it was not a problem until today...

I am getting the template error Variable "entry" does not exist with a reference to line06 below.

This is a template for social icons that I include on each page.

The code template below is included in my site template.  It works on the index page, but it works no where else other than an actual entry (post) page.


texts: AJAX user registration and JSON returned

texts:
I am using business logic plugin to tap into save user event and create some profile field values.

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

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

    }
}

On save user returns a success object.
I want to return more user profile data to the page on success.

In the save User function I have tried:

 if (craft()->request->isAjaxRequest())
 {
     $return = array(
         'success' => true,
         'errorCode' => 1,
         'uid' => $user->id,
         'urn' => $URN
     );

     return json_encode($return);
 }

but I still get the usual response of success and user id.
How do i get a thank you 'page' into the process so I can feedback to the user?


texts: How do I exclude a Channel, Structure or Singles from search?

texts:
I'm trying to figure out how to exclude a Channel, Structure or Singles from my search results.

Currently I have the default example from Craft

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


texts: How do I validate an array model attribute against a set of possible values?

texts:
I have a need to set a property on a plugin Model that is an array of one or more valid values.

I can see that I can use AttributeType::Enum and record and define a set of values but if I'm not mistaken, that enables me to validate a single value against that set of values:

class MyModel extends BaseModel
{
    protected function defineAttributes()
    {
        return [
            'mySetting' => [ AttributeType::Enum, 'values' => 'validOption1,validOption2,validOption3' ]
        ];
     }
}

What I want to do is enable mySetting to be an array that would be valid when set as an array containing any combination of the defined options:

MyModel::populateModel(['mySetting' => [
    'validOption1'
]]); // is valid

MyModel::populateModel(['mySetting' => [
    'validOption1',
    'validOption3'
]]); // is valid

MyModel::populateModel(['mySetting' => [
    'invalidOption',
    'validOption3'
]]); // is *not* valid

MyModel::populateModel(['mySetting' => []); // is *not* valid

Etc.


texts: How do I loop through and access all sections of returned entries?

texts:
On my search results page I want to add a section filter depending on the different sections that are included in all of the returned entries.

I am getting all the sections like this:

{% set entries = craft.entries.section(['inspirationArticles', 'pages', 'pressArticles', 'products']).search(searchQuery).order('score') %}
{% set entrySections = entries.getAllSections() %}

And then loop through them:

{% for entrySection in entrySections %}
...
{% endfor %}

But when trying to access the sections’s names or handles via {{ entrySection.name }} or {{ entrySection.handle }}, I get a CException error:

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

So it looks like it isn't actually accessing the SectionModel. Am I missing a step?


texts:
Have kind of a weird problem going on with my site, which I just moved over from my staging server to production. Originally, everything looked fine, except I couldn't get into the Admin Panel. I discovered that I had an old .htaccess file in my root directory, and once I replaced that with the Craft CMS one, I was able to login just fine. Now, however, I've noticed that while most of the options on the left (Assets, Entries, Categories, etc) work as expected, if I select Settings, I'm greeted by a blank page. Any ideas?

My previous question as mentioned.


texts: API endpoint to show/add/modify/delete content

texts: I would like to access and modify certain entries using asynchronous calls from a custom made webapp using React which is complementary to the main website. Is there any way to achieve this in Craft CMS?


texts: How to use an asset as featured image in different entries

texts:
I have currently the problem, that I can't use the same asset in different entries as featured image.

Craft Pro Version: 3.0.9

My setup is the following:

Volumes:

Local, Base URL: @web/uploads, Type: Local, File Path: @webroot/uploads

Created Fields:

Featured Image, Type: Asset, Limit: 1, Volume: Local

Created Section:

Articles, Type Channel, Added Featured Image to the post type

Now I have uploaded some dummy images. (e.g. Image 1, Image 2, Image 3)
After this I have created some article entries.

Article 1 - Image 1
Article 2 - Image 2
Article 3 - Image 3

Backend Preview:

Frontend Preview:

When I change the Article 1 - Featured Image from Image 1 to Image 2 it looks good in the backend but not in the frontend.

Backend Preview:

Frontend Preview:

The frontend snippet to show the entries is the following:

{% set latestArticles = craft.entries({section: 'articles', limit: 6}).orderBy('id desc').all() %}

    {% for entry in latestArticles %}

        {% set asset = entry.featuredImage.one() %}

{{ entry.title }}

                        {{ entry.teaser|length > 200 ? entry.teaser|striptags|slice(0, 200) ~ '...' : entry.teaser|striptags }}

                            Read more...

                        9 mins

    {% endfor %}

The question is now the following:

Is it an user handling?! :D
Is it not possible to assign one image to multiple entries?
Is there any workaround? (please don't tell me, to upload the image again ;) )

Thanks!


texts: Class 'Craft\ErrorHandler' not found in YiiBase.php after new Thread-Safe PHP install

texts:
I've just upgraded PHP 7.0 on a standard Ubuntu Server 16.04 LTS distro from non-thread safe to thread safe (using Michel Phillipe Luca's instructions here: http://php.net/manual/de/pthreads.installation.php).

I had a CLI method set up which was working perfectly fine, but after installing the thread-safe version of PHP (with no changes to the code), when I try to run ./craft/app/etc/console/yiic plugin method I get the following error:

Fatal error: Uncaught Error: Class 'Craft\ErrorHandler' not found in /var/www/asmar/subdomains/site/craft/app/framework/YiiBase.php:213
Stack trace:
#0 /var/www/asmar/subdomains/site/craft/app/framework/base/CModule.php(393): YiiBase::createComponent(Array)
#1 /var/www/asmar/subdomains/site/craft/app/etc/console/ConsoleApp.php(220): CModule->getComponent('errorHandler', true)
#2 /var/www/asmar/subdomains/site/craft/app/framework/base/CApplication.php(468): Craft\ConsoleApp->getComponent('errorHandler')
#3 /var/www/asmar/subdomains/site/craft/app/framework/base/CApplication.php(749): CApplication->getErrorHandler()
#4 [internal function]: CApplication->handleException(Object(Error))
#5 {main}
  thrown in /var/www/asmar/subdomains/site/craft/app/framework/YiiBase.php on line 213

Any ideas how I may squash this?


texts:
I have set up a Matrix field that contains a block type that contains among other things, an asset field.
Trying to iterate through the contents of that matrix field works just fine for all other field types but produces the following error when it comes across the asset field type.

  Object of class Craft\ElementCriteriaModel could not be converted to string

This is the part of the template that produces the error. "icon" is the asset field type.

{% for block in entry.visitorContentBuilder %}

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

        {{ block.icon }}

    {% endif %}

{% endfor %}


texts: How do I push contact form data to SugarCRM? (currently using Sprout Forms)

texts:
SugarCRM has a REST API, and Craft boasts its ability to integrate with almost anything that has an API; however, I am working on a site that uses Sprout Forms, which doesn't mention anything in their docs about integration.

Is there a way, in addition to emails and saved entries, for Craft to push Sprout Form data to SugarCRM?

If this isn't possible, if there another contact form solution that will integrate this way?


texts: Issue Importing Data to Matrix Fields With FeedMe Plugin

texts:
I am migrating content from a drupal site into Craft CMS. I am trying to using the FeedMe Plugin to do this.

Right now I'm working with a single test XML file to make sure my fields and setup are correct before I do the bulk import. However, my xml only ever creates the first matrix block. There is no limit to the number of blocks a user can include in the matrix block field I'm importing to.

The entry I am migrating content into has three tabs for fields. The main tab consists of the title and a matrix block. The third tab has a third party field "Legacy URL" from the Retour Craft CMS Plugin.

My XML looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<node_export created="Mon, 02 Oct 2017 00:15:47 -0400">
    <node>
        <title>Celebrating J Day</title>
        <nid>862</nid>
        <post_date>2017-09-22T00:00:00</post_date>
        <summary>A super summary.</summary>
        <storyBlock>
            <image>
                <image>http://website.com/path/to/my/image.png</image>
                <position>center</position>
            </image>
            <text>
                <text>Some awesome text is here.</text>
            </text>
        </storyBlock>
    </node>
</node_export>

My FeedMe field mapping looks like this:

The title, post_date, summary, and image matrix block all get imported properly. However, the text block and the nid into the legacy url field are not being imported.

The versions of everything:
FeedMe 2.0.7
Craft CMS 2.6.2991
PHP 7
MySQL 5.7

Does it look like I've set something up incorrectly? Any advice on how I can get this running correctly?

If any of the above is unclear, or if there is additional information I can provide, please let me know. I really appreciate your time and support!


texts: Give Access to Freeform (Solspace) Submission Answers to a tierce person

texts:
I implemented a form on a website using the Freeform Plugin (by Solspace) and I would like another company to have access to the results of this form.

I am thinking of using the bootstrap demo to display the submissions, but to access it one has to be connected to the Craft Account:

{% if currentUser and currentUser.admin %}

How can I create an authentication system but only for the Submission Page?

Thanks!


texts: Craft Pro 3.1.33 - Download PDF in admin user profile

texts:
In Craft 3 Pro i need to download a PDF file that a template form submits to active user profile.

The PDF submits from the front and goes to the admin area under the user account profile.

The problem is that in the user account profile i can see the PDF but cannot download it or even preview it (shows a white thumbnail image with PDF written).

The only way i find to download the pdf is going to the assets section and find it among the other file assets. I do not want this.

Is there a way of adding a download button, or click in the pdf preview to download the pdf, in the user account profile in craft 3 admin backoffice?


texts: I'm setting up a Craft site on a Linode server has anyone had any experience with this? I'm struggling with which owner and user to set the var/www/html folder to with chown and what chmod settings to use on the craft folders. Currently Craft does not show the index page and can't find the admin folder which are all where they are supposed to be so it seems to be something to do with apache permissions. Just wondered if anyone could advise what these should be?


texts: FeedMe - Extracting attribute from an RSS feed field

texts:
So I'm using FeedMe to get RSS atom feeds and this is working O.K. But there's this field that has an attribute I want to extract. And I cannot get this to work.

In the FeedMe documentation it says:

For example, the XML <field my_attribute="Some Value">Another Value</field>,
you can use {{ xml.field.attributes.my_attribute }}.

My field is called 'enclosure' and has an attribute called 'url' that I want to extract. According to the documentation, one would assume that this should work:

{% set feed = craft.feedme.feed(myfeed_rss) %}

{% for node in feed %}

    {
        'title': {{ node.title | raw }},
        'description': {{ node.description | raw }},
        'url': {{ node.link | raw }},
        'date': {{ node.pubdate | raw }},
        'image': {{ node.enclosure.attributes.url | raw }}
    }

{% endfor %}

Namely {{ node.enclosure.attributes.url }} should work? All the other fields are collected correctly. So it's just this one.

Edit: Btw, the feed I'm using is this one.
http://www.adressa.no/?widgetName=polarisFeeds&widgetId=3185248&getXmlFeed=true

Edit2: Managed to get it to work, with help from crafw. Some of the nodes weren't empty, fixed it by changing the line to:

{{ node.enclosure.attributes.url|default('empty') }}

https://craftcms.stackexchange.com/users/632/crawf


texts: Is it possible to take an excerpt from the first rich text area in a matrix?

texts:
I have blog articles set up on the site i'm working on to be built using a matrix, much the same way as in the features video about the matrix field. So it is entirely possible for an article to start with an image or a video.

What i'd like to be able to do is find the first text entry in the matrix and pull the first 155 characters out of it, creating an excerpt. The point of this is to pass that into a meta og:description tag (and i guess meta description too!)

Is it possible to do that with matrix content?


texts: If only one Matrix block show this, for more then one block show that

texts:
I have a Matrix field which contains a bunch of blocks. If only one matrix field is present in the entry I need it to show a message. If more then one matrix field show an other message.

Below is my current code.

{% for block in entry.modelIds.limit(1) %}
    {% if block.modelId|length == 1 %}
        I am link - {{block.modelId}}

    {% else %}
        Not a Link - {{block.modelId}}

    {% endif %}
{% endfor %}

Any help would be appreciated. I have tried a few different approaches and am just stumped.

Thanks!

Edit: adding image of fields.


texts:
Does the control panel search support postDate, expiryDate, dateCreated, dateUpdated?

For a custom date field, the below will return all dates in October 2017:
customDate:2017-10

But for entry attributes like postDate it returns nothing:
postDate:2017-09

Sure would be good to be able to search by these date values.


texts:
I have a Sprout form with table field. I'm trying to fill it as native Entry form table field:

<input type="hidden" name="fields[tableField]" value="">
<textarea name="fields[tableField][0][col1]" rows="1"></textarea>
<textarea name="fields[tableField][0][col2]" rows="1"></textarea>
<textarea name="fields[tableField][0][col3]" rows="1"></textarea>

The data in the table is saved correctly, but after submitting the form, I get an error: Array to string conversion...

Tell me please what is the problem.
Thanks in advance.


texts:
Here is what I am doing, but it's not working:

In a template:

{% import 'macros/global' as macros %}
{{ macros sizedImage(image, alt, 't600X450', 600, 450, link, 'someClass') }}

The I have a macro file with code like this:

{% macro sizedImage(img, alt, transform, declaredWidth, declaredHeight, link, class) %}
...bunch of code...
{% endmacro %}

It's not clear from Craft's documentation what I should be doing differently. I did note that macros have to be included in the template where they are called, instead of a parent template, and that is fixed.

The error I get is:

  Twig Syntax Error – Twig_Error_Syntax
  Unexpected token "name" of value "sizedImage" ("end of print statement" expected).


texts:
I am new to Craft.

Do I need to change any files to display the Description that I have set up for http://viviendasdeprimera.com/eventos/proyectos-de-casas-en-arraijan ?

Many thanks,

Mike


texts:
i´m implementing a image gallery and want to show the thumbnails ( no problem here ) with a transform applied, and i want to implement a image transform on the large image that opens on a lightbox. Why? because it´s a responsive website, and the load speed is crucial, and don´t want to slow things down loading the full image uploaded directly from the client camera ( 6mp or more ), i want to load a large image with a max width of 1000px and jpg quality of 70. I applied the transform and works fine, but the images below 1000px are streted to fit 1000px.

So, my question is: how to set max width of an image to 1000px BUT not forcing it if it´s smaller than the required size?

Crop Fit and Scales don´t do the job.

Any help is welcome! Thanks.


texts:
I think I am not fully understanding how caching works.

Based on this answer I thought I could cache my query and then shuffle the resulting array items.

So I ended up with this code:

{% cache %}
  {% set categoryProducts = craft.entries.section('products').relatedTo(category) %}
{% endcache %}

{% set categoryProducts = shuffle(categoryProducts) %}
{% for entry in categoryProducts %}
  ...
{% endfor %}

But that does give me a "categoryProducts" does not exist error.

Could someone shed some light as to why caching the query doesn't work? I thought caching tags help to reduce the amount of queries being made and I've been studying the documentation, but I don't seem to fully grasp the concept.


texts: Setting a conditional for username in URL?

texts:
Similarly to how Craft knows that a category is defined when a category slug is used, is there a way to detect a user in the same way?

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

Something along the lines of (which only returns true if a user is logged in):

{% if user is defined %}
...
{% endif %}

If a username is in the URL, would/should above code return true similarly to how {% if category is defined %} returns true if a category slug is in the URL? (i.e. .com/news/sherlock_holmes)

I'm able to return author posts using method listed in this question, I'm just trying to simplify even further and have one template list all these views.


texts: Find related entries from section entry Matrix entry field

texts:
In my projects section, each project entry has a Entry field in a Matrix. The Entry field references a tool. On the tool entry page I am trying to display all the projects that use that tool in their Matrix entry field. How do I do that? Currently I use this code but it doesn't display anything. I'm guessing I need to reference the Matrix handle and Entry field handle somehow but I haven't seen it done yet.

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

{% for project in relatedProjects %}
    {{ project.title }}
{% endfor %}


texts: Getting entries related to all of supplied categories, if they exist

texts:
I'm trying to get all entries that related to one .. three categories, as determined whether their id appears in the query string:

{% set sector = craft.categories.id(craft.request.getQuery('sector')) %}
{% set impact = craft.categories.id(craft.request.getQuery('impact')) %}
{% set topic = craft.categories.id(craft.request.getQuery('topic')) %}

{% for post in craft.entries.section(section).relatedTo('and', sector, impact, topic) %}

This works well if each of sector, impact, and topic are present, but will return nothing if any one of sector, impact, topic is null (i.e. getQuery('') is blank). Can anyone suggest a way I can do this?


texts:
As a solution to keep things segregated and clean in git, we started developing websites for craft with templates in the template folder, and js, css, etc in a plugin.  So each website had our base plugin (standard stuff like font-awesome, foundation, jquery, etc) and their website plugin (any additional libraries and their custom css/js).  As an added bonus, our clients could look at the plugin page in the admin panel and see "oh, cool... my website is built by [studio name]!"

To load javascript and css, I used things like:

{% includeJsResource "pluginname/vendor/foundation/bower_components/modernizr/modernizr.js" first %}

We started to notice some significant speed issues.
So I switched to this:

{% includeJsFile "/assets/vendor/foundation/bower_components/modernizr/modernizr.js" first %}

the page loaded SIGNIFICANTLY faster.  Like, 3-7 seconds faster.  Which is a lifetime on the web.  The documentation doesn't appear to make any mention of this.

Why is includeJsFile so much faster?
Is it possible to use includeJsFile AND keep my resources in the plugin directory?


texts: How to search a matrix block with a specific handle?

texts:
I want to query a specific matrix block using text search which will search all the searchable fields in that particular block and give me output in the form of blocks that I can further process.

I tried this

 {% set MatrixBlocks = craft.matrixBlocks()
.type('metaData')
.search(query)
.all() %}

But when I dump each block, I am seeing so many fields and not fields only from the particuar block (metaData) that I want to query.

What is the correct query?


texts: Craft on Heroku with buckateer as a middleman for Amazon S3

texts: We are using Craft on Heroku and wants to use S3. The problem is that we want to use a Heroku element (buckateer) as a middleman. Buckateer only gives you an IAM user without listbuckets permissions. So you get "S3::listBuckets(): [AccessDenied] Access Denied". Is there a smart and easy way to set the bucket manually without going into the core files?


texts: Freeform email notifications going to spam

texts: Hi does anyone know how to keep the email notifications from going to spam folder?


texts: How can I only get the entries that are related to an active category

texts:
In the product overviews and search results on my website are also products listed which are related to passive categories.
Is there a way to get only entries which are related to active categories?

The product with this category status should not be displayed at the website


texts:
I am including head.html and scripts.html in my template. Most of the scripts load except for 2 yet the path is the same for all of them. I {% include %} them.

If I change foundation.min.js to foundation.js it works. The min file exists.

Update:
This is because JS files are checked for errors before being loaded. For example, if I visit those URL's directly it will show me an error. Any way to stop that?

http://craft.dev/bower_components/foundation/js/foundation.min.js

Update:

<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/bower_components/foundation/js/foundation.min.js"></script>
<script src="/bower_components/imagesloaded/imagesloaded.pkgd.min.js"></script>
<script src="/bower_components/velocity/velocity.min.js"></script>
<script src="/bower_components/velocity/velocity.ui.min.js"></script>
<script src="/bower_components/wookmark-jquery/jquery.wookmark.min.js"></script>
<script src="/js/app.js"></script>


texts: Link to a front-end upload in email notification using the Sprout Forms plugin

texts:
I'm trying to add a link to a front-end upload in an email notification.  The docs say "To send notifications that include a direct link to your file, you can enable Template Overrides". I've done that, but all I can get is a link to a temporary file in cpresources/tempassets which doesn't exist any more.

I can't see how the code in the docs could be used in the email.html override file.

This is from the docs: (https://sprout.barrelstrengthdesign.com/craft-plugins/forms/docs/examples/front-end-file-uploads)

{% set resume = object.resumeAssetFieldHandle.first() %}
Resume: {{ resume.getUrl() }}

But that doesn't work for me. Presumably resumeAssetFieldHandle is just an example field name but I don't know what the object is.

I have (after line 44)

{% if field.handle == 'uploadFile' %}
{{ value[0].getUrl() }}
{% endif %}

Which gives me the temp link.

Any pointers to how I can get the permanent link?

Thanks!


texts:
I have created a custom element type and cant get the reference tags to parse correctly, I've set the refHandle and the action to copy reference tag which seems to be correct format when I copy a reference tag.

If I try to parse that in a template it doesn't work, it just stays in the reference format {refHandle:identifier}, I have the syntax correct because it works with entries and other base element types.

Am I missing something from my element type? I can't see anything from the docs or from looking through the craft commerce plugin as a guide.


texts: Front-end Registration Form just refreshes with no error displayed and user not created

texts:
I am using the registration form from the docs here - https://craftcms.com/docs/templating/user-registration-form - in the front end of my site. Unfortunately, when I click on "Register" the page just refreshes and no errors are displayed, and the user is not created.

I have checked the following:

"Allow Public Registration?" is checked in the CP.
I made sure that the Snaptcha plugin was disabled (just in case).

Any ideas on what I should look for?

Thanks!

<form method="post" action="" accept-charset="UTF-8">
<input type="hidden" name="action" value="users/saveUser">
<input type="hidden" name="redirect" value="/success/">

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

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

Username
<input id="username" type="text" name="username"
    {%- if account is defined %} value="{{ account.username }}"{% endif -%}>

{% if account is defined %}
    {{ errorList(account.getErrors('username')) }}
{% endif %}

Email
<input id="email" type="text" name="email"
    {%- if account is defined %} value="{{ account.email }}"{% endif %}>

{% if account is defined %}
    {{ errorList(account.getErrors('email')) }}
{% endif %}

Password
<input id="password" type="password" name="password">

{% if account is defined %}
    {{ errorList(account.getErrors('password')) }}
{% endif %}

<input type="submit" value="Register" class="submit">
</form>


texts: PHP error when trying to access dates in Sprout Reports

texts:
Basic Sprout Report here, settings page:
{{ forms.dateTimeField({
  label: "Start Date"|t,
  instructions: "The start date of the date range you wish to display in your report."|t,
  id: 'datetimeStartDate',
  name: 'datetimeStartDate',
  value: settings.datetimeStartDate is defined ? settings.datetimeStartDate : now|date_modify("-30 days")
}) }}

{{ forms.dateTimeField({
  label: "End Date"|t,
  instructions: "The end date of the date range you wish to display in your report."|t,
  id: 'datetimeEndDate',
  name: 'datetimeEndDate',
  value: (settings.datetimeEndDate is defined ? settings.datetimeEndDate : now)
}) }}

Results page:
{% set purchases = craft.entries()
  .section('purchases')
  .limit(null)
%}

{% if settings.datetimeStartDate and settings.datetimeEndDate %}
  {% set purchases = purchases.postDate('and, >= ' ~ settings.datetimeStartDate.date ~ ', <= ' ~ settings.datetimeEndDate.date)
%}
{% endif %}

I am getting the following PHP error:

PHP Notice – yii\base\ErrorException Undefined property:
DateTime::$date

I have copied the datetime fields directly from the example docs, and tested the results template code with hardcoded dates, which works fine, but passing dates this way does not work.


texts:
I need to add an adjuster after the order is completed, but can't get it working.

The reason is that the customer can order a individual picture, after that he get's a preview of the picture where he can proof the image and only when he confirms the preview he has to make the payment. In case of payment by bill, there is a payment fee about 5 EUR.

The adjuster I made works, but only if the order is not completed. Is there any way to implement this?

Or can i add a payment fee via a custom payment gateway, that adds to the bill at the end?


texts: Lingering artifacts of deleted Sprout Forms plugin causing queue failure for updating search indexes

texts:
I noticed I had a task failure notification that I couldn't clear in my Craft 3 cp for updating search indexes. Found this in queue.log:

  2020-01-15 20:02:44
  [-][41673][-][error][craft\queue\QueueLogBehavior::afterError]  [26]
  Updating search indexes (attempt: 1) - Error (time: 0.000s): Class
  'barrelstrength\sproutforms\elements\Entry' not found

I had installed Sprout Forms and also Sprout Email recently, but then disabled & removed them when they weren't quite what I was after. However, I see they've left some pieces of themselves in my database: tables sprout_addresses, sproutemail_notificationemails, sproutemail_sentemail, sproutimport_seeds, sproutreports_datasources, sproutreports_reportgroups, sproutreports_reports. (I had also installed Sprout Import on this site back when it was still running Craft 2 but it's long gone now, or I thought it was.)

Can I just drop these tables? And does that solve my queue problem? I'm tempted of course to just try and see, but don't know where there may be more bits of these plugins in my database or codebase that might cause trouble if I disappeared these tables. For example, I do see a FK relationship from the one existing row in sproutemail_notificationemails to a row in craft_elements; not sure what happens if I delete that row too.

Would be grateful for advice on the best approach here. Thanks in advance.


texts: Update field within Table using column handle in CraftCMS

texts:
I am writing a CraftCMS plugin out of which I need to update an existing Entry. Within this entry there is a field of type table which has some columns (with custom handles). No I d like to update one of those columns using my Plugin.
The thing is I cannot find out how to access the columns using my custom handles from within my plugin to update them. If I access the column using Craft's default col1/2/... keys it works, but not with my custom handles.
Lets say col3 has a customHandle named "myHandle".
example how it works:
$table[$rowId]['col3'] = "123"
example how it does not work:
$table[$rowId]['myHandle'] = "123"
So to me it looks like its possible to use those custom handles to read values (since it works in twig files) but not to update values. Is that possible? And if yes, is there a way on how I can find out the corresponding key for a custom handle? So to find out that col3 belongs to myHandle?
I am looking forward to your help.
Thx in advance.


texts: Getting a phpmailerException error due to my attachments when my plugin runs

texts:
When my plugin runs, I'm getting a PHP Mailer Exception error stating:

"Could not access file: http://s3.amazonaws.com/patternmanager/clients/healthstream/question-attachments/download.jpeg"

The url being pulled in is correct, and the file exists. I'm still very new to this, but the best I can figure out is that this is some kind of permissions issue?

Is there something in my code that might be causing a problem? Am I calling in the attachments correctly? Any direction is greatly appreciated.

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

    //Event: onSaveEntry
    craft()->on('entries.saveEntry', function(Event $event)
    {

        $entry = $event->params['entry'];
        $isNewEntry = $event->params['isNewEntry'];
        $entrySection = $entry->section;

        $attachments = $entry->questionAttachments;

        if ($isNewEntry and $entrySection == 'Questions')  {
            //Get all users from UserGroup
            $user_criteria = craft()->elements->getCriteria(ElementType::User);
            $user_criteria->groupId = '9';
            $users = $user_criteria->find();

            //Send to each User
            foreach ($users as $user) {
                //Send Mail
                $email = new EmailModel();
                $email->toEmail = $user->email;
                $email->subject = 'New Question';
                $email->htmlBody    =

                'A new question has been posted: url.'" title="'.$entry->title.'">'.$entry->title.'';

                if ($attachments) {
                    foreach ($attachments as $attachment) {
                        $email->addAttachment($attachment->url, $attachment->filename, 'base64', $attachment->kind);
                    }
                }

                craft()->email->sendEmail($email);
            }
        }
    });
}


texts: Should the initial selected subfolder in the 'Add an asset' dialog be the Default Upload Location?

texts:
Using Craft Pro 2.2.2601, I am finding the asset selection mechanic a little confusing from a UX perspective when I am using {slug} in the asset field's 'Default Upload Location' to place assets in correct subfolders.

When I drag assets directly onto an asset field, it places the asset in the specified subfolder correctly. However, when I click on the Add an Asset button, the asset dialog opens with the root asset folder selected, so clicking the Upload files button causes the file to be added to the root folder by default. When this happens, the {slug} subfolder is generated anyway, with no contents.

It would make more sense to me if this generated subfolder was automatically selected so that the asset is placed in there. Having to navigate down the directory structure manually is a bit annoying and fiddly, and if a client forgets to do this then they are left with an empty {slug} subfolder.

Is this a bug or intended behaviour?


texts: What is the difference between the Translation Methods when creating a new site

texts:
I am creating a new multi-lingual site and the documentation does not explain the difference between the options in the translation method dropdown.

What is different for each of these and when is it recommended to choose the from the options?


texts: I've looped through individual category groups to find each parent/child category, but is there a way to loop through and only show Category Group names?


texts:
I am currently using the Standard JSON configuration. My config is below. I cannot get the image button to show up for my Body Field/Rich Text. This is the same configuration I've used on other CraftCMS sites without issue.

{
    buttons: ['html','formatting','bold','italic','unorderedlist','orderedlist','link','image','video'],
    plugins: ['fullscreen','video'],
    toolbarFixed: true
}


texts:
How do you make breadcrumbs in your Twig templates for Craft 3?

Unfortunately I found examples only for Craft 2


texts: Can you pass a variable with includeJsFile?

texts:
Can you do something similar to using "with" in twig's include tag (http://twig.sensiolabs.org/doc/tags/include.html), but instead with includeJsFile?

I am using a plugin to filter my entries by their tags. The js initiation for this plugin requires me to list all the tags I'm using as a variable. I'd love to assign a variable to the tag group I'm using and pass it to the javascript file, rather than hard code the tag names. Is this possible?


texts:
I'm running into this effectively https://github.com/pixelandtonic/ElementAPI/issues/4 and I'm not quite sure how I'd integrate this change with https://gist.github.com/stevieg83/85dd058dc77a3b46764165975b17bb76 adding it as the first part of my function errors out for me

syntax error, unexpected '=>' (T_DOUBLE_ARROW)

What's missing?


texts:
I got given a db dump using Craft 3.5.16. After installing all the dependencies using composer and npm  I can login to the admin section.
However, I do not see any entries or any files in the admin section. In the frontend, I can only see the basic skeleton of the website including the footer and the correct CSS but no content. All links in the footer redirect to the live website though they should go to local pages.
The DEFAULT_SITE_URL is set in .env, pointing to the right local URL. There are no errors in the logs either.
Any clue what could be going on would be much appreciated! :)


texts: How to send automated Commerce Subscription related emails?

texts:
What’s the best way to send automated Commerce Subscription related emails? For example, if a user sets up a new subscription they would get sent a confirmation email with details about it, how to cancel etc. Then emails relating to renewals, payment issues, cancellations would follow.
I imagine this could work in a similar way to Commerce order status related emails, with the emails being generated from a template. As far as I can see that’s not something built into Craft, yet, so assuming this needs to be done with event listeners.


texts: How to get current locale in the controller

texts:
I'm struggling to get current locale code from the controller, I would use craft.locale in the template, but craft()->locale does not do the trick.

Any help would be appreciated.


texts:
How do I get pagination set up with the following? It should be easy but I'm getting in a muddle.

{% set myUserQuery = craft.users().group('members').order('companyName asc').limit(10).find %}
{% set users = myUserQuery %}

<div class="col-24 gutter-bottom--none flex-container">

  {% for user in users %}
      {% include "includes/_directory-list" %}
  {% endfor %}

</div>

{% include "includes/_pagination" %}

I thought I might be able to do this, but no

{% paginate users %}