texts: "An unknown error occurred." when changing profile avatar image

texts:
I'm trying to change my profile avatar image, and I'm getting a "An unknown error occurred." No indication of what might have gone wrong. Permissions are correct on /craft/storage/userphotos and all the user directories inside. What am I doing wrong?

Error message in /craft/storage/runtime/logs/craft.log:

2014/09/13 13:39:02 [warning] [application] 404 -
2014/09/13 13:39:02 [error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in /abs/path/to/craft/app/controllers/TemplatesController.php:59


texts: Is it possible to change the time increments in the Date/Time field?

texts:
We have a date/time field shown to render the time for a series of workshops but right now Craft only increments in 30 minutes.

Is there a way for us to render 15 minute increments?


texts: YouTube video embeds in rich text field not saving

texts:
When adding a YouTube video to a rich text field the video embed appears as expected. The entry then fails to save with no error (if I make other changes at the same time they don't save either).

Strangely, this only happens on the live server (my local MAMP setup saves the entry as expected) so I'm thinking it might be a server config thing?

I have unchecked the 'Clean up HTML' and 'Purify HTML' options for the field. It's in a Matrix field if that makes any difference.

Here's my Redactor config (added everything to allowedTags to try to figure it out):

{
  "buttons": ["html","formatting","bold","italic","unorderedlist","orderedlist","link","image","video"],
  "plugins":["fullscreen","video"],
  "toolbarFixed": true,
  "pastePlainText": true,
  "allowedTags": ["a", "abbr", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "blockquote", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "dd", "del", "dfn", "div", "dl", "dt", "em", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "i", "iframe", "img", "input", "ins", "kbd", "keygen", "label", "legend", "li", "map", "mark", "menu", "nav", "ol", "optgroup", "option", "p", "picture", "pre", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "small", "source", "span", "strong", "sub", "summary", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "u", "ul", "var", "video", "wbr"],
  "replaceDivs": false,
  "formatting": ["p"],
  "formattingAdd": {
    "heading": {
      "title": "Heading",
      "args": ["h2", "class", "h2", "toggle"]
    },
    "subheading": {
      "title": "Subheading",
      "args": ["h3", "class", "h3", "toggle"]
    }
  }
}


texts: Clean install - Service Unavailable message at setup

texts:
Folks:

I installed CraftCMS. All files are uploaded, chmod done, and everything else. I visit the page http://example.com/admin to go through setup and I get the message "Service Unavailable. Our site is temporarily unavailable. Please try again later."

I checked .htaccess and the config file. All is well.
I changed isSystemOn from "null" to "true". Same message.
I contacted my host to see if Craft will run on the server. All
requirements are met.

Since this is a Craft message it seems pretty clear that the database is being connected to but nothing is happening. Any assistance would be great.


texts: Is it possible to upload a zip file via Assets?

texts: I have a need to be able to upload a zip file into assets. Is it possible?


texts: Trigger Update Asset Index from url endpoint

texts: Is it possible to trigger an update of the asset indices from an url endpoint? I guess not, but is it planned to provide some kind of API?


texts: Plugin field-type not getting javascript variable?

texts:
Updating a plugin from Craft 2 to Craft 3, so this logic used to work.

The plugin has a field-type which is a button. When clicked, the button does stuff depending upon another field. That handle(ID) of that other field must be passed to the button's javascript.

The field's class seems to register the js correctly. When the page loads, it gives a popup with the correct info.

var startDateFieldHandle = 'fields-startDate';
alert( 'startDateFieldHandle = '+startDateFieldHandle);

Above that is
<script src="http://f.dev/cpresources/6991e452/occurrencesField.js?v=1527142206"></script>
which pulls in the following:

jQuery(document).ready(function(){
    $("#fields-cal37_choose_dates_button").click( function() {
        alert('Clicked the button');
...
        var start_date = new Date( jQuery("#"+startDateFieldHandle).val() );

The alerts happen in the correct sequence, but nevertheless my guess is that because <script cpresources> bit occurs earlier on the page than where startDateFieldHandle is set, that somehow it still isn't set when the button is clicked.

I don't see, using Craft::$app->View->registerJs($js); that there is any way to say "put this first."

It did used to work under Craft 2. Any tips?

Update
At present, I'm seeing in occurrencesField.js that as soon as I reference the startDateFieldHandle variable in any way, such as alert(startDateFieldHandle); the script quits.

Also, in the Firefox console, I'm getting:

jQuery.Deferred exception: startDateFieldHandle is not defined @http://f.test/cpresources/6d6f7137/occurrencesField.js?v=1527518592:101:2
l/</e@http://f.test/cpresources/61c13c0c/jquery.js?v=1527049453:1:29794
l/</t<@http://f.test/cpresources/61c13c0c/jquery.js?v=1527049453:1:30109
 undefined  jquery.js:1:31365
Double-instantiating a menu button on an element garnish.js:1:2512


texts: Is it possible to bcc/cc an admin on every system email?

texts:
My understanding is that the testToEmailAddress config items replaces the to address for system emails.

Is there a way, outside of extending the system functionality with a plugin, to add a to/cc/bcc address for system emails? (Use case: I want to CC/BCC an admin on every system email.)


texts:
I'm trying to pull all the entries in a category that have a multi-selection selected and then paginate it.

If I just do the below, it works perfectly fine.

{% set entriesRed = craft.entries.section('eventRentals').relatedTo(category) %}
{% for entry in entriesRed if entry.rentalColor.contains('red') %}
            {{ entry.title }}
{% endfor %}

But now I want to paginate it and I can't quite get the right syntax. To be clear, it's the top part I can't get a hold of, I'm modifying an already working existing pagination so I'm not including the bottom half.

{% paginate craft.entries.section('eventRentals').relatedTo(category).limit(12).order('title') as entries if entry.rentalColor.contains('red') %}
{% for entry in entries %}
    {{ entry.title }}
{% endfor %}
{# blah blah blah rest of the pagination ul li stuff #}

doesn't work, neither does

{% paginate craft.entries.section('eventRentals').relatedTo(category).limit(12).order('title') as entries %}
{% for entry in entries if entry.rentalColor.contains('red') %}
     {{ entry.title }}
{% endfor %}

Any tips?


texts: Issue Updating Asset Index:S3 Product Downloads

texts:
We recently added a large file (3gb) to our S3 location, and upon updating the assets index, the file is not being recognized.

The file is accessible and we have tested download directly.

Additionally, when we attempt to update the asset index, files that were previously indexed are now showing an error intermittently (Missing files: The following files could not be found. Should they be deleted from the index?)

Any ideas?


texts: Help understanding an error message from Dukt OAuth plugin

texts:
I'm using the Dukt Twitter plugin which requires the Dukt OAuth  plugin.

Both are working perfectly on both my local Dev environment and the remote Staging environment, but not on the Live site. Both plugins install with no errors or problems. Configuring the OAuth plugin (for Twitter only) is fine as well - it accepts the keys/credentials generated from the Twitter API Management Console and shows as "configured" on it's status screen.

However, when I then go to the actual Twitter plugin config and hit the "Connect to Twitter" button, I get this error message:

Fatal error: Class 'League\OAuth1\Client\Server\Twitter' not found in /webserver/domains/[CLIENT]/live/craft/plugins/oauth/providers/Twitter.php on line 46

Anyone have any idea what this error message means?

I suspect it's more to do with the server or site config than the actual plugin but I'm not sure where to start looking as I don't understand why it can't find that namespace


texts: Craft CMS login 500 (Internal Server Error)

texts:
I transferred a website using Craft CMS and now when I want login to admin the console return me

jquery-2.2.1.min.js?d=1493126871:4 POST http://website.com/index.php/admin/actions/users/login 500 (Internal Server Error)

I put app to debug mode and I have very more error like to

[14:44:38.309][trace][system.CModule] Loading "cache" application component in /home/domains/website.ca/public_html/craft/app/etc/web/WebApp.php (593)

I try put RewriteBase / and ma .htaccess my site is multilang so i put this and the .htaccess of each file /en and /fr

The website is at a hosting company and a not access to ssh . The PHP version is 7 and a have activate all module


texts:
In the previous version of the Google Maps plugin (Smart Maps) I used something similar to this to toggle multiple KML layers:
    var streetLayer = new google.maps.KmlLayer('https://www.comovisionzero.org/assets/data/high-crash-network.kml', {
        preserveViewport: true,
        suppressInfoWindows: false
    })
    function toggleStreetLayer() {
        if( $("#streets").is(':checked') ) {
            streetLayer.setMap(map);
        }
        else {
            streetLayer.setMap(null);
        }
    }

In the new version, I'm trying to use the callback and map.kml functionality, but I'm having difficulty toggling the KML layer off:
  {{ map.tag({
    'callback': 'mapFilters'
    })
  }}
  <script>
  {% js %}
    function mapFilters() {
      var map = googleMaps.getMap('mapAlpha');

      function showLayer(kmlUrl) {
        map.kml(kmlUrl, {
          'preserveViewport': true
        });
      };

      function toggleStreetLayer() {
        if( $("#streets").is(':checked') ) {
          showLayer('https://www.comovisionzero.org/assets/data/high-crash-network.kml');
        }
        else {
          showLayer(null);
        }
      }

      $("input").change(function() {
          toggleStreetLayer();
      });

    }
  {% endjs %}
  </script>

Am I even close to being on the right track?


texts: How can I use CSRF protection with AJAX routes?

texts:
I have CSRF enabled on my install. I have a bunch of frontend forms so CSRF is pretty important for me. However, when I use AJAX to post to a controller action I get the following error.

Bad Request

The CSRF token could not be verified.

Here is my AJAX that I am testing with.

$(function(){
    var data = { id: 100 };
    $.post("/actions/gistClient/exampleAjax", data, function(response) {
        console.log("success", response, data);
    });
});

Here is my controller action

public function actionExampleAjax()
{
    $this->requireAjaxRequest();
    // ... whatever your AJAX does...
    $response = array('response' => 'Round trip via AJAX!');
    $this->returnJson($response);
}

Is it possible to disable CSRF for certain routes? Alternatively, how would I pass CSRF through AJAX to the controller action?


texts: How can I access or set a Task's properties inside a class or method?

texts:
How am I able to get or set additional properties on a Task model inside a plugin.
Eventually I would like to influence the Totalsteps of a task.

$task = craft()->tasks->createTask('Reroute', 'Importing routes', array(
    'files' => $files,
    'steps' => count($files)
));

class RerouteTask extends BaseTask
{
    public function getTotalSteps()
    {
        return $this->getSettings()->steps;
    }

Is resulting in Craft\TaskModel.steps is not defined.
What am I missing here?


texts: Clicking New field on /admin/settings/field/new hangs site

texts:
Running 3.2.4, and clicking on "new field" which calls /[admin]/settings/fields/new times out on our AWS servers where the DB is hosted in the cloud. It isn't an issue when everything's running localhost, but that's the only things we can see as a difference between them.

On the AWS hosted site, the CP and front end become unresponsive for that user in that browser for 15-20 minutes, but a newly created session from another browser works.

Could anyone else who similarly has their DB hosted on another machine try clicking Settings->Fields->New and see if it returns fast?


texts:
I have a channel with a related users field. I want to output all channel entries ordered by the number of related users, this is what i have so far:

{%
    set entries = craft.entries.find({
        section:  'MyChannel',
        orderBy:  'relatedUsers'
    })
%}

What do i do to order by the number of related users?


texts: Upload file from plugin's Controller to a non-Assets folder

texts:
I have a plugin Controller that accepts a POSTed form, including an uploaded file. If I make an Assets Source I can successfully save the file into its folder like this:

$file = UploadedFile::getInstanceByName('myFieldName');

$folder = craft()->assets->findFolder(array(
    'sourceId' => 3, // My Asset Source's ID.
));

$response = craft()->assets->insertFileByLocalPath(
    $file->getTempName(), // Local path to file.
    $file->getName(), // Name file should be given when saved.
    $folder->id,
    AssetConflictResolution::KeepBoth
);

if ($response->isSuccess()) {
    ...

However, I want to upload the file to a folder that's not an Asset Source - for security reasons I don't want these particular files to be visible in any way in the CMS. Is there a way to do this, eg, by using a filepath rather than an Asset Source?

(I'm also not sure how to validate the file, in terms of its file extension, size, etc. I can see how to do this in Yii but I'm not sure how to do it having uploaded the file as above.)


texts: Password validation for resetting password

texts:
I have the following code to further validate passwords when creating/registering an account which is working fine.

However, when trying to use this same validation for resetting a password I am not getting any errors back?

Can anyone point me in the right direction...?

public function onBeforeSetPassword(Event $event)
{
    $user = $event->params['user'];
    $password = $event->params['password'];

    if (mb_strlen($password) < 8)
    {
        $user->addError('password', 'Sorry but your password must be at least 8 characters.');
        $event->performAction = false;
    }

    if (!preg_match('/(\d.*[A-Z]|[A-Z].*\d)/', $password))
    {
        $user->addError('password', 'Sorry but your password must contain at least one uppercase letter and one number.');
        $event->performAction = false;
    }
}

On the template:

{% if account is defined and account.getErrors('password') %}
    {% include '_includes/formError' with { error : account.getErrors('password')|join('<br>') } %}
{% endif %}

Thanks.


texts: How can I disable automatic copy to new localized fields on first save of an entry?

texts:
Is there any way to stop this? It would be nice to stop this (for my purposes) and then tell the template to fallback to content from a certain locale if the current locale does not have content for a given field.

Essentially, I'm searching for the best way to have fields track the changes of a "default" locale. Currently in Craft content is only tracked on the first save of an entry after adding the locale.

Thanks!


texts: Creating a new entry in a specific section

texts:
Let's say I created a section called, "Answers". In a custom plugin, I want to create an entry that should show up under the "Answers" tab in the CP entries page.

  $entry = new EntryModel();
  // How do I say, save this entry into the "Answers" channel?
  $saveIt = craft()->entries->saveEntry($entry);

I have literally been reading Craft docs for the past hour, and have gotten nowhere.


texts:
I'm looking into a project another developer has done, and after submission of a front-end form the system is ignoring the redirect set in the template. The form is being submitted and saved correctly though.

Anyone got any ideas why this would be?

<form method="post" action="" accept-charset="UTF-8" id="download-subscribe">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="guestEntries/saveEntry">
    <input type="hidden" name="redirect" value="/downloads/available-downloads/">
    <input type="hidden" name="sectionId" value="11">

        First Name
        <input id="firstName" type="text" name="fields[firstName]">

    ...

</form>

Possible complications, which i expect aren't a problem but might be worth knowing:

The form is in an include rather than in the template directly
The form is being spat out mid-way through a matrix loop (i.e., if the loop is count 2 then first spit out the form).


texts: Possible to use REGEX Backreference in Routes

texts:
I've searched and searched for info on regex backreferences in Craft's route.php file to no avail.

I have a URL structure required by the client along the lines of:

/ [state] / [section] / region / [region]

so for examples:

/ hawaii / hotels / region / oahu
/ hawaii / retaurants / region / oahu
/ hawaii / hotels / region / maui

The "hotels" and "restaurants" are each their own Section (Channels) and require their own templates.

Given the above URL examples, I've created template directories:

/hotels/region.html
/restaurants/region.html

I can manage the routes if I spell them all out. But what I'd like to do is use regex backreferences in the target templates.
Tried but it fails. tried something like the following:

'hawaii/(.*)/region' => '\1/region'

The '\1' backreference doesn't catch the first group of either "hotels" or "restaurants."

Is it simply not possible to use backrefs in the target route templates...or is my syntax not correct for Craft?


texts: Craft site moved to HTTPS - now having issues

texts:
I have had a Craft install running for some time now, and it has come to the point where I want to run it securely over HTTPS.

Using Laravel Forge, I have set up a Let's Encrypt certificate successfully, so on certain pages of the site it all works well. In my config/general.php file I altered the siteUrl and environmentVariables -> baseUrl to use https.

However when I try to log in to the admin on this server, in the JS Console, the GET requests for all the admin/resources CSS / JS files are returning 404. So the admin login screen shows without any styling, and crucially, logging in returns a bad CSRF token screen!

Any tips?

Thanks

Here's my nginx config:

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/www.fira.co.uk/before/*;

server {
    listen      80;
    server_name www.fira.co.uk;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

server {
    listen 443 ssl;
    server_name www.fira.co.uk;
    root /home/forge/www.fira.co.uk/public;

    # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/www.fira.co.uk/105882/server.crt;
    ssl_certificate_key /etc/nginx/ssl/www.fira.co.uk/105882/server.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/nginx/dhparams.pem;

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DOT NOT REMOVE!)
    include forge-conf/www.fira.co.uk/server/*;

    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/www.fira.co.uk-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 ~ /\.ht {
        deny all;
    }

    # Media: images, icons, video, audio, HTC
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
  expires 1M;
  access_log off;
  add_header Cache-Control "public";
}

# CSS and Javascript
location ~* \.(?:css|js)$ {
  expires 1M;
  access_log off;
}
}

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/www.fira.co.uk/after/*;


texts: Newbie: Trying to understand includeCssFile

texts:
I'm a newbie to Craft and am working with a raw version of Craft CMS 2.6.2903 on localhost and am trying to understand some of the basics. The problem that I am encountering at the moment is to do with the Twig includeCssFile command.

I want to create a folder that will contain all my CSS details, so I went to _layout.html and moved all the CSS script from between the
style tags into a new script which I saved at craft/templates/styles/index.css. I then deleted the style tags from _layout.html.

I added this line to the <head> section of the _layout.html script:

{% includeCssFile "styles/index.css" %}

So that the <head> section looked like this:

<head>
<meta charset="utf-8" />
<title>{% if title is defined %}{{ title }} - {% endif %}{{ siteName }}< /title>
<link rel="home" href="{{ siteUrl }}" />
{% includeCssFile "styles/index.css" %}
</head>

and once again the Home page worked perfectly.

The problem occurred after I moved the whole styles folder up one level (i.e. to the same level as the templates folder).

I changed the calling code to
{% includeCssFile "../styles/index.css" %}
and refreshed the home page and had lost all the page styling. I played around with removing the '../' and changing it to './' and even '/' but it still didn't work. When I returned the styles folder to the templates folder, it all worked okay again.

There have been a couple of similar questions already posted on this group, but they haven't resolved my problem (link 1, link 2)

Can someone please tell me what I need to do?


texts: Retain value from select and checkbox on frontend form after failure

texts:
I have a registration form on my frontend and when people click register but the form fails (due to the username already existing for example) I would like to keep all info they entered in the form so they don't need to enter all their data again while editing the form input that gave the error.

I know that there is an account model which you can use to keep all the info into the inputs. I used the official example as a source.

{%- if account is defined %} value="{{ account.fieldName}}"{% endif -%}>

Then I found this for checkboxes but for some reason it doesn't seem  to work. I used this in my code (receiveNewsletter is a lightswitch in Craft / checbox on the frontend):

{%- if account is defined and account.receiveNewsletter == "1" %}checked{% endif -%}

But it always seems to return TRUE.

And I have no idea how to handle this for select inputs. Can anyone get me back on track please?


texts: Get entries where relation matches or is empty

texts:
I have a channel section (tickets) where each entry has a members field. The members field can either be empty (making the entry 'public') or specific members can be added (making it 'private', to only the selected users).

I want to get a list of all the entries within the section where the members field is either empty or the currentMember has been added to the list, e.g. a member should see both public entries and private entries they have been added to.

I'm using the following to get all private entries for the currentMember, but I can't figure out how to make it include the public ones as well.

{% set tickets = craft.entries.section('tickets').relatedTo({
    targetElement: currentMember,
    field: 'members'
}) %}


texts: Experience with Craft's native rss/atom support?

texts:
I'm trying to use the native support for rss and atom as described in the documentation, but it misses some info.

https://craftcms.com/docs/templating/atom-feed
https://craftcms.com/docs/templating/rss-feed

Did anyone got this to work? I'm not even sure how to name my template or what the url is going to be.

I tried the following template names:
template.twig.atom
template.atom.twig
template.atom

I tried requests with atom in the header and .atom postfix. Both without any success.


texts: Checking if user authored an entry in another channel while in loop, N+1 problem

texts:
I have 2 channels set up: Channel A and Channel B.  I also have public registration so users can log in and fill out two forms (Form A and Form B), each form creating an entry in their respective channel with the user as the author.  The user can only create an entry in Channel B if they already have an entry in Channel A.

To get all the users who have an entry in Channel A but not in Channel B, I tried writing something like this in my class:

public function getUsersWithoutChannelBEntry()
{
    $channel_A_entries = Entry::find()
        ->sectionId(1)
        ->all();

    $userIds = [];
    foreach ($channel_A_entries as $entry) {

        $channel_B_entry_exists = Entry::find()
            ->sectionId(2)
            ->authorId($entry->authorId)
            ->exists();

        if (! $channel_B_entry_exists) {
            $userIds[] = $entry->authorId;
        }

    }

    return User::find()
        ->id($userIds)
        ->all();
}

However, this creates an N+1 problem. I have roughly 200 users, so potentially 200 entries in either channel, and thus a lot of db queries and a substantially larger load time.

As an alternative approach, I've also tried looping through Channel A, adding each author ID into an array (Array A), then doing the same with Channel B making Array B.  Then I use array_diff() to extract the author IDs that are in Array A but not in Array B.  However, this still causes a bit of long load time.

I've looked into eager loading, but that seems to only apply to related fields.

Is there a more efficient way to get all users who authored a Channel A entry but not Channel B entry?


texts: Is there a way to apply project.yaml changes on deployment?

texts:
Love the new new project config functionality, but if there are changes that need to be synchronised the site essentially goes down until the changes are applied manually.

I wondered if anyone had a simple way to programmatically apply the changes automatically when the site is deployed, via a webhook?


texts:
I'm trying to make a simple post request with ajax to a controller in plugin.
The problem I'm having is that I always get a 400 Bad request because I don't send a valid CSRF Token.

But I can't figure out how to get this in javascript. I found multiple examples saying you get it by calling

Craft.getCsrfInput();

but this only works in "CP mode", on the front-end the Craft object is not available. I also found that importing it is not a good idea.

So anyone who can tell me how to do this?


texts: How to remove a Super Table row on the front end?

texts:
Is it possible to remove a Super Table row?

I got it to work to add a new row but it would be great if I can remove it later.

Thanks for any help! :)


texts:
Should be easy i thought. How can i display all entries from a section from a certain category?

This is my code now, but nothing shows up (screenshot bottomleft):

{% set category = craft.categories.slug('b2c').first() %}
{% set entries = craft.entries.section('homeBlocks').relatedTo(category).find() %}

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

This code shows all entries (screenshot topleft), and you can see there are entries with b2c:

{% set category = craft.categories.slug('b2c').first() %}
{% set entries = craft.entries.section('homeBlocks').find() %}

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

My Category Group is called Business Category (with handle "businessCategory"). It contains two categories:

b2c (slug "b2c")
b2b (slug "b2b")

The field handle used in the section "homeBlocks" is "businessSegment"

Where's the error? :)


texts: What attribute type should I set in the record or model to create a TEXT type in the database?

texts:
I am having a problem with record and model attribute types.

I have a frontend user form with some textfields which require a TEXT type field in the database to hold the data. So far I have tried setting the attribute type to String which creates a varchar(255) which isn't big enough to hold the data.

I've also tried Mixed which creates the TEXT type but does not populate the data when the form is submitted. Reading further and based on a previous problem I had I think this is due to the lack of validation on the Mixed attribute.

So my question is how do I get my form to submit this data if the attribute I create is causing the

$record->setAttributes($model->getAttributes());

to ignore the Mixed fields data. Or is there another attribute that would work better something like Text?

Also what would be useful to know is if there is any resource which describes the different attributes with examples of how to set them up for records and models as I can't seem to find anything that describes this process clearly.

Any help much appreciated.

Cheers


texts:
I have the following menu structure:

as you can see, the Item "Clients" points to the same Url as its Child "Client Portfolio" does.

Unfortunately this is not working for my submenu that should consist of the active menuitems childs:

{% set activeNodeId = craft.amNav.getActiveNodeIdForLevel('mainmenu','1') %}

{% if activeNodeId %}
   {{ craft.amNav.getNav('mainmenu', {
    class: 'subnav-inner',
    startFromId: activeNodeId
                }) }}
{% endif %}

The variable "activeNodeId" is always the deepest level child (with that url). So in my case, clicking on "Clients" would result in an activeNodeId = 66. Of course fetching the subitems of this makes no sense because "Client Portfolio" has no children.

Any idea how to force the plugin to take always the correct (parents) id? Or any other way to get the submenu items of the active menu?


texts:
Is is possible to assign a category via a frontend Guest Entry form.

I tried

<input type="hidden" name="fieldHandle" value="SomeExistingCategorySlug">

But that did not work.


texts: Categories field is losing its value when programmatically updating other fields’ values

texts:
I have a webhook that fetches an entry, modifies one of its custom Text field values and then saves the entry. However there is also a required Categories field on the entry, and when I do this, I get a validation error because the Categories field is blank.

Here’s the relevant code:

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

$entry->setContentFromPost(array(
    'myTextField' => $newValue
));

// Let's see if it saves.
// Field validation should happen automatically
if (craft()->entries->saveEntry($entry))
{
    Craft::log('Entry updated (ID: '.$entry->id.').');
}
else
{
    Craft::log('Could not updated the entry (ID: '.$entry->id.').', LogLevel::Error);
}

How do I save the entry without losing its existing Categories field value?


texts:
I was wondering if it was possible to translate the labels, like "Singles","Entries" in the CP

I know it's possible with Craft 2, but I didn't find with Craft 3.

Do you have any ideas?

Thanks!


texts:
Right now my homepage title looks like:

Home page - SiteName

But i want it to look like this:

SiteName

How do i do this?


texts: How do I allow a user to remove an uploaded asset from a front-end entry form?

texts:
I see for users, I can add a hidden field <input type="hidden" name="deleteUserPhoto" value="1" /> to remove the uploaded photo, however I need to allow this functionality for an assets field in an entry form.

I have tried submitting an empty file field, but it just retains the existing uploaded asset after submission.

Is there a trigger similar to deleteUserPhoto that I can use here?


texts: How to configure Google Cloud Storage in Craft v3?

texts:
I'm doing the Craft 3 upgrade and I can't figure out how to connect our Google Cloud Storage. Back with Craft 2 I used a Google Access Key and Access Secret Key. Now I am asked for a Project ID and the Contents of the access key file.

After reviewing the plugin's README I read about getting the Service Account Credentials JSON. Which after a search, I found were generated through (Google's Identify Platform, IAM)[https://developers.google.com/identity/protocols/OAuth2ServiceAccount] which allowed me to create a Service Account for the project and I downloaded a JSON file.

I went to enter my Project ID and the contents of the JSON, thinking this would solve it, but I keep getting a permissions error. Despite going through the project permissions and the created account permissions. I've tried with Legacy owner permissions and still nothing.

[IAM USER] does not have storage.bucket.list permission to access project [PROJECT # ID]

Am I missing anything or are these not the right credentials?


texts: I currently implemented a fixed position edit button in the front-end when a user is logged in based on this " Get Entry Edit Link in Twig " Is there a version of this link, but to Clear Cache?


texts: Complex logic on a ElementCriteriaModel parameter?

texts:
How would you combine multiple logical expressions on a ElementCriteriaModel parameter?
You could query twice and then merge the two returned arrays of entry models,
but that probably wouldn't allow me to later use the {% paginate %} tag or methods like getNext().

Here's an example where I'd like to filter events starting in calender week 32 or 34:

{% set dateParamCw32 = 'and, >= 2014-08-04 00:00:00, < 2014-08-10 23:59:59' %}
{% set dateParamCw34 = 'and, >= 2014-08-18 00:00:00, < 2014-08-24 23:59:59' %}

{% set startDateParam = 'date range cw32 OR cw34' %}

{% set entries = craft.entries.section('events').startDate(startDateParam) %}


texts: How can I create a status message of X of TOTAL pages under a parent?

texts:
I have a Structure section with an ordered number of entries under a parent. On each entry I would like to add a status message of the user's current progress... i.e. You are on page 1 of 5 pages.

The total was easy...

{% set total = entry.getParent(entry).getDescendants().count() %}

How do I get the current page (child) number within the total number of children.

Thanks!


texts:
Is there a way to get the parameters from the referrer url?

I've tried this:
{{ craft.request.urlReferrer.getQuery }}
but that’s not working.


texts: How to create sub-nav when using a structured navigation heirarchy?

texts:
I have my navigation in a Structure like here and I want to build a sub-navigation on my Information page containing Specials, Reviews, and About, but I can't figure out how.

{% set active_item = craft.entries.section('navigation').nextSiblingOf(48).first() %}

doesn't give me what I need (and I really don't like handling with id's).


texts: AJAX Update Entry (500 Internal Server Error)

texts:
I'm trying to update an entry on the front end with a click and without a form. I'm a bit new with AJAX but would love to simply put a new title for the entry that the button relates to. I'm currently getting 500 Internal Server Errors when trying.

{% for entry in currentUserSubmissions %}
  {{ entry.title }}
  {{ entry.submissionUrl }}
  Approve
{% endfor %}

This is my AJAX

{% js at endBody %}

  $('.btn-approve').on('click', function() {

    var entryId = $(this).data('id');
    var data = {
        value: entryId,
        name: 'entryId',
        title: 'hello test'
    };
    var tokenName = '{{ craft.app.config.general.csrfTokenName }}';
    data[tokenName] = '{{ craft.app.request.csrfToken }}';

    // send ajax request
    $.ajax({
      method: "POST",
      dataType: "json",
      url: "/actions/entries/saveEntry",
      data: data,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      success: function (data) {
        console.log('success', data);
      },
      error: function (error) {
        console.log('error', data);
      }
    });
  });
{% endjs %}

  /actions/entries/saveEntry 500 (Internal Server Error)


texts: unable to delete entries after migration to new server

texts:
After migrating from one server to another, I'm unable to delete entries.

I'm able to add new entries and change their status. But delete doesn't work.

The servers are identical (using digital ocean LAMP stack). I've checked my craft/server logs, I can't find any errors related to this.

Any suggestions as to where to look?


texts: Commerce - show description of discount without coupon applied to cart

texts:
We can retrieve description of discount applied to cart that has its own coupon like this:
craft.commerce.discounts.getDiscountByCode(cart.couponCode).description

Is it possible for discount that do not have coupons and are applied automatically?


texts: How to export client-entered content for a specific channel to keep my local database in sync with staging

texts:
I'm in the process of developing a site for a client and I'd like to give them access to the control panel on the staging server so they can begin to enter content for their "News" channel, which is set up and ready to go, and for which they have lots of historical content to enter.

The issue is that I'm still developing the rest of the site and want to come up with the most painless way possible of keeping their content in-tact in the database without breaking my development workflow as I continue to create additional fields and templates for the remaining sections of the site.

Is there a way that I can easily export just their "News" channel content from the staging database periodically, importing it into my local database and eventually migrating my more complete local database back to staging as I finish more sections?


texts: Record - Mixed/String values will not be saved if attribute not required=true

texts:
I have defined string and mixed attributes for my Record/Model.

'titel' => array(AttributeType::String),
'lage' => array(AttributeType::Mixed, 'required' => true),

If i try to save a record, the data will not be saved, if required=true is not defined! That happens with both, string and mixed attribute types.

But i want to save the records also with empty values.
Whats wrong?

// UPDATE:

I found this The Active Record and added this to my model

public function rules(){
    return array(
        array('title', 'default', 'setOnEmpty' => true, 'value' => null),
    );
}

But it doesnt change anything.


texts: Account Verification or Password Reset Error

texts:
Craft 2.6

I have a site that's been running for some time and now when trying to do a password reset or account verification error I get the following message.

I found this stack exchange thread Where Brad Bell said:

  Every time we've been able to investigate this issue so far, it has
  been because of either .htaccess stripping querystring params behind
  the scenes (i.e. no [QSA] flag on the rewrite rule), or the equivalent
  in nginx-land.

This is good, however I don't know what the The equivalent of [QSA] is in nginx.

Here is my nginx config file  relevant bits with sensitive stuff removed.. any tips?

# FORGE CONFIG (DO NOT REMOVE!)
include forge-conf/www.domain.ca/before/*;

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.domain.ca;
    root /home/forge/www.domain.ca/public;

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DO NOT REMOVE!)
    include forge-conf/www.domain.ca/server/*;

    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; }

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

    # Localized sites, hat tip to Johannes -- https://gist.github.com/johanneslamers/f6d2bc0d7435dca130fc

    # If you are creating a localized site as per: https://craftcms.com/docs/localization-guide
    # the directives here will help you handle the locale redirection so that requests will
    # be routed through the appropriate index.php wherein you set the `CRAFT_LOCALE`

    # Enable this by un-commenting it, and changing the language codes as appropriate
    # Add a new location @XXrewrites and location /XX/ block for each language that
    # you need to support

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

    location /en/ {
        try_files $uri $uri/ @enrewrites;
    }

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

    location /fr/ {
        try_files $uri $uri/ @frrewrites;
    }

    # For WordPress bots/users
    location ~ ^/(wp-login|wp-admin|wp-config|wp-content|wp-includes|(.*)\.exe) {
        return 301 https://wordpress.com/wp-login.php;
    }

}

# FORGE CONFIG (DO NOT REMOVE!)
include forge-conf/www.domain.ca/after/*;

Got a partial hacky fix working. in nginx config I changed this:

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

location /en/ {
    try_files $uri $uri/ @enrewrites;
}

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

location /fr/ {
    try_files $uri $uri/ @frrewrites;
}

to

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

location /en/ {
    try_files $uri $uri/ @enrewrites;
}

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

location /fr/ {
    try_files $uri $uri/ @frrewrites;
}

And when I got the password reset link I had to manually remove the /en/ from the url and it works. Not perfect but at least I can reset passwords.

Not a solution but more of a temporary work around.

UPDATE 2

Not a fix - had to remove above code as it made all interior pages return a 404.


texts: How to show to profile related data inside Users page in admin dasboard, also showing some addtional filters

texts:
I would like to add some additional functionality in Users page, like adding profile related data which we are creating separately suppose, mother tongue, address, hobbies , and job related in same page of the User, can we somehow override the main users page in back-end admin dashboard to show these details as well along with main user data.
Also the admin should be able to create/modify or delete it.
Can you help me in this issue, I'm not able to redesign the page.


texts: Caching ElementCriteria Lookups In Craft CMS Plugins

texts:
Two recent sites I’ve built have plugins built to handle filtering through projects based on some categories and related entries.

For example the lookups look similar to this:

# Get element criterea for searching projects
$projectCriterea = craft()->elements->getCriteria(ElementType::Entry);
$projectCriterea->section = 'projects';
$projectCriterea->limit = null;
$projectCriterea->relatedTo = $relatedElements; # This is an array of categories and related entries.
$projects = $projectCriterea->find();

All these lookups aren’t particularly fast, and there aren’t that many different variants. Is there a way I can add some caching into these lookups?

I had a bit of a look into the CacheService but I'm not sure how to apply that to this.

Thanks


texts: Using language specific variables inside section URL settings

texts:
When i use some kind of variable in url settings of section, it always uses default language version of this variable.

For example, blog has two languages, english (default) and german. If i use these settings in URL settings for single post section, in german version:

{{craft.entries.section('archive').one().uri}}/{slug}

It returns english (default, not german) version o archive section uri.

Is it expected behaviour?


texts: Setting a default entry for the entry field

texts:
I have an entry field that is a selector tool for the page call to action at the bottom.

I have a channel of four or five entries and I'd like one of them to be the default selection so it's one less thing to setup on a site full of pages.

I haven't seen any details or questions for this sort of request as of yet so I thought I'd ask the question.

Thanks,
Jay


texts: Showing just the child category titles of a parent

texts:
I have a category group with parents each with 1 level of children.

On my category entry page I want to list JUST the children of the current category being viewed.

I'm sure it's simple but I can't figure what to put in my category template?

Many thanks in advance.

Martin


texts: Best way to create tags under new EntryModel?

texts:
As best I can tell entries have to be created, tags have to be created, a relationship created and then an update to the original entry. Is this correct or is there a simpler way to do this?

There is a similar question here which address how to create a tags but I feel like how to relate the new tag(s) to the entry could use some elaboration.


texts:
I'm building my first Payment Gateway (offsite gateway) for Commerce 2.  This one is for Moneris.  I'm hitting an error when the page returns the response.

Argument 1 passed to craft\commerce\services\Transactions::getTransactionByHash() must be of the type string, null given

I'm pretty sure I need to do something in completePurchase with the response given, but I don't really understand where to start.  I've looked at Mollie and Paypal Express for exemples and I can't figure it out.  Can anyone point me in the right direction?

Here is the Post Moneris is sending me back:

$_POST = [
    'response_order_id' => '85a6df720018874fde293aa3418e7a97',
    'date_stamp' => '2018-09-11',
    'time_stamp' => '08:37:36',
    'bank_transaction_id' => '660186290010010030',
    'charge_total' => '88.10',
    'bank_approval_code' => '945622',
    'response_code' => '027',
    'iso_code' => '01',
    'message' => 'APPROVED           *                    =',
    'trans_name' => 'purchase',
    'cardholder' => 'Test Card',
    'f4l4' => '4242***4242',
    'card' => 'V',
    'expiry_date' => '2108',
    'result' => '1',
    'txn_num' => '3-0_11',
    'cvd_response_code' => 'M',
];

Thank you!


texts: Checking which version of Craft CMS a site is using

texts:
I've been asked to look at Craft CMS site where my would-be client has been ghosted by his previous developer. I have no handover information and only FTP and phpmyadmin access presently.

Looking via the FTP it appears that both Craft 3 and Craft 2 versions are installed in the vendors directory.

How can I most easily check which the actual site is being used? From the license key or database perhaps?


texts: Using Recaptcha v2 and Guest Entries plugin

texts:
How can I prevent bots from sending tons of messages from a frontend form, it uses the Craft Guest Entries plugin. I'm using Recaptcha 2 but it only hides the submit button and it doesn't work using Craft 2.

All other solutions (antispam) that I check seems quite old...

Thank you.


texts: Can we use PHP in our templates instead of Twig?

texts:
Is it possible to use strait PHP in our templates along side of Twig and or instead of Twig?

If so how does one go about it?


texts:
This is my second website I am building with craft cms and I have no prior experience with Twig.

I have had a particular issue with echoing image assets from a singles entry.

The line I copied from my previous website with craft was;

Field handles were updated correctly and yet on the template page the image is not displayed.

After looking into this I found the following;

{% set asset = entry.teamImage1.first() %}

{% if asset %}
    {{ asset.url }}
{% endif %}

This had no effect either.


texts:
I’ve set up a new Ubuntu 18.04 server, but can not get Craft 3 to run on it - despite it passing the Server test script with flying colours.

I know the server setup is OK as PHPmyAdmin is running on this server (though that has its own issues with PHP7.2, it does at least run).

I don’t want to use Composer as it is not the right choice for our use case; so I’ve downloaded the zip and used that. It won’t install via the browser as whenever I go to /admin/install it claims a 404 error (going to index.php?p=admin redirects to /admin/install).

If I go to the root of the site it claims an Internal Server Error. I can’t see any information in the /storage/logs files, nor in the /var/www/project/logs folder that Apache is configured to dump logs into when hitting the Internal Server Error. There are log entries - and I had issues with - permissions writing to files. Specifically to do with Yii2 file mutex and fopen.

Anyone got any pointers?

Apache is running as the default www-data user and group, the site files are owned by a user belonging to that group, and I’ve 774’d everything recursively.


texts:
I created a payment gateway for Commerce 2. When I try to make a payment, an error happens and the flash error I get is this "Invalid payment or order. Please review.".
I don't know if my gateway is returning the error or Craft.
How do I know what is the error especifically?


texts: frontend editing, show selected category

texts:
I have this in my edit form

{% set categories = craft.categories.group('jobCategory') %}
    <label for="fields[jobCategory]">Job Category:</label>
    <select id="jobCategory" name="fields[jobCategory]">
        {% for category in categories %}
            <option value="{{ category.id }}">{{ category.title }}</option>
        {% endfor %}
    </select>

but can't for the life of me, show select as 'selected' for the category the entry belongs to.

Missing something simple I'm sure.


texts: Can I extend entries listing views (currently or in the future)?

texts:
Is there a way to show custom columns in the backend with entries listing views? Or can it be a feature in the future?
For example: show category as a column in the news overview in the backend


texts: Dedicated channel for news? or a channel for blog with a news category?

texts:
A clean installation of Craft includes a 'News' channel which has confused me slightly. Would it not be better to have a 'Blog' channel with a 'News' category?

What is the advantage to having a dedicated 'News' channel?


texts:
I want to create an array of all SKUs on Craft Commerce. The end goal is to create a plugin that only applies Sales to certain variants. It does this by  checking the Sale's description for any mention of SKUs and comparing this against the list of all available SKUs.

I thought this would do the trick…

$allvariants = craft()->elements->getCriteria('Commerce_Variant');
$allskus = $allvariants -> sku;

But it doesn't appear to work. The full code of the plugin is…

craft()->on('commerce_sales.onBeforeMatchProductAndSale', function($event){
    $sale = $event->params['sale'];

    $allvariants = craft()->elements->getCriteria('Commerce_Variant');
    $allskus = $allvariants -> sku;

    if (stripos($sale->description, 'only') === false) {
       return; /* do nothing, and let the sale match as it normally would, because the sale does not have 'only' in the description. */
    } else {
        if (stripos($sale->description, $allskus) === false) {
            $event->performAction = false; /* since this SKU is not in the description string, then don't apply this discount */
        }
    }
});`

(Full credit to @luke-holder who wrote the plugin to do this for Discounts)


texts: Using Craft for publishing an online magazine

texts:
I was wondering if Craft is suitable for publishing online magazines. I was thinking about using a new structure for every issue/release. And entries for the actual content of an issue.

Is this the way to go? And does it affect Craft's performance?

Thnx


texts: Moving to another database: "Specified key was too long"

texts:
I am attempting to move the database from my local machine running MySQL 5.5.38 to my webhost running 5.1.70. However when I do so I get the following error on at least two tables. I am using a MySQL export/import process.

  #1071 - Specified key was too long; max key length is 1000 bytes

Does anyone have any idea how I might overcome this problem, or what is causing it?


texts: Displaying content defined by radio button in admin panel

texts:
I want to let my customer decide if they want a 2 or 3 column page so I made a radio button but now I need to show different content if they select one of them but I cant get the syntax right.

{% if entry.column.contains ('two') %}
   content here for two columns
{% endif %}

{% if entry.column.contains ('three') %}
   content here for three columns
{% endif %}


texts: List all entries in a section filtered by given category groups

texts:
I've got a section called 'web development' and there are four categories that apply to it. Three can be grouped together as 'original content' and one is a link list to external third party content.

I'd like to split my entry archive list such that one group lists all entries in the Web Development section that don't belong to the 'external' category (there will only ever be one 'external' category, but I may make new categories that apply to 'original content' so I don't want to hard-code the categories).

After that I'd like to loop through again but only listing entries that do belong to that 'external' category. For each entry I'd like to spit out which category it belongs to as well as the entry title and date.

I can't wrap my head around how to do this, I'm not sure I'm groking how to use relations. Or would I be better to create nested categories rather than trying to group them 'after the fact'?

EDIT: went with making categories and sub categories, but still can't get things to work!

{% set originalContentCategory   = craft.categories.slug('original-content').find() %}
{% set originalContentCategories = craft.categories.group('global').descendantOf(originalContentCategory).find() %}
{% for category in originalContentCategories %}
    <h3>{{ category.title }}</h3>
    {{ category.synopsis }}
{% endfor %}

This is listing all categories in the group, including the 'original-content' category itself. What am I doing wrong?


texts: How to use form.handle in Custom field.html

texts:
I've created a custom field.html which is working fine when I manually specify the formHandle for use with submittedEntry as mentioned in the docs:

{% set ourForm = craft.sproutForms.form('formHandle') %}
{% set submittedEntry = craft.sproutForms.getEntry(ourForm) %}

However, I need to be able to have a dynamic formHandle in the field.html as I am using the same file for an infinite number of forms. This means I cannot manually specify the formHandle as it throws the below error (as the form methods for Form A won't exist in Form B)

Craft\SproutForms_EntryModel and its behaviors do not have a method or closure named "fieldNameFormB".

Is there any way I can pass form.handle from form.html into field.html so that I can use the below code, or is there another method by which I'm not forced to manually specify the form?

{% set ourForm = craft.sproutForms.form(form.handle) %}
{% set submittedEntry = craft.sproutForms.getEntry(ourForm) %}


texts: Where should PHP file of custom widget be in?

texts:
I would like to develop my custom widget as this document in Craft 3.
https://docs.craftcms.com/v3/extend/widget-types.html#registering-custom-widget-types

However, it does not tell me where the PHP file should be in. I suppose it is not under vender/craftcms, because it would be deleted by Craft update. I wonder if you could tell where.


texts: How to save Entries to an entry? (non-plugin)

texts:
I've got a 'booking' channel and an 'event' channel setup. Through the frontend, I need the logged in user to be able to submit a saveEntry form on the frontend which saves a new entry in the booking channel. The booking channel has two fields, both Entries fields. The first field is a relation to one user (the logged in user), and the second field is a relation to a single entry in the events channel.

When I submit the form, the entry is being created in the booking channel, both both Entries fields are blank. How do I make it save the related entries? Can't find any documentation on it.

Existing code:

Summary

<form method="post" action="" accept-charset="UTF-8" class="custom">
    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="events/{{event.slug}}">
    <input type="hidden" name="sectionId" value="18">
    <input type="hidden" name="enabled" value="1">
    <input type="hidden" name="fields[userBooking]" value="{{user.username}}">
    <input type="hidden" name="fields[eventBooking]" value="{{eventID}}">
    <input type="submit" value="Confirm Booking">
</form>

Short version: How do I save a related entry through a frontend form?


texts:
Some similar posts on here already but I'm still struggling. My code looks fine as far as I can tell? Page just reloads with no changes to the email (other fields change fine). I'm missing something right?

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data" class="js-validate">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="users/saveUser">
<input type="hidden" name="redirect" value="{{ craft.request.url ~ '/saved' }}">
<input type="hidden" name="userId" value="{{ currentUser.id }}">
<input type="hidden" name="password" value="{{ currentUser.password }}">

{{ "My Profile"|translate }}

        {{ "First Name"|translate }}*
        <input type="text" name="firstName" id="firstName" placeholder="{{ "First Name"|translate }}" value="{{ currentUser.firstName }}" required>

        {{ "Last Name"|translate }}*
        <input type="text" name="lastName" id="lastName" placeholder="{{ "Last Name"|translate }}" value="{{ currentUser.lastName }}" required>

        {% if currentUser.unverifiedEmail %}

{{ "Email verification pending"|translate }}

{{ "We sent a verification email to"|translate }} {{ currentUser.unverifiedEmail }}. {{ "Until this email is verified, we’ll continue to use your previous email"|translate }} ({{ currentUser.email }}).

        {% else %}
            Email*
            <input type="email" name="email" id="email" placeholder="{{ "Email"|translate }}" value="{{ currentUser.email }}" required>
        {% endif %}

        {{ "Town/City"|translate }}
        <input type="text" name="fields[userTownCity]" id="userTownCity" placeholder="{{ "Town/City"|translate }}" value="{{ currentUser.userTownCity }}">

        {{ "Phone Number"|translate }}
        <input type="text" name="fields[userPhoneNumber]" id="userPhoneNumber" placeholder="{{ "Phone Number"|translate }}" value="{{ currentUser.userPhoneNumber }}">

<input type="submit" value="Save Changes" class="button button--fw">


texts: Craft 3: Cache element query or variable assignment

texts:
Is it possible to cache a variable assignment and/or an element query with TWIG in Craft 3? With Yii2 this is possible, but is there a wrapper to TWIG?

2 use cases:

{% set entries = craft.entries.someThingVerySlowHere() %}
{% set myObject = customVerySlowTwigFunction(...) %}

Why would I want to do that? Let's assume I have 2 blocks in my page, both make use of the variables assigned above, then I can not cache this within the block itself (where the {% cache %} tag belongs, unless I assign/query twice.


texts:
Is there somewhere documented on what field handles are reserved? Would be great to have this as a resource here, especially for plugin development.

Edit: A good place to start would be https://github.com/craftcms/cms/tree/master-v2/src/records/FieldRecord.php#L24


texts: I have an entry which has a category field 'productCategory' and the chosen category is a nested one (3 deep), I want to output the category and where it's nested, but by using the field's name: {{ entry.productCategory.one() }} I get the parent category only, because of .one() I guess, if I use without .one(), then I get a tonne of queries displayed, so I'm not sure how to even approach displaying the actual nested category like a breadcrumb trail. I can display the categories as a nested navigation, but for now I want the entry's chosen category, any ideas? Thanks


texts: Filtering a Matrix block for future dates

texts:
I'm struggling with filtering future dates in a Matrix block that contains a date field.

I would like to display 'Open' or 'Closed' as the result of a condition checking if the value of matrix rows is today, but I only want to run the condition against future dates in the matrix block.  Past dates should be ignored.

In all examples I have seen, the search logic is at declared at the entries-level, but this is a matrix block and I can't get the two to connect.

My code...

{% set closed = craft.block('closedDates')
    .type('closedDate')
    .date('>=' ~ today)
    .all() %}
{% for block in entry.closedDates.all() %}
    {% if today == closed %}

Closed

    {% else %}

Open

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

The (matrix) field = closedDates, the block type = closedDate, the field = date.

I prefer a matrix field so I have only 1 entry.

Would appreciate any suggestions.


texts: My new pages appear with Sorry, we couldn't find the page you were looking for

texts:
I am adding new entries to my site and following the exact same blueprint as the rest of my pages.

However I cannot make any edits to the the new pages and when I attempt to preview them it appears: Sorry, we couldn't find the page you were looking for.

Can you help please?

Best,
Jack


texts:
Not sure what is happening but

{% set searchQuery = craft.request.getParam('q') %}

Does not seem to be working at all on a different server than staging. Anyone seen this before? Any ideas what could be preventing getParam from working? Here is what the end of my url looks like with the param: results?q=test

I then later try to display the search parameter like.

Search Results {{searchQuery}}

But it only displays Search Results leaving the parameter empty... and my search results seem to be returning everything since it is basically doing a wildcard search since I'm using this below to query the matching results...

{% paginate craft.entries.search(searchQuery).order('score').limit(10) as entries %}

Everything works as expected on staging server.


texts: How can you return elements between two values?

texts:
I my be in a bit of a "wood for the trees" situation but how is it possible to return elements based on a custom field being between two supplied values.

For example returning users based on a number field. Let's say the number field is between 1 - 100 and I want to return users that have between 5 and 10 selected.

I could do it like the following

$users = craft()->elements->getCriteria(ElementType::User, array("customNumberField"=>array(5,6,7,8,9,10))->find();

However that sets OR

I know that you can use parameters eg "customNumberField"=>"<= 10" but obviously specifying that key twice causes it to be overwritten.

You can also specify an array with the parameters (avoiding the overwriting) like so

 $users = craft()->elements->getCriteria(ElementType::User, array("customNumberField"=>array(">= 5", "<= 10"))->find();

But again this just creates customNumberField >= 5 OR customNumberField <= 10.

Is it possible to use the array as above but tell it to use AND instead of OR?

Am I on the right track or way off?


texts:
Is it possible to use custom environmental settings with Craft?

I have separate web services that I use in production and development environments. I would like to programmatically point to the appropriate service based on my environment. If I am in development, I should always point to the dev service...production...to the production service.

The documentation leads me to believe that I can only use the settings that Craft provides.

How can I use custom environmental settings within Craft?


texts:
My IDE knows about craft() from an autocomplete and code validation point of view, but it knows nothing about the plugin services that have to be accessed in this way.

Any suggestions on how this could be improved to aid with easier development? Is it an IDE issue, or perhaps a Craft 3 feature request?


texts:
Using Sprout Forms in conjunction with Amazon S3. The file is being uploaded to the S3 source, however it fails to send when viewing the Craft log.

[error] [application] Email error: Could not access file: /home/me/me.example.com/craft/storage/runtime/assets/sources/8540.txt

It appears that the file 8540.txt (named differently) is stored on Amazon S3, but it does not exist in the runtime/assets/sources/ directory. Any idea why the files for images successfully send and are properly created in the runtime/assets/sources/ directory but any other file type i.e. pdf, doc, txt, the server does not create the file and the email fails to send because the file does not exist.

Is this a server configuration or a Craft configuration?


texts:
I am trying to import some categories from a CSV into Craft entries (a categories field). Everything else imports ok apart from the categories

I have created the categories in admin with the same name as the CSV categories but when I import nothing gets selected.

I have the categories formatted in one column in the CSV seperated with a comma .e.g "Branding,Marketing,Design," (I read somewhere this is how it can be done).

Any ideas anyone?

Thanks
Malcolm


texts: Creating a calendar event from within a plugin (stuck on saving)

texts:
I'm trying to create an event from within a plugin. I've come up with the following:
$event = new Event(); // Solspace\Calendar\Elements\Event;
$event->authorId = 1;
$event->calendarId = 5;
$event->name = 'Hello name';
$event->title = 'Hello title';
$event->startDate = new DateTime();
$event->endDate = new DateTime();
$event->allDay = true;

But I don't understand how to actually save the event (e.g. $event->save()). Am I on the right track or completely off? I couldn't find anything on this in the docs.


texts: Is it possible to use template tags within an entry? Specifically, I'd like to use Globals I've set up within an entry, so I can manage a brand name globally.


texts: I'm using Records to create some new tables for use by my plugin. I now need to add some initial data to one of the these tables. What's the best way of accomplishing this on install?


texts: Does the cache tag behave differently for Mobile vs Tablet vs Desktop?

texts:
Are different cache saved for Mobile / Tablet / localisations or do we have to take care of this?

I.e. if i use:

{% if craft.request.isMobileBrowser() %}

will the response be cached for desktop users as well?


texts: How can I make a SmartMap field required on a user profile page?

texts:
I am using Craft 2.5 (Beta) along with the fantastic SmartMap plugin. I have a user registration page that I am using the SmartMap field with like this:

twig

...

        This field is required.
         Street Address

    <input type="text" id="address" name="fields[address][street1]"
    class="form-control"
    placeholder="Street Address"
    {%- if account is defined %} value="{{ account.address.street1 }}"{% endif -%}>
    {% if account is defined %}
        {{ errorList(account.getErrors('address.street1')) }}
    {% endif %}

...

I have designated the field be required in the CP, yet I'm not seeing the "Address cannot be blank" message.

I do get the error message for a default field type:

twig

        This field is required.
         Home Phone

    <input type="tel" id="homePhone" name="fields[homePhone]"
    class="form-control"
    placeholder="Home Phone"
    {%- if account is defined %} value="{{ account.homePhone }}"{% endif -%}>
    {% if account is defined %}
        {{ errorList(account.getErrors('homePhone')) }}
    {% endif %}

The address fields are getting re-populated if there is an error somewhere else on the form, so I know I'm at least talking to it - I just haven't been able to find the right combination

{% if account is defined %}
    {{ errorList(account.getErrors('athleteAddress.street1')) }}
    {{ errorList(account.getErrors('athleteAddress[street1]')) }}
    {{ errorList(account.getErrors('account.athleteAddress.street1')) }}
    ...
{% endif %}

EDIT

I think I may have stumbled onto something that could be related?

I have a SmartMap field in the CP with the handle of address (as shown above).
On the profile tab of the user account, I have assigned the address field, and have set it to be not required.

Within my front-end registration form, I am attempting to populate the SmartMap fields. I have all of the field names matching the field names within the CP.

fields[address][street1]
fields[address][street2]

...and so on.

However, when I submit the form - which (should) be valid I am getting redirected to the form (page refreshes), the form is fully populated as if there were a validation error, and the user is not saved.

When I look at the log file, I am seeing all of the data, and it looks good so I'm not sure what the error is.

craft.log

...
'fields' =>
    array (
        'address' =>
            array (
                'street1' => '1234 My Street',
                'street2' => '123',
                'city' => 'My City',
                'state' => 'AZ',
                'zip' => '12345',
            ),
         ...


texts: Order entries by a matrix field category

texts:
I have a lot of trouble in understanding the database/model structure and how to work with the query builder.
I tried playing a bit with leftJoins but i cannot seem to make complex queries in craft 3. I would like some help with a query.

The matrix field is as follows:

Entry

audienceTarget(matrix)
audience (block type)

targetName (field type: category)
points (field type: dropdown)

We use this to segment entries for certain users so we can show users that are segmented more relevant entries

Before i'm running the query i have the ids of the audience.targetName i want to favour in a variable let say $mainSegment.

What i am trying to do:

I want to query entries with the default order "postDate" but i like to place the relevant entries first. so all the entries that has the category id i specify must be first.

For example when a user is segmented on targetName(category) with id 2.
I want to favour all the posts that has a block type with segment 2 selected on the matrix in my order by.

I could not find a lot of craft examples with complex queries so it would be very helpful if someone could give me some examples.

Thank you.


texts: Attribute default value is always being saved as an int

texts:
Following block in generateColumnDefinition($config) function in DbHelper.php class is always converting default value to int if it is a numeric value. A numeric value can be a float so this is causing an issue:

if (isset($config['default']) && (is_string($config['default']) || is_bool($config['default']) || is_numeric($config['default'])))
{
    if (is_string($config['default']) && !is_numeric($config['default']))
    {
        $def .= ' DEFAULT "'.$config['default'].'"';
    }
    else
    {
        $def .= ' DEFAULT '.(int)$config['default'];
    }
}

Is there a way that I can override this method? Any help much appreciated.

Many thanks


texts: Get locale entry.title in other languages

texts:
I'm trying to get the locale title (dutch: nl_nl) of an entry, in the english version of the same post. I want to do this so that on hover it shows the English title's Dutch version.

Any help is appreciated!


texts:
When exactly are migrations run?  I wrote a migration that runs and does its job properly if I run it via the command line: yiic migrate up Seomatic but despite the version number and schema number being bumped, Craft doesn’t run the migration automatically`

Instead, my code dies because of a column that doesn’t exist in the db.  Shouldn't the migration be found and run before my plugin's code is?

Here's the version numbers returned by my plugin:

public function getVersion()
{
    return '1.0.5';
}

public function getSchemaVersion()
{
    return '1.0.1';
}

The previous installed version was '1.0.4' and '1.0.0', respectively.  Shouldn't this be enough for Craft to find and run the migration?

The migration is named:

m151225_000000_seomatic_addHumansField.php

...with a class of the same name, and again, it's found and runs properly if manually run it via yiic -- what am I missing?


texts:
I am having the following sections:

1. work (section type: single)
  fields:
    - workList (type: entries from section type workArticles)

2. workArticles (section type: channel)
  fields:
    - workName (type: plain text)

So the first section (work) is an overview page that links to pages of the second section (workArticles). Basically a normal portfolio page.

On my workArticles pages I want to link to the next entry from work.workList. So imagine: my portfolio overview page shows 8 projects, the user clicks on the third entry, the page for the third entry opens, on the bottom of that page I want to link to the fourth entry of the list.

Is that even possible?


texts: DeleteStaleTemplateCaches job getting stuck

texts:
We have only two templates leveraging the cache tag and they both have a construct similar to:

{% extends "_layout" %}

{% block content %}
  {% cache globally using key entry.url ~ "relatedArticles" for 1 hour %}
    ... bunch of relational queries ...
  {% endcache %}
  ...
{% endblock %}

Once or twice a day, the DeleteStaleTemplateCaches get stuck and requires manual "killing".  For example, when this occurs, the craft_tasks table indicates say currentStep 1309 of totalSteps 12800...  Then, "error'ing" the task, and choosing the "Retry task", generate a new job but will say only 670 totalSteps...  and of course it succeeds.  Why is the total steps so much different on retry?

There is no clue in the logs.  Only the logs of the "retried task" that show the steps and its successful result.  Nothing about the stuck task that I killed.

Currently, we have 3 nodes sharing a common file system for all (except most of the "runtime folder") and common database but individual memcached server (one per node).  Craft is configured to use memcached.  Could the issue be that more than one node start the delete task at the same time?  i.e. all try to cleanup the same db table?

Beside this specific problem, I would be very grateful if you could explain how the different caching (data, templates, etc.)  works within craft or indicate where I can find the information. i.e. I'm not clear on what is cached in memcached vs the database, vs file system (if anything).

Thanks.


texts: Freeform is unable to send emails after changing webhost

texts: I have moved a website to a new webhost. Since the freeform ist no able to send any emails for notification reasons or alert reasons. Is there a basic switch or something similar I am missing to enable sending emails?


texts: How to import Category subfields within a Matrix block using FeedMe?

texts:
I'm importing Entries that have a Category field inside a Matrix block. My JSON includes data that I want to import directly to the Category subfields.
Here's a simplified example of my JSON:
{
  "entries": [
    {
      "title": "Thor",
      "matrix": {
        "matrixBlock": [
          {
            "role": "Former member",
            "categoryField": {
              "category": [
                {
                  "title": "Avengers",
                  "code": "AVG",
                  "headquarters": "Avengers Mansion"
                }
              ]
            }
          },
          {
            "role": "Member"
            "categoryField": {
              "category": [
                {
                  "title": "Guardians of the Galaxy",
                  "code": "GOTG",
                  "headquarters": "Knowhere"
                }
              ]
            }
          }
        ]
      }
    },
    ...
  ]
}

In FeedMe, when I select <matrix/matrixBlock/role> and <matrix/matrixBlock/categoryField/category/title> they are imported correctly to the Entry.
But, when I click the switch in FeedMe to import "Element fields" aka subfields for the Category, and select <matrix/matrixBlock/categoryField/category/code> and <matrix/matrixBlock/categoryField/category/headquarters> the data does not import correctly. What happens is that the data from the first matrixBlock is used for all subsequent blocks.
So the Category data ends up as:
{
  "title": "Avengers",
  "code": "AVG",
  "headquarters": "Avengers Mansion"
},
{
  "title": "Guardians of the Galaxy",
  "code": "AVG", //WRONG
  "headquarters": "Avengers Mansion" //WRONG
}

Has anyone out there managed to do this successfully or know what syntax should be used?


texts:
When I upload animated gif assets to a Craft site, they end up static and corrupted, as so:

(Original here.)

My guess is that what's displayed is the last frame of the animation (which only contains pixels changed from the penultimate frame).

Other image resizing functions work. The site is hosted on a dedicated Ubuntu box with PHP 5.3.10. Here's what phpinfo() says about my ImageMagick/Imagick install.

imagick module version => 3.1.0RC1
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator
ImageMagick version => ImageMagick 6.6.9-7 2014-03-06 Q16 http://www.imagemagick.org

Calling convert source.gif -resize 123x123 dest.gif works on the server—the issue seems to lie in the PHP call to ImageMagick rather than in the installation itself. Answers to this question indicate that GIF issues disappear with the proper configuration, but I fail to see what's lacking in this particular setup.


texts: Loading assets cross-domain with SSL or non-SSL option

texts:
Here's a unique situation. I have three websites. All assets are stored at the domain of the first site:
domain.com/files/*
The first two sites run completely over SSL. No problem.
The third site needs to have the option to load either over SSL or non-SSL. This is entirely thanks to the authoritarian governments of countries like China, which may block a site, no matter the content, if it can only load over SSL.
In my config.php, I have this:
'@assetBaseUrl' => 'https://site1.domain.org/files'

If I change this to exclude https://, Craft does not create proper URLs for images and files. I also tried //site1.domain.org, but that doesn't work either.
Is there some setting I can use for @assetBaseUrl that will work across the board?


texts: Does each MatrixBlockModel in an entry have a unique dateUpdated?

texts:
After doing some experimentation in looping through MatrixBlockModel, it seems that even though each block has a dateUpdated property, this value is never unique to each block, but is shared between all blocks in the Entry.

{% set timeLimit = now | date_modify("-2 min") %}
{% for block in entry.blocks %}
  {% if block.dateUpdated >= timeLimit %}

    {{ block.dateUpdated | date(dtFilter) }}

  {% endif %}
{% endfor %}

If the entry has 6 blocks, and I update one of those blocks and save, the same date will output 6 times for about 2 minutes, then nothing will output.

Can anybody confirm this?


texts: Changing the frontend sorting according to different fields

texts:
I am creating a site that has a list of events that I need to be able to sort by different fields. I know how to do it statically in my templates but I want to enable it in the front end.

For the example, each event will have three different sorting fields - 'Teacher', 'Country' and 'Event Date'. The initial order will be according to date but I want that the user will be able to choose from an option button a specific value (with all the available options of this field) and to see only events from a specific teacher or specific country.

I would appreciate any help on how to start such a thing. Again, I know how to create static sorting in the templates but not live one being done in the front-end...


texts: Pass 'not' category.id to relatedTo in Craft

texts:
I have a search page that filters with these params:

{% set results = craft.entries({
    section: 'properties',
    price: range,
    search: query.location,
    relatedTo: status,
    order: priceDesc
}) %}

The status variable needs to be set to a 'not' this category (or an array of all the other categories), but I can't seem to phrase my param correctly.

I've tried both the string and array method with category ID's, like this:

relatedTo: ['not', category.id]

And this:

relatedTo: ['or', category1.id, category2.id, ...]

Advice?


texts: 302 redirect when updating the cart via Ajax using Craft Commerce 2

texts:
I'm working on a site that has recently migrated from Craft v2 with Commerce v1 to Craft v3 with Commerce v2.

Using Commerce v1 I was able to update the cart via Ajax and get a data object with the state of the cart as a response.

After updating to Craft Commerce v2 the ajax requests fail, returning Status 302 - Redirect instead of the data object, although the changes to the cart are successful.

I can add one or more products or change their quantity via Ajax, however, I need the data object in order to properly update the state of the cart without reloading the page.

I'm running Craft v3.0.10.2 with Craft Commerce from dev-develop commit 1db58f6 on a machine running PHP v7.1.12
The action I'm using is commerce/cart/update-cart
The method of all requests is POST
Any form data should to be ok since the cart updates succesfully
All requests are sent with the following headers:

Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest

I'm I missing anything new in CC2? Any help would be much appreciated.


texts: Adding Categories navigation to show certain entries

texts:
I'm abit lost as to how to structure my FAQ page.
I have a single FAQ page that pulls in every FAQ post, these posts come from the FAQ Entries channel.
But
On the single FAQ page, how do I add a navigation that only shows certain FAQ Entries using categories?


texts: Can I add a billing address while updating the cart?

texts:
I'm designing a donation form right now for what will be a Craft Commerce site, and I want to collect the donator's billing name, address, etc in the product form which adds the donation to the cart. Will commerce/cart/updateCart accept billingAddress parameters when posted?

(I would simply test this, but I've not even started the build phase yet, and don't want to include the address fields on the donation form in my design if it won't be possible.)


texts: Is it possible to ask a user arbitrary, changing questions at checkout with Craft Commerce?

texts:
Craft Commerce allows us to have one set of custom Order Fields associated with a checkout process. I have a situation where we are selling tickets to a yearly event and I need to ask two questions of each registrant that change from year to year. For this example, I'll present the following two questions, but it's possible that the number of questions and type of question changes from year to year:

Year 1:
- Will you attend the opening reception on Friday?
- Will you attend the lunch reception on Saturday?

Year 2:
- Will you attend the opening reception on Thursday?
- Will you attend the lunch reception on Friday?

It seems custom Order Fields will not easily solve this use case with an ideal workflow for the content admin for two reasons:

The questions need to change from year to year, which would require a developer update the Order Fields layout
Even if a developer did go in and change the questions to be the ones relevant to the year, they'd be breaking the data model of the previous year rendering past data inaccurate and useless (if someone wished to query it for whatever reason)

The ideal solution would allow an admin to:

Create a product for a new year
Customize the arbitrary questions they need to ask each user who checks out (The questions for the Order would ideally be associated with the Product Field Layout, not the Order Field Layout)
Have the option to query accurate data (questions and responses) for all customers of a product for a specific year

Before I go down the road of custom development, are there any supported or existing options that address the use case described above?


texts:
I have a list of year from a form field, not in consecutive order. (ES: 2008, 2010, 2012)

I have built an url in this way: q=&year[]=2008&year[]=2010 to get all the records of years 2008 and 2010.

I can get the array from url, but was unable to build a query by year on the entries section.

There is a way to query over multiple years?


texts: Add Section Name to SEOmatic Title Field

texts:
I have an index page for a Section which lists out the entries.

As this index template doesn't have a title field associated with it how do I get the Section name in the SEOmatic's SEO Title Source?


texts: Two plugins contain the same function name so they're conflicting

texts:
I'm trying to use a filter function from a plugin, but it turns out two plugins that I have installed have the same function name and the wrong one is getting called. For now I edited the vendor files to rename the function, but I don't want that to be my final solution in case I want to upgrade the plugin later.

What is the best way to go about circumventing this type of conflict between two plugins?


texts:
I am trying to pull entries that match a date criteria. Any ideas why this is not working?

{% set entries = craft.entries({
section: 'leads',
lastAssigned: '("now"|date_modify("-3 days"))'
}) %}

I get the following error.

Fatal error: Call to a member function getTimestamp() on a non-object in .../craft/app/helpers/DbHelper.php on line 597


texts: How to use the Element API endpoint without wrapping it in data object

texts:
By default the Element API plugin all endpoints in a data object like this:

{ "data": [ { "key" : "value", "key2": "value2" } ]}

But i don't want to wrap this in the data object but like this:

{ "key" : "value", "key2": "value2" }


texts:
I have to make a website that has a single craft installation and one database.

Now the site is for a company that owns several garages which should have their own subsite on a subdomain. It should all be multilingual and those subsite/subdomains would have single pages as well as channels for used cars or new cars.

Now what I'm wondering is how to set up those subsites.
Their url structure should be like http://subsite.domain.com/{lang}/{single-page} or http://subsite.domain.com/{lang}/blog/{slug}

I was thinking maybe using a structure per subsite to keep all the content uncluttered in the dashboard and creating a channel for each subsite blog, used cars section and new cars section.

But I'm not really sure what the best way to set this up would be or even how to point the pages/channels to a subdomain.

Would I have to create new multi-environmont configs for each subsite or is there a way to do this automatically or maybe that's not even necessary?

Each subsite will also have users who can only edit that specific subsite. (Maybe something to keep in mind when structuring the site)

Here's a  little diagram that might help show what I'm looking for:

Of course I'll be using craft pro for the languages and users.

Any help and tips would be much appreciated.
(Feel free to ask for more information if necessary)

Thank you very much in advance


texts: How Do I group entries by Category and retain fixed Category Order?

texts:
I found a solution to grouping entries by category here which is working perfectly but I need the categories in the order they were arranged in the categories tab in the Admin panel.

Currently, the categories are outputting in the order they were entered but they've been re-ordered since then.

I tried using .fixedOrder(true) in a few places but nothing good happened. This is the current code:

{% set entries = craft.entries({
  section: 'projects'
}).find() %}

{% for category, catEntries in entries|group('projectCategory.first().title') %}

{{ category }}

        {% for entry in catEntries %}

{{ entry.title }}

        {% endfor %} {# -- // for entry -- #}

{% endfor %}{# -- // for category -- #}


texts: What are the cache options available to a Craft installation?

texts: Reading the Craft docs and other related questions on Stack Exchange there seems to be a lot questions about caching, what it does under different scenarios and how to best utilize it.  Is there an overview of all of the different caching options available in a Craft installation?


texts:
I'm having a problem getting my asset URLs to print properly in templates. The site is using a multi-environment configuration (dev/stage/live) with localized content (en/es/da) and shared assets. Here are the config and settings.

In the config file:

define('SITE_URL', URI_SCHEME . $_SERVER['SERVER_NAME'] . '/');
define('BASEPATH', realpath(CRAFT_BASE_PATH . '/../') . '/');

return array(
    '*' => array(
        // common config settings
    ),
    'site.craft.dev' => array(
        'siteUrl' => array(
            'en' => 'http://site.craft.dev:8888/',
            'es' => 'http://site.craft.dev:8888/es/',
            'da' => 'http://site.craft.dev:8888/da/',
        ),
        'environmentVariables' => array(
            'baseUrl'  => 'http://site.craft.dev:8888/',
            'basePath' => BASEPATH . 'http/',
        ),
    ),
    'stage.site.com'  => array(
        // etc
    ),
    'site.com'  => array(
        // etc
    ),
);

In the CP:

I have an 'Images' asset source defined with:

File System Path: {basePath}assets/img/
URL: /assets/img/

I have a 'printImage' asset field defined with:

Upload Location: Images (selected in dropdown); prints (in field)

Uploading images through the CP works great, and images go to the correct folder, and are viewable in the CP.

In the template (and here is the problem), when I request the image url using {{ printImage.url }} it outputs:

http://site.craft.dev:8888/prints/imagename.jpg

when it should be:

http://site.craft.dev:8888/assets/img/prints/imagename.jpg

Also, when I switch to another language it outputs:

http://site.craft.dev:8888/es/prints/imagename.jpg

It seems to be missing the portion of the path defined in Settings:Assets:Sources:'Images', and also is including the localization prefix.

All other paths and URLs in the site are working perfectly. Anyone have any ideas where I'm going wrong with assets? I guess I don't understand how it's crafting the asset URLs. Should I be defining an 'assetsPath' in my environment variables?

Thank you!


texts:
I have a Craft CMS installation in which there will be other data imported into the db (via Cronjob). It's data from a Weatherstation which will be displayed without further editing in the Control Panel.

Is it possible to display this data via Twig bypassing the Control Panel all-together?

something like:

{% for entry in special.db.section('xyz') %}
  {{ entry.value }}
{% endfor %}

My first thought would be to do this via the Element API Plugin and then use JavaScript to display this data. But maybe that's not necessary?


texts: Is it possible to create a custom field listing all enabled locales?

texts:
We have a multilingual site with about 30 different locales and about 5 pages of content for each. We're using Craft as a content API for the editors to manage content.

Some of those locales share the same language - for example there's USA (English), Singapore (English) and UK (English).

It's a big hassle for them to have to copy the English text into 3 different localisations.

So I'd like to add a custom field at the top of each entry edit page to say "Inherit from another locale?" and provide a dropdown list of all the locales which are currently available and enabled in Craft.

Should this be possible? Does anyone have any code samples of this being done? Is it likely to present any issues if we attempt to do this.

Tips appreciated!


texts: Related Items in a Category not Appearing in Results

texts:
I am still having a problem looping through related posts.

I get zero, not even the HTML. And there are no Craft template errors. There are plenty of entries that were assigned the same market, so there should be something.  AND this exact approach worked perfectly before !@$!@#!

Similar Projects

{% set relatedMarket = entry.market.first() %}
{% set relatedEntries = craft.entries.section('posts').relatedTo({ targetElement: relatedMarket, field: 'market'}).id('not'~entry.id) %}

{% for relatedEntry in relatedEntries %}

 Entry title goes here. {{ relatedEntry.title  }}

{% endfor %}

I double checked.  My entry section handle is posts. The handle for the posts entry type is notifications. The category group handle is markets.  The category entry field handle is market.  I included the entry type and category group handles just in case I am missing something.


texts: How to Upload Multiple Assets Using Frontend Form

texts:
I'm trying to create a more interactive experience to upload moultiple images on a frontend entry form.

Things I have done:

I have implemented the code here: https://docs.craftcms.com/v3/dev/examples/entry-form.html
I also know about https://docs.craftcms.com/v3/assets-fields.html#templating
I tried to implement this: Does anyone have a working example of frontend form with multiple file upload, drag & drop etc?
I have also looked into: https://github.com/fruitstudios/craft-uploadit  but the plugin seems unfinished.

Item number 3 seems the closest to what I am looking to do, but it's for CraftCMS 2 and I have tried to update the code for CraftCMS 3 with no luck. Specifically there seems to be an issue with {{ url(actions/assets/uploadFile) }}

Ideally I'm trying to integrate either dropzone.js or jQuery Upload into a frontend form to create entries with upload assets (images) that a user can add to and re-arrange.

Any ideas / thinking greatly appreciated.


texts: Any reason why {% requirePermission 'editEntries:1' %} would stop working within the past week or so?

texts:
This worked fine last week when the site was in development:

{% requirePermission 'editEntries:1' %}

We made the site live a few days ago. I dont know if its related, but when I now go to pages with this on, I am getting

HTTP 403 – Forbidden – yii\web\ForbiddenHttpException
User is not permitted to perform this action

I have doubled checked all settings, they are still the same. The logged in user getting this message is in a group that is allowed to editEntries for section 1.

Thanks


texts: How to duplicate a page within a Structure?

texts:
Most of the pages in my Craft site are contained in one big Structure. There are a couple of pages whose content needs to exist in two locations within the structure. I'm not sure how best to do this.

I could probably hack something together with a bespoke route that loads a template which sets variables related to the navigation, then loads the content from the Entry defined in the CMS... but that seems like a horrible hack, and at that point I'd start to think I should just manually copy and paste the content between the two Entries in the CMS.

Any other ideas? Ideally I'd like it to be manageable in the CMS so it's not too hidden away from the client.


texts: Is cache condition necessary to stop HTML being inserted into database cache?

texts:
We currently use cache tags with a condition referencing the cache config setting:

{% cache for 1 hour if craft.config.cache %}

Is the condition necessary to stop HTML being inserted into the database cache?


texts: Can I output custom or specific data (Not related to an elementType) on Element API?

texts:
For example, an endpoint to retrieve all the languages available on the website

'endpoints' => [
   'languages' => function () {

            $sites = Craft::$app->getSites()->getAllGroups();

            $languages = Craft::$app->getSites()->getSitesByGroupId($sites[array_search('Languages', $sites)]['id']);

            Craft::dd($languages); // output this in a nice json

            return $languages;
        },
    ]

Or an endpoint to retrieve all the available sections

    'sections' => function () {

            $sections = Craft::$app->getSections()->getAllSections();

            Craft::dd($sections); // output this in a nice json
    },


texts: Routing within a single page app integration

texts:
I'm using Craft as the backend for an app and VueJS along with Element API to deliver the content.

Everything so far is working sweet, except when I try to pull up the detail page for an entry because in Craft, the route doesn't exist.

To be clear, my main listing page and links work but if I try to visit http://localhost/slug/id directly, I get a 404.

I know within the context of something like Laravel, I could do

Route::any('{all}', function () {
    return view('index');
})
->where(['all' => '.*']);

Is there something similar I could do with Craft?

I should add I have user registration and aspects that vue can't handle because Craft doesn't have a full crud api.


texts: Is there a way to schedule a draft of a entry to go live?


texts: How do I change a user's password programmatically in a plugin?

texts:
I'm new to Craft and (attempting to) create a plugin so that I can import existing users from CSV.

I'm referencing this method:

https://docs.craftcms.com/api/v2/craft-usersservice.html#method-changepassword

In my function, I'm using the following code:

$user = craft()->users->getUserById(6);
$user->newPassword('mynewpassword123');
craft()->users->changePassword($user);
craft()->users->saveUser($user);

Am I completely misunderstanding what this is supposed to do?


texts: Asset saves in Draft but not showing up in Preview - help!

texts: I have saved an asset to the Assets tab in Craft and successfully uploaded it into an article I'm creating. I deleted the picture it was replacing, and then uploaded it. It saves in draft, but doesn't show up when I look in the preview. All other stuff (like copy I wrote) DOES show up, so I know it's an asset issue. Please advise, thank you!