texts: How to set a dynamic title in plugin on entry save?

texts:
I have a section of events and am trying to automatically set a readable title on the event entry in the CMS ( such as Jan 5 - 12, 2015 or Jan 5, 2013 - Jan 10, 2016 ). I realize I can do this via a Dynamic Title on the entry type, however my twig logic gets cut off, it seems it won't fit in the allowed character limit (220 ?). My twig code looks like:

  {% set start = object.startDate %}
  {% set end = object.endDate %}

  {{start|date('F j')}}
  {% if end %}
    {% if start|date('Y') == end|date('Y') %}
      {% if start|date('F') == end|date('F') %}
         – {{end|date('j, Y')}}
      {% else %}
        – {{end|date('F j, Y')}}
      {% endif %}
    {% else %}
      {{start|date(', Y')}} – {{end|date('F j, Y')}}
    {% endif %}
  {% else %}
    {{ start|date(', Y') }}
  {% endif %}

I have made numerous attempts at shortening this to fit in the character limit, below is my best attempt:

{% set s,e = object.startDate,object.endDate %}{{s|date('F j')}}{% if e %}{% if s|date('Y')==e|date('Y') %}{% if s|date('F')==e|date('F') %}–{{e|date('j, Y')}}{% else %} – {{e|date('F j, Y')}}{% endif %}{% else %}{{s|date(', Y')}} – {{e|date('F j, Y')}}{% endif %}{% endif %}

But it's still getting cut off. Perhaps there is an easy solution for this via some Twig magic?

I then moved to try to do this within a plugin. I put this in my main plugin class:

public function init()
  {
      craft()->on('entries.onSaveEntry', function(Event $event)
      {
          $entry = $event->params['entry'];
          if($entry->section['handle'] == 'dates')
          {
             $start = $entry->startDate;
             $end = $entry->endDate;
             $fullTitle = $start . " - " . $end;
             $entry->setContentFromPost(array(
               'title' => $fullTitle,
             ));
          }
      });
 }

I am fairly certain this code is running on save, however my title isn't updating. Any idea what I'm missing?

I have turned off dynamic titles for this section in the entry settings to ensure that wasn't interfering.


texts: Looping on the User Field added to Entry

texts:
I am fetching the fields of an entry in a block but can not draw through a user field named as eventHost.
I get error 'Variable "name" does not exist.' What is wrong with my loop?
{% set webinar = block.webinar.all() %}
{% if webinar is not empty %}

{% for entry in webinar %}

        {% set url = entry.url %}
        {% set title = entry.title %}
        {% set desc = entry.previewDescription %}
        {% set img = entry.previewImage.one() %}

        {% for expert in entry.eventHost %}
            {% set name = expert.name %}
            {% set avatar = expert.avatar %}
            {% set job = expert.personJobTitle %}
            {% if expert.linkedInProfile %}
                {% set linkedin = expert.linkedInProfile.url %}
            {% endif %}
        {% endfor %}

{{ title }}

{{ name }}
{{ job }}

{% endfor %}

{% endif %}


texts: Find one section in a for loop based on url

texts:
I am new at Craft CMS so have patience with me (and my English).

I don't know if I am doing this right, but I have a link (URL) from my index.html, and I want to display the specific content on the _entry.html.

Index.html

{% for entry in craft.entries.section('news') %}

{{ entry.title }}

{% endfor %}

And when I click on that link I want only to display the content related to that entry.url.

If I click the link now, all my entries will show in _entry.html.

_entry.html

{% for entry in craft.entries.section('news').type('news') %}

{{ entry.title }}

{% endfor %}

I just want to show the specific content for that section.

Update:

I tested this and it worked:

{% for entry in craft.entries.section('news').type('news').slug(craft.request.getSegment(2)) %}

But I don't know why?


texts: How should we be setting up product categories/sub-categories?

texts:
New to Craft CMS and currently don't understand the terminology or how things work together in the platform yet.

If I want to set up a category structure like the below in Commerce, how is the best way to achieve this in the backend?

Pets
+++ Cats
+++ Dogs
Fashion
+++ Clothing
+++ Jewellery
+++ Sports

Also using the 'Events' plugin too which has ticket types - should these be used for categories?


texts:
I'm 5 minutes new to Craft and G&T, but my client needs GA installed on their new site.

Any thoughts about how to do this?

Also, general SEO questions: are there SEO plugins a la wordpress that you guys can point me to?


texts: Is there an easy way to loop through all existing values of an entry field and store them in an array?

texts: Looking to loop through and filter based on possible values in a text entry field...I have a text field called storeBanner that has 11 possible values (but could have more). Just need a way to go through every entry and create an array with all possible values.


texts:
Unfortunately I'm still very new to Craft, but I have a question to which I haven't found an answer here or in the Docs or the ones I found don't seem to work: Why doesn't this entry-loop output a picture? Because the image title is output correctly and the transformation medium exists.

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

    {% set image = entry.image.one() %}
    {% if image %}

    {% endif %}

{% endfor %}

thanks for help!


texts: Any plans on adding Imperavi's Article WYSIWYG editor to Craft CMS, like Redactor?


texts: Recommended workflow when developing new websites

texts:
A common workflow for me when building a web page is the following.

I'm getting a PSD-file (Photoshop) from a external advertising agency
Build the site in Webflow and then export to plain html/css/js
Build the site locally in Craft CMS using Textmate
Deploy to dev.customer.com using DeployBot and Github
Send username and password for Craft to advertising agency, they then start to fill the site with content

The problem with this workflow is when the agency in step 5 want changes (new fields, sections).  I don't want to add fields on both localhost and dev.customer.com. And I don't want to temporarily shut down dev.customer.com, export database on dev.customer.com to localhost and then import to dev.customer.com when done (there is often a tight schedule).

How would you do? Does Craft 3 solve this?  If not, maybe me and the agency should work on the same codebase and database. One way is to have a small server locally (which i don't have) turned on 24h and open port 80 from outside so the agency could work in Craft. Another way is to use SSHFS to mount file system over SSH on a remote Linux VPS (which i have plenty of), but i'm not sure how stable this is.


texts:
I have a problem with my page after upload on server. Currently a enabled devMode and while loading it shows

  HTTP 503 – Service Unavailable – craft\web\ServiceUnavailableHttpException

  whatmore:

  vendor/yiisoft/yii2/base/Application.php at line 386 – craft\web\Application::handleRequest(craft\web\Request)

web.log below:

  2018-07-19 07:11:06 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][info][yii\db\Connection::open] Opening DB connection: mysql:host=localhost;dbname=my_database;port=3306;
  2018-07-19 07:11:06 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][profile begin][yii\db\Connection::open] Opening DB connection: mysql:host=localhost;dbname=my_database;port=3306;
  2018-07-19 07:11:06 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][profile end][yii\db\Connection::open] Opening DB connection: mysql:host=localhost;dbname=my_database;port=3306;
  2018-07-19 07:11:06 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][error][craft\db\Connection::open] SQLSTATE[HY000] [2002] No such file or directory
  2018-07-19 07:11:06 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][error][craft\db\Connection::open] SQLSTATE[HY000] [2002] No such file or directory
  2018-07-19 07:11:06 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][info][yii\web\Session::open] Session started
  2018-07-19 07:11:06 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][error][yii\web\HttpException:503] craft\web\ServiceUnavailableHttpException in /path/to/public_html/www/vendor/craftcms/cms/src/web/Application.php:507
  Stack trace:

  0 /home/cluster-sites/3/t/toolmach.co.uk/public_html/www/vendor/craftcms/cms/src/web/Application.php(184): craft\web\Application->_processInstallRequest(Object(craft\web\Request))

  1 /home/cluster-sites/3/t/toolmach.co.uk/public_html/www/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))

  2 /home/cluster-sites/3/t/toolmach.co.uk/public_html/www/web/index.php(21): yii\base\Application->run()

  3 {main}
  2018-07-19 07:11:07 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][trace][yii\base\View::renderFile] Rendering view file: /path/to/public_html/www/vendor/yiisoft/yii2/views/errorHandler/exception.php
  2018-07-19 07:11:07 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][trace][yii\base\View::renderFile] Rendering view file: /path/to/public_html/www/vendor/yiisoft/yii2/views/errorHandler/callStackItem.php
  2018-07-19 07:11:07 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][trace][yii\base\View::renderFile] Rendering view file: /path/to/public_html/www/vendor/yiisoft/yii2/views/errorHandler/callStackItem.php
  2018-07-19 07:11:07 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][trace][yii\base\View::renderFile] Rendering view file: /path/topublic_html/www/vendor/yiisoft/yii2/views/errorHandler/callStackItem.php
  2018-07-19 07:11:07 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][trace][yii\base\View::renderFile] Rendering view file: /path/topublic_html/www/vendor/yiisoft/yii2/views/errorHandler/callStackItem.php
  2018-07-19 07:11:05 [80.55.43.241][-][72baf4994c2e29ee1f32982349aec971][info][application] $_GET = []

  $_POST = []

  $_FILES = []


texts: How do you raise/fake an event so that you can test handlers listening for it?

texts:
We use event integration (native and custom) in a lot of the plugins we build and I was wondering if anyone has come up with a simple way to raise those events at will, without having to follow a specific flow of execution.

For example, if you are listening for entries.saveEntry and don't want to manually save an entry in order for that event to be raised/triggered.

I think it would be nice to have a simple way of doing this and interested in seeing if anyone has found the need for such thing.

With enough patience, one could fake many events and call the service that raises them but I'm sure that there other developer way more clever than me that may have solved this already.


texts: Making multiple pages different with the same template

texts:
Lets say I have four different pages I set up on a channel to have four different directories. ie ... hello/1, hello/2, hello/3, hello/4. But they are all using the same template.

What could an engineer adjust in craft to be different between the four pages vs. not be able to adjust if they can't touch the html template or CSS?


texts: Password should fail on front-end registration form

texts:
Update For anyone else having a braindead moment, registration form errors only display for password when logged out. If you're logged in as admin they won't display.

User posted even though using an empty password. According to this post and this form template an empty password box (or less than 6 characters) should fail and return an error yes?

        Password

        <input id="password" class="form-input" type="password" name="password">
      6 characters or more — keep it secret, keep it safe.

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

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

Screenshots:


texts: Using a Matrix field to create a homepage that shows entries from sections and categories

texts:
I have set up 3 channel types - A, B & C and a Category. Each entry type shares the same pool of categories.
On the home page, I have created a Matrix field (homeSections) with a block type heroSections that has A, B & C in a dropdown (mediaType) and a Category select (homeSection), so I can have "select mediaType A that has Category 1" as an option.
This is what I have so far
{% set entry = craft.entries().section('home').one() %}

{% for block in entry.homeSections.all() %}

    {% switch block.type %}

    {% case "heroSections" %}

        {% for entry in block.homeSection.all() %}

            <h3>{{ entry.title }} {{ block.mediaType.label }}</h3>

            {% set section = block.mediaType %}
            {% set category = entry.slug %}
            {% set entries = craft.entries.section(section).limit(4).orderby('postDate desc').all() %}

            {% include '_includes/listing' %}
        {% endfor %}

{% endswitch %}

{% endfor %}

but I can't figure out how to then filter the results so that the category is applied to the entries returned.


texts: Is there any way to set enable by default a permission on the registerUserPermissions hook?

texts:
When I create a permission using the registerUserPermissions hook I would like everyone, in all user groups have access to that permission. An admin has to take an explicit step to restrict access to that pemission. Something like this:

/**
 * @return array
 */
public function registerUserPermissions()
{
    return array(
        'my-permission' => array(
            'label' => Craft::t('Edit Settings'),
            //****ENABLE BY DEFAULT****
            'enable'=> true
        ),
    );
}


texts: Only layout template being rendered in local environment

texts:
I've just set up a multi-environment install of Craft but am having an issue on my local install under MAMP Pro. Everything seems to be loading fine except for my index template in the root of the 'templates' directory. It extends a _layout.twig template but when I load the site locally, only the layout template is being rendered (ie. my block overrides in the index template that extends it aren't being rendered).

However, this works fine on the remote version of the install.

Any thoughts or help would be appreciated as I'm scratching my head at this point...

Thanks.

Update - here is the code from _layout.twig and index.twig. Pretty straight forward - and these do work expected in the other non-local environment.

_layout.twig

<!DOCTYPE html>
<html lang="en">

<head>

    {% block head %}
        ...head code in here
    {% endblock %}

</head>

<body>

    {% block bodyContent %}
        ...presentational code in here
    {% endblock %}

    {% block footer %}
        ...presentational code in here
    {% endblock %}

</body>

</html>

index.twig

{% extends "_layout.twig" %}

{% set entries = craft.entries.section('homepage') %}

{% block head %}
    {{ parent() }}

    ...additional head code
{% endblock %}

{% block bodyContent %}
    ... presentational code overriding _layout
{% endblock %}

{% block footer %}
    ... presentational code overriding _layout
{% endblock %}


texts: Craft Commerce not sending E-Mails immediately

texts:
I have an e-mail problem at Craft Commerce.
Emails are not sent at the time of purchase.
The e-mail is only sent when you log in to the backend.

I first thought it was a server queue problem. But the support of our Nginx server could not find any error. I have also already tried out various e-mail sending options.
Strangely enough, contact form e-mails are sent immediately and without delay.

The problem occurred first when updating Craft Commerce.


texts: Problem with Site Running Both HTTP & HTTPs

texts:
So we're trying to set-up a site to run both HTTP & HTTPs version in parallel for SEO auditing before making the full switch to HTTPs. We followed Ben's answer on this SE question to make it work: https://craftcms.stackexchange.com/a/4734/57.

The behavior we're seeing after implementing Ben's recommendation are that we can access both the http and https version of each page but a click on any link in the site populated by Craft templates (nav, blog overview page linking to other entries, etc.) takes us to the HTTP version of the page. So for example, if you're on https://example.com, a click on a nav link takes you to http://example.com/click rather than https://example.com/click. However, if we have a root relative link that was added manually through the control panel, that takes you to a version of the page consistent with the protocol of the current page. Basically, Craft is treating all links as if they're HTTP, even if you're on the secure version of the site.

We would like the site to function where if you're on the HTTPs version, a click on any link keeps you on the HTTPs version. Same goes for if you're on the HTTP version, any link click takes you to another HTTP page.

Is there a way to configure Craft to make that happen?

Here are the contents of our craft/config/general.php file:

<?php

/**
 * General Configuration
 *
 * All of your system's general configuration settings go in here.
 * You can see a list of the default settings in craft/app/etc/config/defaults/general.php
 */

// SEE http://buildwithcraft.com/docs/multi-environment-configs for info

// Ensure our urls have the right scheme
define('URI_SCHEME',  ( isset($_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == "on" ) ? "https://" : "http://" );

// The site url
define('SITE_URL',    URI_SCHEME . $_SERVER['SERVER_NAME'] . '/');

// The site basepath
define('BASEPATH',    realpath(CRAFT_BASE_PATH . '/../') . '/');

return array(

  // DEFAULT
  '*' => array(
    //'isSystemOn' => false,
    'omitScriptNameInUrls' => true,
    'cpTrigger' => 'discover',
    'addTrailingSlashesToUrls' => true,
    'siteUrl' => SITE_URL,
    //'devMode' => (preg_match('/dev|xip|staging/', $_SERVER['HTTP_HOST']) ? true : false),
    'devMode' => false,
    'pardotUserName' => "FILLER TEXT",
    'pardotPassword' => "FILLER TEXT",
    'pardotUserKey' => "FILLER TEXT",
    //'backupDbOnUpdate' => false,
    'generateTransformsBeforePageLoad' => true,
    // 'cacheDuration' => false,
    'defaultImageQuality' => 90,
    'caseListPagination' => 6,
  ),
  // Example dev
  'example.dev' => array(
    'devMode' => true,
    'caseListPagination' => 2,
  ),

  'example.svn.dev' => array(
    'devMode' => true
  ),

  'local.example.com' => array(
    'devMode' => true,
    // 'enableTemplateCaching' => false // Only work on Craft 2.4 and later
  ),
  'environmentVariables' => array(
    'siteUrl' => SITE_URL,
    'basePath' => BASEPATH
  ),
);

Thanks!


texts: Craft 3 Redirect after login based on User field

texts:
i'd like to alter the after login redirect URL based on a User custom field, i encountered this but looks like it's not applicable to Craft 3.

I could re-write the whole UsersController class on a custom plugin but maybe there's another way?


texts: Filter entries by Field value using a variable

texts:
How do I filter a list of entries by the value of a field using the value of a variable?

e.g.

{% set location = block.locationVacancies %}
{% set entries = craft.entries.section('careers').search('locationVacancies:"{{location}}"')

doesn't work for me. But if I replace {{location}} with the value of the string location by hand then it works

{% set entries = craft.entries.section('careers').search('locationVacancies:"uk"')


texts: Range Facets with SearchPlus and Algolia

texts:
Currently using Algolia with SearchPlus on my setup. Unfortunately some data is quite clunky e.g. Prices with 23.93 48.12 etc. What I'm wanting to do is have range pricing/grouping where by I can define 20-50 as a facet and all prices within those ranges appear?

Not sure if this is an Alogia side or SearchPlus JS.


texts: Can I change the list of available locales?

texts: Is it possible, by any method, to change the list of available locales? The current list includes some strange entries, e.g. East Germany, and we would like to update this to be more current for our client.


texts: Fail validation of frontend form if field value is not unique

texts:
I was surprised to see that there is no plugin in the store for the purpose of requiring unique values on fields. I need to create a form that will not let front end users create an account if they enter the same [identifying number] as another user.
Is there no way of configuring custom validation logic for creating an entry, and/or for making a field require a unique value, or am I going to finally be forced into learning how to write a module here?


texts: Is there any downside to using localized characters in urls?

texts:
I'm working on a site with both english and spanish locales. Crafts localization features have been awesome so far, and I've been embracing Craft's ability to easily localize URLs.

For example, if I have a section on conservation, the english url would be:

www.mysite.com/conservation

And the spanish one would be:

www.mysite.com/es/conservación

Am I going to run into any technical issues by allowing accented characters in my urls?


texts: How would you go about creating a daily quota for posts? I have a simple photo gallery where users can submit images, problem is some people are a bit too excited. I'd like to limit submission to let's say 10 per day per user. Any tips how to approach this welcomed.


texts: How to set multi-lingual image paths in a css file for different environments?

texts:
Not sure how to do this. I'm setting up a multi-lingual site with a couple of locales and I have 3 different environments set up. I've set up some environmentVariables for assets store and assets path these work fine in the templates.

However how do you deal with background images in the CSS file? Can you include the Twig code? i.e. add {{ craft.config.environmentVariables.sitePath }} to the image path I'm assuming not as CSS uses the curly braces. I know I can add the full URL to the image but this is no good when trying to work within different environments where the overall domain path will be different each time.

Anyone come across this problem and have any ideas?

Many thanks.


texts: Possible to reflect changes to a plugin's composer.json without uninstall/reinstall?

texts:
When working on a plugin recently, I decided to add a CP section:

composer.json

{
    ...
    "extra":
        ...
        "hasCpSection": true
    ...
}

The only way that I was able to have this change reflected in Craft was to uninstall/reinstall the plugin. Is there an alternate way (e.g. CLI) to do so?


texts:
I'm using the import plugin from Bob Olde Hampsink and I've got a exported .csv file. There's nothing special in it but I can't seem to import. I know there's an error log somewhere, but I can't seem to find it. Does anyone know where it's situated? I've found it once but now I'm totally lost and can't seem to find an answer somewhere...

Thanks!


texts: In general what is the best practice to handle invoices from orders made in Craft Commerce ?


texts:
I am trying to create a form that allows users to rate a restaurant (which is another section) by creating a "userRatings" section entry. userRatings has three fields: a dropdown field called ratings, a users field called user, and an entry field called restaurants. The form is on the entry page for a restaurant. Here is what my form looks like now:

<form method="post" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="entries/saveEntry">
  <input type="hidden" name="redirect" value="viewentry/{slug}">
  <input type="hidden" name="sectionId" value="userRatings">
  <input type="hidden" name="sectionId" value="9">

  <input type="text" id="user" name="ratings" value="{{currentUser}}" style="display:none;" readonly>

  <input type="text" id="restaurant" name="restaurant" value="{{entry}}" style="display:none;" readonly>

  <label for="ratings">Rate This Restaurant</label>
  <select id="ratings" name="ratings">
      {% for option in entry.ratings.options %}
        <option value="{{ option.value }}">{{option.label}}</option>
      {% endfor %}
  </select>

<input class="button" type="submit" value="Rate">

The select list successfully pulls in the options from the "ratings" dropdown field, and I have two text boxes that are recording the current user and the restaurant that the user is trying to rate.

Right now, when the form submits, it goes back to the same page with no errors, but nothing is saved on the back-end. Any help or suggestions would be greatly appreciated!


texts: Get an Asset's Filename Without the Extension

texts: How do I get an asset's filename without the extension? So if my filename is my_cool_photo.jpg I want to return my_cool_photo. Using {{ entry.assetsField.one.filename }} returns the name of the file with the extension included.


texts: Cache Records Being Stored for Invalid Paths

texts:
I'm trying to figure out why I have so many template cache records and when I look in my database templatecaches table I'm seeing a bunch of rows being stored for paths that don't exist. For example there are a bunch of Wordpress-like paths that presumably a bot tried to hit:

site:wp-admin
site:wp-content/themes/konzept/includes/uploadify/uploads/cache.php

Also a bunch of records with file extensions like .zip and .rar:

site:website.tar.gz
site:website.rar
site:webroot.zip

All of these paths should have thrown a 404 when the bogus URL was hit, and therefore should not have triggered a cache record to be created. Why am I getting all these junk cache records?


texts: Is there a way to ask for an email address before you download a file?

texts:
For Wordpress there's a plugin called Email before download (https://wordpress.org/plugins/email-before-download/).
I'd like to ask the user's email address before they are able to download a pdf file.
Is there a plugin that can do this in Craft?
Anyone wants to share their experience for best practices?

Thanks in advance!


texts: Cannot call service: "'MyPlugin' not found" error

texts:
I'm sure this is a trivial mistake but I can't figure it out (first-time plugin dev).

I have my plugin running with all code in the controller and want now follow best practice and move the workhorse code into a service class.

My main plugin code is

namespace ns\yutulic;
use ns\yutulic\models\SettingsModel;
use craft\models\Section;

public function init() {

    parent::init();

    self::$plugin = $this;

    $settings = $this->getSettings();
    $settings->sectionOptions = $this->setSectionOptions();

    // Register services
    $this->setComponents([
        'videoentries' => \ns\yutulic\services\VideoEntriesService::class,
    ]);

    $data = $this->videoentries->scanForVideos(null); // works

}

The relevant controller code is

Class ScanController extends Controller {
    public function actionScanEntries() {
        // Neiter works :-(
        //$data = Yutulic::$plugin->videoentries->scanForVideos($id);
        $data = Yutulic::getInstance()->videoentries->scanForVideos($id); // (*)
    }
}

And my service code:

<?php
namespace ns\yutulic\services;
use ns\yutulic\Yutulic;
use Craft;
use craft\base\Component;

class VideoEntriesService extends Component
{
    public function scanForVideos($sectionId = null) {
        echo "Works!!!";
        return null;
    }
}

Even if I use the example of the docs it fails with the same error message on the line indicated (*) in the controller (but with the 'Foo' class name):

Class 'ns\yutulic\Yutulic' not found

This shouldn't be so hard?


texts:
I was running a page speed test and it came up that I'm not leveraging browser caching for images and such. I was hoping to use the header tag to solve this. https://docs.craftcms.com/v3/dev/tags/header.html#app

Where does this go exactly? In the _layout?


texts: Selecting descendants of a category when ancestor is clicked

texts:
I have a question about combining Twig and jQuery in Craft. I have a couple of filters on a page that outputs some entries:
http://www.joycefdn.org/grants

My categories are organized like this:
Education and Economic Mobility
 - Educator Quality
 - Innovation
 - Pathways
Environment
 - Climate Solutions
 - Great Lakes
Culture
 - Arts Access and Participation
 - Arts Leadership and Workforce
 - Creativity and Cultural Production
 - Joyce Awards
Democracy
 - Fair Elections
 - Media
Gun Violence Prevention and Justice Reform
 - Gun Violence Prevention
 - 21st Century Policing
 - Reducing Mass Incarceration
Special Opportunities
 - Communications
 - Cross-Programmatic Innovations
 - Digital Tools

with the top level being Programs and the second level being focus areas.  I would like to have it so that when a Program is selected then the Focus Area select menu gets populated with the categories that are children of that program.  I currently have this jQuery left over from another method I tried which does get the current Programs that are selected:

$(".grants-data form[name='grantSearch'] select[name='program']").change(function(){
    var selectedPrograms = $("form[name='grantSearch'] input[data-name='selectItemprogram'][value!='']:checked").map(function() {
    return this.value;
                }).get().join('|');
});

and I have this which appends all of the descendants of all categories to the focus area menu:

{% set catSlug = craft.categories.title('focusArea').first() %}
            {% set childFAs = craft.categories.descendantOf(catSlug) %}
            $("select#focusArea").html('<option value="">Focus Area</option>');
            {% for fa in childFAs %}
            $("select#focusArea").append('<option value="{{fa.title}}">{{fa.title}}</option>');
            {% endfor %}
            {% if faSlug|length %}
                $("select#focusArea option[value='{{faSlugOrig}}']").attr('selected',true);
            {% endif %}
            </script>

but I can't seem to connect these two so that only the descendants of the program that is clicked get populated.  I think I may be overthinking this or trying to combine two methods that just won't combine.  Any help would be greatly appreciated!

Thanks!!


texts:
I'm just trying out the imager plugin. It looks promising!
I've set up the first usage example but I don't see any image on my site in the browser. The image is uploaded properly to the asset source but it seems that Imager is placing its transforms in a subfolder (in this case: '7' ->  http://craft-imager.dev/imager/images/7/nature-13_d4e4e04a52bfbdbeab5ba4d2cf1d1390.jpg)

The subfolder '7' doesn't exists on my machine..

I did some digging around, but I can't figure out what's wrong. The directory 'imager/images' exists and is writable by PHP.

Any idea?
Thanks in advance!


texts:
Does anyone know why Craft CMS generates continual 404 errors for things like the following:

?p=1504
tag/tag.js
newsdetail.asp?
module/mod_novasfh?

Even after clearing or 301 redirecting 404 errors, a few days later, they explode again and create hundreds of errors in Search Console/Webmaster Tools


texts: How to query entries and take into account the timezone offset? - ChartHelper

texts:
I'm trying to query a range of entries and my results are not returning all the entries in the range I am trying to target. My situation relates to displaying data on a chart using the Craft ChartHelper class, but I'm not sure if this issue is specific to that situation or more general.

I believe Craft saves records to the database based on the UTC timezone. So if I'm in Los Angeles (UTC-7) and save an Entry on 2016-08-31 18:00:00 in Los Angeles, the dateCreated value in the database will be 7 hours later in the UTC/GMT timezone: 2016-09-01 01:00:00.

Now, I want to query all entries that happened in the month of August. The following, largely taken from the Craft Commerce chart codebase, gets me roughly what I need – entries that range over the month of August:

$startDate = DateTime::createFromString('2016-08-01', craft()->timezone);
$endDate   = DateTime::createFromString('2016-08-31', craft()->timezone);
$endDate->modify('+1 day');

$criteria         = $this->getElementCriteria();
$criteria->limit  = null;
$criteria->search = null;

$query = craft()->elements->buildElementsQuery($criteria)
  ->select('COUNT(elements.id) as value');

The above code gets handed off to the ChartHelper::getRunChartDataFromQuery() method which performs the query with this code:

$results = $query
  ->addSelect("DATE_FORMAT({$dateColumn}, '{$sqlDateFormat}') as date")
  ->andWhere(
    array('and', $dateColumn.' >= :startDate', $dateColumn.' < :endDate'),
    array(':startDate' => $startDate->mySqlDateTime(), ':endDate' => $endDate->mySqlDateTime()))
  ->group($sqlGroup)
  ->order($dateColumn.' asc')
  ->queryAll();

While I get back a month's worth of entries, the query does not return entries that were saved after 5pm on August 31st in Los Angeles. I believe this is because the dateCreated value in the database is actually on the following day, September 1st.

I would like to adjust this query to return entries from within the month of the timezone of the website – in this case Los Angeles.

Where do I need to adjust how the date values are being set in order to get back the right data?


texts: How can I create a zip file containing all assets from an entry gallery?

texts:
I'm trying to create a download button which will allow the user to quickly download all assets in an entries image gallery.

I've started by adding each image url into an array stored in a data attr of the button.

<button data-zip-download='[{% for imageUrl in entry.collectionImages %}"{{imageUrl.url}}"{% if not loop.last %},{% endif %}{% endfor %}]'>Download Gallery</button>

I've then tried to get these URL's using jQuery, and zipping/downloading the zip with JSZip.js and FileSaver.js. Although through a bit of research I think I've found this is generally achieved through PHP.

I'm wondering if anyone on here has had a similar situation and has an idea of how I can achieve this.

I'm not too experienced with ajax but have also read that ajax is necessary to get this working via jQuery.

So far my JavaScript looks as so:

$('[data-zip-download]').each(function(){
var $this = $(this),
    urls = $this.data('zip-download'),
    files = [],
    zip = new JSZip();

for (var i = 0; i < urls.length; i++) {
    files.push(urls[i]);
};

zip.file(files);

$this.on('click', function(){
    zip.generateAsync({type:"blob"}).then(function (blob) { // 1) generate the zip file
        saveAs(blob, "gallery.zip"); // 2) trigger the download
    }, function (err) {
        $this.text(err);
    });
});
});

This however only creates a corrupted zip file as I imagine I need to actually load those images via ajax.

I suppose it would be ideal to simply use a craft/twig function if such a thing exists, although anything that works would be great haha.

Sorry for not having much knowledge on this specific need, really hoping someone out there can help!

Thanks!


texts: Complex Conditionals with ElementCriteriaModel / Element API

texts:
Working with the Element API for the first time and I'm having a bit of a hard time finding any kind of documentation regarding writing more complex conditionals using the ElementCriteriaModel.

What I'm trying to accomplish, is selecting all entries (they are events with a start/end date as custom fields) from a given section, which overlap in any way with a passed-in query start/end date.

It is probably easier to simply supply the raw query that works, and perhaps someone could point me in the direction of documentation that could help me.

SELECT *
FROM craft_content
WHERE
! ( field_eventStartDate > @queryStartDate AND field_eventStartDate > @queryEndDate)
AND
! ( field_eventEndDate < @queryStartDate AND field_eventEndDate < @queryEndDate )


texts: Method for pulling entries that have a specific image linked?

texts:
Let's say that I have an Assets field on a single page where someone can add a bunch of images to a "gallery" on that page. Is there a way to perform a query and return the entries from a channel where these images are used as well?

Ideally, I'm trying to get the URL's to all of the listing entries where any of these images are also used, but without the admin explicitly relating them to those entries on the single page. There's no explicit relationship between them, other than the same images were used on both the single and channel entry.


texts:
I'm currently building a site with two languages, and I need a language switcher so wherever you enter the website you can switch the language easily.

I've come this far:

{% for locale in craft.i18n.getSiteLocales() %}
    <li {{ locale == craft.i18n.getCurrentLocale() ? 'class="active"' }}>
        <a href="/{{ locale }}/{{ entry.slug }}">
           {% if loop.first %}DE{% else %}FR{% endif %}
        </a>
    </li>
{% endfor %}

The problem here is that {{ entry.slug }} only returns the slug for the current language and doesn't loop trough the languages.

When I'm on french it returns /bonjour twice and on german it returns /hallo twice. Why is that?


texts:
I'm trying to set up a multisite with Craft 3, and the client wants a set up with URLs that look like foo.client.com, with foo.client.com/2018 and foo.client.com/2019. Right now, my index.php file looks like this:

switch(explode('/', $_SERVER['REQUEST_URI'])[1]) {
  case '2018':
    define('CRAFT_SITE', 'twentyEighteen');
    break;
  default:
    define('CRAFT_SITE', 'default');
}

This correctly changes the site if I go to /2018, but the problem is that Craft is looking for templates at templates/2018/xx/xx instead of templates/xx/xx.. So when I go to foo.client.com/2018 I get:

Template not found: 2018

In the back-end I have the twentyEighteen site defined and the site base URL is set to http://foo.client.com/2018/.

I know that this should work because they even use /en and /nl as examples in the Craft 2 Localization Guide, and Craft 3 multisites work similarly.


texts: Is there a way to clear old database files from storage|backups folder automatically?

texts: We require a way to remove old db files from the storage|backups folder and I was wondering if there is a way to do this automatically or if someone has written a plugin that does it via a cron job?


texts: How to slightly alter _layout for one specific page?

texts:
I have a _layout which includes a contact button:
{% include '_contact-button' %}

This creates a small contact button in the bottom right of every page that when clicked expands into a contact form. I would like this to be on every page of the site except the Contact page as it has it's own contact form. Is there a way in the contact template to not include _contact-button while still using _layout? Something like {% dontInclude '_contact-button' %}?


texts:
When calling my links, they're appearing and trying to link like so:

  testurl.com/university/testurl.com/university/arizona-state/

Really it should just be

  testurl.com/university/arizona-state/

The line that is generating a category URL:

        <a class="university-widget w-inline-block" href="{{ category.url }}">

and my general.php:

return array(

  '*' => array(
  ),

  'localhost' => array(
    'devMode' => true,
    'siteUrl' => 'http://localhost:8888/',
    'server' => 'localhost',
        'enableCsrfProtection' => true,
        'defaultWeekStartDay' => 0,
        'omitScriptNameInUrls' => 'auto',
        'defaultSearchTermOptions' => array(
            'subLeft' => true,
            'subRight' => true,
        ),
        'cpTrigger' => 'admin',

    'environmentVariables' => array(
      'baseUrl'  => 'http://localhost:8888/',
    ),
    'testToEmailAddress' => 'dev@email.com',
  ),

  'testurl.com' => array(
    'siteUrl' => 'testurl.com',
    'server' => 'localhost',

        'enableCsrfProtection' => true,
        'defaultWeekStartDay' => 0,
        'omitScriptNameInUrls' => 'auto',
        'defaultSearchTermOptions' => array(
            'subLeft' => true,
            'subRight' => true,
        ),
        'cpTrigger' => 'admin',

    'environmentVariables' => array(
      'basePath' => '/var/www/html/',
      'baseUrl' => 'http://testurl.com/',
    )
  )
);


texts: Is there a way to calculate the dominant color from an asset available in Craft?

texts: Given an image uploaded to Craft, I am wondering if there is a plug-in or a native method to detect the dominant color of said image.


texts: Central Craft CMS management for agencies

texts:
We have now more than 60 active website running on Craft CMS and have been able to keep our lives somewhat straightforward when it comes to the development side of things (eg. code repository access, deployment, etc).

The main challenge we are still faced with: how to central access or authentication (eg through groups in Google or AD) to the individual sites without having to create/delete users on each and every site when a new team member joins/leaves (too much effort) and without using a single login for all team members (too insecure)

Other challenges
- how to have an overview of CraftCMS version installed on production
- how to know centrally what plugins are used and what versions

I'm sure other agencies also have similar or other needs, what are yours?


texts:
I know how to find user by username and email. The problem comes when I need to query users based on a custom field.

Here is my scenario. I have about 2,000 users (part of a user group 'Affiliates') that I have created in our system. They have many custom fields including affiliateId and studentCount. I need to be able to execute two separate queries.

Find a single user by his/her affiliateId (int).
Query all users within the Affiliate group, order by studentCount asc and return the top record. (I need a user that has the fewest number of students).

I have searched docs and tried numerous combinations to query users. Any help at this point greatly appreciated. Is search the best way? If so, how do you order the search result?


texts:
I have a custom field type which I need to be unique. So far I have this:

/**
 * Validates the field values is unique
 *
 * @param mixed $value
 *
 * @return true|string|array
 */
public function validate($value)
{
    $existingEntryCount = craft()->elements->getCriteria(ElementType::Entry)->total(array(
        $this->model->getAttribute('handle') => $value
    ));

    return ($existingEntryCount) ? $this->model->getAttribute('name') . Craft::t(' must be unique') : true;
}

This works in that it returns an error if any entry is found with the value submitted, however I need to restrict the search so that it excludes the current entry from the search query.


texts: The smoothest way to store JSON object to an entry?

texts:
I'm creating a page where I have a bunch of entries I want to populate with jquery drag and drop boxes. It's for the arrangement of songs, just as a tool.

And I want to store the position of these in a JSON object. When I was using Expression Engine I managed to send an SQL command and store the data in the correct fields. Albeit it was kinda wonky.

But now I'm using Craft so I figure there might way better ways of doing stuff like this. Do I use a form? Do I hide that form and send it using AJAX every time I make some changes to the jquery drag and drop boxes?


texts: Can't update from v2.6.2789 via manual update

texts:
I can't seem to update my local dev site Craft version (2.6.2789) to the latest 2.6.2964. I've followed the steps to update manually but it has no effect and still shows the v2.6.2789 in the footer.

Is there anything I can do to update?


texts: What's the correct way to uninstall a plugin which MUST NOT be enabled?

texts:
I hadn't allowed Craft to update for a while, and then did, but it broke on a plugin, and I couldn't get into the CP. I figured out which plugin was causing the problem, it turned out I wasn't using it, so I disabled it in craft/config/general.php as follows:
return [
    '*' => [
        'disabledPlugins' => ['embedded-assets-link'],
    ],
];

That enabled me access to the CP, but, being disabled, I couldn't uninstall it through the CP, as explained here.
I tried many things, including

remove references to the plugin in craft/vendor/craftcms/plugins.php
removed references to the plugin from composer.json
run composer update

and probably some other nonsense.
So, having done it the hard way, I'd like to ask, is there a correct way to remove a plugin which cannot be enabled ('cause it's broken) ?


texts: Craft 3: Custom "Set Password Form" not working

texts:
I'm trying to make a custom page for setting a new password. I found the following in the docs: https://docs.craftcms.com/v3/dev/examples/set-password-form.html

I created a file called setpassword.twig in my templates folder but it isn't shown when I click the link in the email.

What am I doing wrong? Needs the template to be somewhere else?


texts:
I have a number of entries, each with a quote (table field with one phrase and author row). I would like to show one quote on my login page, but some of these entries do not have quotes.

How can i filter the entries so that it can only choose from the entries that have quotes and exclude the ones who don't have?


texts: Sprout SEO - Characters output to decimal HTML entities

texts:
For some reason, "special" characters such as the apostrophe get converted to HTML entities in the seoTitle variable, resulting in unreadable tab titles.

As you can see, there's this &#039; instead of a regular ' (what is typed into the field).

If I use entry.title instead, I get a clean and readable output.

Is there anything I can do to get a clean output from the seoTitle variable?


texts: Change custom element Index title via getTableAttributeHtml?

texts:
I want to change the title in the index of an custom element.

public function getTableAttributeHtml(BaseElementModel $element, $attribute)
{
    switch ($attribute)
    {
        case 'title' :
        {
            return $element->attribute . 'blabla';
        }

        ...
    }
}

But whatever I try, the title field didn't change. Other fields are no problem.
How can i do this?


texts:
I have a search form that contains a dropdown based on categories and a text field to search by title. This works the way it should. Now I need to add an extra text field to search by location as well but when I do that the search form doesn't work anymore.

What I have is:

{# defaults #}
    {% set queryParams = {
      section: 'klanten',
      order: 'title asc',
    } %}

    {# Build a category array beginning with 'and' and add targetElement objects with selected categories Ids to it #}
    {% set categoriesArray = ['and'] %}

    {% set searchCat = craft.request.getParam('cat') %}
    {% if searchCat is not empty %}
      {% set searchThemeCat = craft.categories.slug(searchCat).ids() %}
      {% set categoriesArray = categoriesArray|merge([{
        targetElement: searchThemeCat,
      }]) %}
    {% endif %}

    {% if categoriesArray|length > 1 %}

      {% set queryParams = queryParams|merge({
        relatedTo: categoriesArray
      }) %}

    {% endif %}

    {# search #}
    {% set searchQ = craft.request.getParam('q') %}
    {% if searchQ is not empty %}
      {% set queryParams = queryParams|merge({
        search: {
          query: 'title:' ~ searchQ,
          subLeft: true,
          subRight: true,
        }
      }) %}
    {% endif %}

{% set klantEntries = craft.entries(queryParams) %}

Now I thought adding the following would allow me to search by location as well but instead it says 'no results are found for ""' which means that it search query is empty, I guess?

{% set searchL = craft.request.getParam('loc') %}
    {% if searchL is not empty %}
      {% set queryParams = queryParams|merge({
        search: {
          query: 'klantLocation:' ~ searchL,
          subLeft: true,
          subRight: true,
        }
      }) %}
    {% endif %}

I don't really know how to fix it, I've been looking through a lot of examples but I can't get it to work, any help would be appreciated


texts:
we have a little problem with craft after updating to the new version.
the entry-overview (foo.com/craft-admin/entries/) seems to load much slower than before when I click an entry (up to 10 seconds)
problem part 2: we just created about 100 sections, which makes the system complete unusable, as we run into timeouts by clicking certain entries.
any idea how to deal with this?


texts:
Is it possible to make the uploaded "original" images unaccessable for site visitors and make only the transforms public?

I'd like to upload images in full quality, to

get the best possible quality out of Craft transforms
make Craft's assets folder basically a backup for my Lighroom library
no manual transforms necessary before upload (Craft does the job anyways for all the required 2x, 1x and thumbnail sizes)

The images should be secure in that folder, otherwise I run into possible copyright problems (images would be in printable size and quality).


texts: How can I import a large number of new entries into Craft 3

texts:
I need to create a few hundred entries at once.  I used the Import plugin for Craft 2 to create these entries from a CSV file.

How can I do the same for Craft 3?  I do not see a plugin for this capability on the Craft 3 plugin page.

Thanks,


texts:
I have a simple nav tag

{% set navConfig = {
    'startwithActive' : true,
    'maxDepth' : 2,
    'activeClassOnAncestors' : true,
    'ancestorActiveClass' : 'active',
} %}
    {% nav node in navigation %}

        {{ node.title }}
        {% ifchildren %}

{% children %}

        {% endifchildren %}

{% endnav %}

This works fine all but with the News section entries. my-site/news adds the active class to the link, but my-site/news/new-entry doesn't add the class to the ancestor.

I have tried most configurations with the available parameters and variables, but I cannot work it out.

Any help would be brilliant!


texts: Target second (or nth) element in a for loop

texts:
I'm trying to show content for only the second entry in a for loop, but can't find any info on how to do specifically this. I'd like to do something like the below.

{% for relatedImage in entry.relatedImages %}
    {% for images in relatedImage.image %}

             {% if loop.index == 2 %}

Welcome!

{% endif %}

    {% endfor %}
{% endfor %}

Any ideas?


texts: Help debugging "An unknown error occurred."

texts:
Recently, when I edit categories or entries I get the dreaded "An unknown error occurred." When I check the logs I see:

2017/12/11 20:41:51 [error] [exception.Craft\HttpException.403] Craft\HttpException in /srv/users/serverpilot/apps/0default/craft/app/services/UserSessionService.php:329

Not quite sure where to go from there. 403 makes it look like a permissions issue but my permissions are all setup just like I normally have them (744). Anyone got any ideas?


texts: How to save Matrix data programmatically in Craft 3

texts:
How can you programmatically save an entry that has a Matrix field in Craft 3?

(Something like this gist for Craft 2)


texts: Unavailable plugin during migration to craft 3

texts:
During a migration from craft 2 to craft 3, I stumble in 3 issues with plugins.

Plugins are not available in craft 3. For example,"instablog" plugin
Reinstall paid license plugins.
Custom plugins.
What should we handle in different cases?


texts:
I am working on a client site and trying to upload the following plugin:

https://github.com/craftcms/guest-entries

The directions instructed me to install the app via composer in my project folderj via composer.

Can I use composer to install the plugin into a random folder, then FTP upload the same into my client's craft plugins folder?

Thanks,


texts:
I want to only show entries that match a specific tag. I'm trying to do something like:

{% paginate craft.entries.section('blog').relatedTo('tagName').order('score') as entriesOnPage %}

This doesn't seem to net any results though. Is .relatedTo() not the way to go when limiting results to a specific tag?


texts: Can't access plugin variable in a twig template?

texts:
So i've got this little plugin named AnnuaireAdherents with a variable that i try to access from within a template :

annuaireadherents/
├── AnnuaireAdherentsPlugin.php
├── services
│   ├── AnnuaireAdherents_Service.php
│   └── Proxy.php
├── twigextensions
│   └── AnnuaireAdherentsTwigExtension.php
└── variables
    └── AnnuaireAdherentsVariable.php

The variable should return a dynamic array, but let's try a static one first :

<?php namespace Craft;

/**
 * Variables provides access to list of adherents inside templates
 */
class AnnuaireAdherentsVariable {

    /**
     * Liste d'adhérents
     *
     * @return array
     */
    public function adherents() {
        return array(
            array(
                "raison_sociale" => "JOHN DOE & Co",
                "contact" => "JOHN DOE",
                "cp" => "99999",
                "address1" => "DESTINY STREET",
                "locality" => "NOWHERE",
                "mail" = "john.doe@nowhere.net"
            )
        );
    }
}

I've tried every namespace variants i could think of to access it inside a template :

{% for adh in craft.annuaireAdherents.adherents %}
    {{ adh.raison_sociale }}
{% endfor %}

but i keep receiving the error :

  Method "annuaireAdherents" for object "Craft\CraftVariable" does not exist

Is it the correct namespace ?
Do i have to relaunch Apache and Craft between each code modification to retest my variable ?
Could there be another error that is masking me the true cause of this message ?

Thanks a lot for any clue /  direction to investigate.


texts:
The examples I have seen to link to previous and next entry all seem to be for sections. I want to get the previous and next category.

My category handler is called 'media'.

So I might have entries in this category such as :
Time
Life
People

When viewing the entry 'Life', I want to be able to go back to Time (Previous) or to People (Next). Again, these entries are entries in my category.

I tried:

{% set params = craft.entries.section('media').relatedTo(category) %}
{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}
{% if prevEntry %}Previous{% endif %}
{% if nextEntry %}Next{% endif %}

That didn't work, so I also tried:

{% set category = entry.category.first() %}
{% set params = craft.entries.section('media').order('title asc').relatedTo(category) %}
{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}
{% if nextEntry %}
    {% set nextEntryUrl = nextEntry.url %}
{% else %}
    {% set firstEntry = craft.entries.section('media').first() %}
    {% set nextEntryUrl = firstEntry.url %}
{% endif %}
{% if prevEntry %}
    {% set prevEntryUrl = prevEntry.url %}
{% else %}
    {% set lastEntry = craft.entries.section('media').last() %}
    {% set prevEntryUrl = lastEntry.url %}
{% endif %}

But also no good.


texts: Output a default asset if one hasn't been specified

texts:
I've looked at and tried a couple of solutions on here but struggling to apply them to my circumstance.

Below is my current code.  I would like a 'default' asset (image) to be used if one hasn't been specified by the admin.  This is so that the front end doesn't have gaps in the gallery.

{% cache %}
  {% for entry in craft.entries.section('people').find() %}

      {% for block in entry.basicProfileInfo %}
      {% set varBarrPic = block.mx_peoplePhoto.first() %}

{{ block.mx_positionWithinBusiness }} {{ entry.title }}

      {% endfor %}

  {% endfor %}
{% endcache %}

I hope this is a simple solution.

Many thanks

Martin


texts: For asset uploads, where should the 'temporary path" be created?

texts:
I just moved my Craft CMS site to production (MediaTemple DV) and I can't upload images to my asset sources. I get this error:

Error uploading the file: there was a problem creating the temporary path.

I have checked (and fixed) the asset source paths but I still get the error.
I guess I need to change permissions on some directory, but which one? I don't know where this 'temporary path' is supposed to be created.

Have I diagnosed the error correctly? If so, where should that path be created?


texts: Template error: A template that extends another one cannot have a body

texts:
How am I able to use bootstrap in Craft? I created a folder in a templates directory named _layouts and inside of that I have base.html

<!DOCTYPE html>

<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

and this is where i want to include the bootstrap (contact.html)

{% extends "_layouts/base" %}
{% macro errorList(errors) %}
{% if errors %}

{% for error in errors %}

{{ error }}

        {% endfor %}

{% endif %}
{% endmacro %}
{% from _self import errorList %}

<form method="post" action="" accept-charset="UTF-8">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="contactForm/sendMessage">
<input type="hidden" name="redirect" value="../public/index.php/contact.html">

Your Name

<input id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}">
{{ message is defined and message ? errorList(message.getErrors('fromName')) }}

Your Email

<input id="fromEmail" type="email" name="fromEmail" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}">
{{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

Message

<textarea rows="10" cols="40" id="message" name="message">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
{{ message is defined and message ? errorList(message.getErrors('message')) }}

<input type="submit" class = "btn btn-submit" value="Send">
</form>

I'm having an error => "A template that extends another one cannot have a body."


texts:
I have a transform in my CP called detail large.
IN my template the image will render normally.

Wen i want to use the transform like below:

I get a 404.

The image path created for the transformed asset is:

/webroot/assets/images/_detailLarge

but not folder or assets is ever created there.
Permissions and aliases are fine.


texts: Load new entry(s) in the same page with ajax as a popup

texts:
First time I'm going to use Ajax with Craft CMS therefore I'm still confused how it works.

What I need is this, when I click on a specified link  in the front, I need the CMS to load some entry/entries and display the data in a popup on the same page of course.

The CSS for the popup is ready, the HTML too (static for now, not twig template) the backoffice also is ready.  The only thing I need is how to get the entries (basic explanation if possible) with ajax (It seems to be the best solution) and load them into the page then show them in a popup.

Is there any link(s) to help in my task or someone to explain those first steps please ?


texts: Showing different field layouts for entries within the same structure

texts:
I set up a structure for pages that looks like this:
- All Services
  - Service 1
    - Service 1 subpage a
    - Service 1 subpage b
  - Service 2
    - Service 2 subpage a
    - Service 2 subpage b

I followed the accepted answer to this question to set up different templates within that structure, so now the level 2 pages (i.e. Service 1 and 2) use a different template than the level 3 subpages (i.e. a and b).
These templates have different elements, so now I want to show different fields/field layouts when I edit the page entries. For example, if I'm editing a level 2 page, it should show fields for the title, a rich text field, an image upload field, and a few other fields I've created, but if I'm editing a level 3 page, it should only show a title and rich text field.
Is it possible to do this? If not, what's the best way to handle this type of thing in Craft? I'm trying to avoid creating one structure for level 2 pages, and another structure for level 3 pages, because I'm not sure how to preserve the hierarchical relationship between level 3 and level 2 pages if I do that.


texts: How would I omit zero value decimals in a number format?

texts:
Say I have {{ item.width }} and {{ item.height }} which are number fields with 2 decimal places.
In my template I have this:

Dimensions: {{ item.width }} x {{ item.height }} in.

Which will output like this:

Dimensions: 8.50 x 11.00 in.
Dimensions: 5.00 x 7.00 in.
Dimensions: 4.25 x 6.50 in.

How would I drop the decimal places that are not used?  Like this:

Dimensions: 8.5 x 11 in.
Dimensions: 5  x 7 in.
Dimensions: 4.25 x 6.5 in.


texts: How do I access the category of an entry with Element API?

texts:
The category count is only ever 1 and I need to output the name of the category the entry belongs to.

Would there need to be a cross-over between the EntryModel and CategoryModel?

'transformer' => function(EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'jsonUrl' => UrlHelper::getUrl("jobs/{$entry->id}.json"),
                    'postDate' => $entry->postDate->getTimestamp() * 1000,
                    'id' => $entry->id,
                    'jobOverview' => (string) $entry->jobOverview,
                    'category' => $entry->jobCategory[0],
                ];
            },


texts:
In a Element::EVENT_BEFORE_SAVE event within a custom module I'd like to set an SEOMatic field. setFieldValue doesn't work presumably because it's a custom field, is there any reliable way to do this?
Example event I have set up within a module:
public function init()
{
    parent::init();
    self::$instance = $this;

    Event::on(Entry::class, Element::EVENT_BEFORE_SAVE, function(ModelEvent $e) {
        $entry = $e->sender;

        // $entry->seoField seems to be seomatic\models\MetaBundle
        // Setting $entry->seoField->metaGlobalVars->canonicalUrl with setFieldValue doesn't work:
        $entry->setFieldValue('seoField.metaGlobalVars.canonicalUrl', 'special canonical');
    });
}


texts: Redirect and locale issues when using Valet / Caddy Server

texts:
I'm trying to setup our Craft CMS dev environment with Valet which is just a wrapper for Caddy Server and dnsmasq.

I seem to be running into some redirect/locale issues that's preventing these pages from loading. The rest of the site and the CMS admin itself is working fine.

I've previously had things setup on apache and have followed the localization guides but I'm thinking it has to do with the fact that caddy server doesn't honor .htaccess files so I need to add some rewrite rules in my Caddyfile for the various locales.

When trying to load the regional sites it's just giving me a 404.

Has anyone else got this working?


texts: Issue with htaccess redirect adding parameters

texts:
Having an issue with htaccess redirects adding parameters to the new locations. I have done some research on this and apparently its from the default htaccess rules. I have tried a few suggestions which fixes it, but then I run into another issue where all of my channels load without www so none of the css or scripts load. I have a redirect to redirect all non www to www, but for some reason it must be conflicting with my rules because it will not redirect the channels.

Here is my redirect code

<IfModule mod_rewrite.c>
RewriteEngine On
#only way the below redirects work without the parameter
RewriteRule (.+) index.php [QSA,L]

Redirect 301 /services/ http://www.domain.com/healthcare-it-services/
Redirect 301 /services/optimization/ http://www.domain.com/healthcare-it-services/optimization/
Redirect 301 /services/insurance-authorization/ http://www.domain.com/healthcare-it-services/insurance-authorization/
Redirect 301 /solutions/ http://www.domain.com/healthcare-it-solutions/
Redirect 301 /solutions/schedule-maximizer/ http://www.domain.com/healthcare-it-solutions/schedule-maximizer/
Redirect 301 /solutions/provider-network-manager/  http://www.domain.com/healthcare-it-solutions/provider-network-manager/

# send any asp page back to home
#RewriteRule \.asp$ http://domain.com [R=301,L]

RewriteCond %{HTTP_HOST} ^domain.com$
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

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


texts: \ns\prefix\Plugin::getInstance() returns null from another plugin in Craft 3

texts:
I'm building a plugin that extends the functionality of the Contact Form Tuner plugin and customize the email recipients based on different scenarios.  The email addresses need to be managed in the plugin settings using forms.
 Thus, I need to grab the settings from my plugin to be used in the Contact Form Tuner config file.

The problem I'm having is that I can't access my plugin from the Contact Form Tuner config file.  The getInstance method returns null.  I know I have the namespace and class name right because the same statement works when running it from my plugin class.

I also noticed that Contact Form Tuner seems to be loading before my plugin when testing with die statements in both plugins.  Is this the reason?

Is there any way around this?

Any help is appreciated.  Thanks!


texts:
Most websites have three distinct types of page.
List of items
Item
Special layout of items / content

A list of entries require a list view. Craft lets us do this with singles - eg blog index page. But we can also just use a template and custom route.

What are the pros and cons of each?
The pros of single index style pages is that I can then build a navigation structure that has an entry link to the single.  Beyond that are there any other reasons why one over the other?


texts:
I'm using the Pixel & Tonic Contact Form plugin.
I have created a template and I'm using the example code from the README file.

No email is being sent. Upon submit it redirects to the form page.  I have successfully sent myself an email test using Php Mail.

Do I need a template at:
<input type="hidden" name="action" value="contactForm/sendMessage">

This is my code:

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

    <form method="post" action="" accept-charset="UTF-8">
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="contactForm/sendMessage">
        <input type="hidden" name="redirect" value="/thank-you-for-contacting-us">

Your Name

        <input id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}">
        {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

Your Email

        <input id="fromEmail" type="text" name="fromEmail" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}">
        {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

Subject

        <input id="subject" type="text" name="subject" value="{% if message is defined %}{{ message.subject }}{% endif %}">
        {{ message is defined and message ? errorList(message.getErrors('subject')) }}

Message

        <textarea rows="10" cols="40" id="message" name="message">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
        {{ message is defined and message ? errorList(message.getErrors('message')) }}

        <input id="kneesbees" class="kneesbees" name="kneesbees" type="text">

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


texts: CraftCMS Push Notifications: New Device Token

texts:
I've been looking at the Push Notification Plugin.

Link: https://github.com/boboldehampsink/pushnotifications

I'm having some issues determining how an iOS or Android application can automatically add a new device token to an application. Meaning, I wouldn't want to add the device token via the CP. Most users don't know what their device token is.

I've looked at the HTTP Requests that is produced when I click to create a new device in the plugin settings; however, when I test trying to create a new device only by URL it fails. Any ideas?

Has anyone else used this plugin?


texts: Where do I add custom css for the Redactor editor in the Craft control panel?

texts:
Redactor provides a way to specify custom styles for content in the editor. It's documented here: http://imperavi.com/redactor/examples/typography/

How can I use this approach with Craft?

I've already added custom formatting options to the menu via formattingAdd. That works great and the corresponding custom CSS classes are being applied in the formatting menu, the editor text, and on the site front-end.

But the items in the formatting menu and the editor just look like standard paragraph elements and don't reflect any of the styles that they will have on the site.

Where do I put the CSS so that when my clients are working in the control panel, the styles are visible in the formatting menu and the editor when they are applied?


texts: Set base 'shop' URL to something else in Commerce

texts:
I am completely new to Craft and to be honest, really struggling to get my head around how it all works at the moment.

I've got loads of, what I feel, is quite basic questions that should be relatively straight forward but after searching numerous documentation and online posts, can't find out how to do any of it.

So figured asking here might be the quickest way of learning how to work with the platform.

So in a development environment, I've got Craft CMS set up with the Pro version of Commerce. By default, this comes set up at /shop/.

What do I have to do exactly in order to change the 'shop' URL to something else, for example /store/?

I tried duplicating the 'shop' directory as 'store' and whilst the pages seem to load at /store/, the templates are still being served from /shop/ (tested by modifying them).

If someone could list step by step the correct process for changing this, that would be very helpful.


texts: How do you use 'if' to stop an empty Matrix block from displaying?

texts:
On a complex page, where there are different sections that need to be present in the template, but may not all have content added via Craft entries I need to stop the empty areas from being output (e.g. a set of div's that will create an ugly empty space in the page).

I can successfully do this for empty simple entries - like this:

{% if entry.modelTitleType %}

{{ entry.modelTitleType }}

{{ entry.modelIntroType }}

{% endif %}

So the div enclosed by the 'if' statement is only output if there's an entry added for 'modelTitleType'.  But I cannot get this to work for a Matrix entry!

How do I wrap an 'if' statement around a Matrix block like this, so it is only output if there's data added?

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

{{ block.typeName }}

        {% endif %}
    {% endfor %}
    {% for block in entry.modelDataType2 %}
        {% if block.type == "type" %}

{{ block.typeName }}

        {% endif %}
    {% endfor %}

I've tried:

{% if entry.modelDataType1 %}

But this doesn't work...

Any help would be very much appreciated!

Many thanks.


texts:
Question 1

I have a Node/Express application where the users are registered and are using some kind of service. I want to have a list of the registered users and their info inside Craft CMS admin panel.  Node/Express may use MongoDB or MySQL. This kind of hybrid to work, I assume that Node/Express and Craft CMS should be using the same MySQL database? Is this possible at all to integrate them?

Question 2

Can you generally review what the architecture of the application would be in the scenario below?
Lets say we want a web application where the users are registering, uploading their pictures in members area, writing some logs about themselves, but on the other hand, inside the members area they are able to see content from Craft CMS.  Lets say frontend is done via REACT, and the frontend team just sends us request calls and we should just answer. What technology would you use and how to accomplish this? Must it be done in php?


texts: How can I make a product field required?

texts:
I have a drop-down of variants of a product. For example t-shirts:

{% for purchasable in product.variants %}
    <option value="">Select</option>
    <option {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}disabled {% endif %} value="{{ purchasable.purchasableId }}">
        {{ purchasable.title }} &ndash; {{ purchasable.price|currency(cart.currency) }}
    </option>
{% endfor %}

As you can see I have "Select" as the default option, and it has no value. I can validate the form client side no problem, but I am curious if there is a way to designate that fields as required from the server-side? I can mark the field as required in the layout builder, but that is for the CP only I think.

If I do not choose an option, I get this error:

Craft\Exception
Not a purchasable ID

Which makes perfect sense since I am not passing it a valid purchasable element.


texts: Incorrectly setting module template variable

texts:
Getting error:

  Calling unknown method:
  craft\web\twig\variables\CraftVariable::markAsReadModule()

Trying to use a template variable that I created in my Craft 3 module, I use this module for other things that work as expected but I am running into an issue with this in the template:

{{ craft.markAsReadModule.read(entry.id) }}

In the init method for craft/modules/markasreadmodule/MarkAsReadModule.php I register the variable:

I am using:

use craft\web\twig\variables\CraftVariable;
use modules\markasreadmodule\variables\MarkAsReadModuleVariable;

Then I have this in the init:

Event::on(
    CraftVariable::class,
    CraftVariable::EVENT_INIT,
    function (Event $event) {
        /** @var CraftVariable $variable */
        $variable = $event->sender;
        $variable->set('markAsReadModule', MarkAsReadModuleVariable::class);
    }
);

In craft/modules/markasreadmodule/variables/MarkAsReadModuleVariable.php

public function read($entryId)
{
    $service = new MarkAsRead(); // initialize the service class
    $read = $service->read($entryId);
}

I suspect I am setting the naming convention where I include it in the template and/or in the init method within craft/modules/markasreadmodule/MarkAsReadModule.php


texts: How to turn off application log in dev mode

texts:
I have been searching through the admin panel on our staging site trying to find where to turn off the application log.

I know that you can turn off dev mode, and that will turn off the log, but I still want dev mode on, I just want to turn off the log itself.

I did look at the documentation here and was not able to find it.

Any suggestions.


texts: Building my first Sprout Form and need ability to add Tags input

texts:
I'm building my first Sprout Form and I need a tags relational field, but where the user filling in the form can add their own tags, but if similar/matching tags exist then they can select them, like the tags field behaves within the control panel.

Anyone know if that's possible? If not in Sprout Forms, another way?


texts: Combining env variables with strings in settings

texts:
I have a site with multiple subsites in the following structure:
www.site.domain/subsite.

To create multiple subsites, I'd consider setting a base url in the .env (for easy changes: localhost <> live url) and setting the url for each subsite like this $SITE_URL . 'subsite-string'.

Is there any way to achieve this? Or is the only way a full variable per subsite like $SITE_URL_SUBSITE_STRING?


texts: Edit entry, on the front end, with the entries field

texts:
I currently have front-end code working for a user to create an entry, add a title (text input) and also relate entries via the entries field type and checkboxes. All on a front-end application.

Creating the entry is fine, but I'm having an issue with the editing of the entry.

I'm unable/unsure how to "check" what the previously selected relate entries where. Code for showing entry items...

{% set entries = craft.entries.section('exercises') %}
{% for entry in entries %}
<li>
    <input type="checkbox" name="fields[planItems][]"
           id="fields[planItems]" value="{{ entry.id }}">{{ entry.title }}
</li>

Other fields are fine such as the title field, all you have to add is {%- if entry is defined %} value="{{ entry.title }}"{% endif -%}>.

Any ideas on how to get that value so I can add checked to the previously selected entries?

Thanks!


texts: GraphQL: get prev / next entry from current entry (channel)

texts:
Is there a way to get the prev and next entry from the current entry, when this entry is inside a channel and not a structure?
query ($id: [QueryArgument], $rel: Int) {
  entry: entry(id: $id) {
    id
    slug
    title
    uri
  }
  next: entry(nextSiblingOf: $rel) {
    id
    slug
    title
    uri
  }
  previous: entry(prevSiblingOf: $rel) {
    id
    slug
    title
    uri
  }
}

Output when the entry is in a structure:
{
  "data": {
    "entry": {
      "id": "145",
      "slug": "neuigkeiten",
      "title": "Neuigkeiten",
      "uri": "neuigkeiten"
    },
    "next": {
      "id": "150",
      "slug": "leistungen",
      "title": "Leistungen",
      "uri": "leistungen"
    },
    "previous": {
      "id": "141",
      "slug": "unsere-praxis",
      "title": "Unsere Praxis",
      "uri": "unsere-praxis"
    }
  }
}

and the result when the entry is inside a channel:
{
  "data": {
    "entry": {
      "id": "182",
      "slug": "david-hellmann-1-2",
      "title": "David Hellmann",
      "uri": "team/david-hellmann-1-2"
    },
    "next": null,
    "previous": null
  }
}

is there a way to get this data?


texts: Saving asset programatically, eg via API

texts:
I'm working on a plugin in Craft 3 that is fetching a file reference (URL) via an API.

I want to fetch the file and save it locally as an Asset. I've tried to do this via Craft::$app->getElements()->saveElement() but am getting the following error:

New Location cannot be blank.

Any thoughts on this issue or where to dig a bit deeper to resolve?

Cole


texts:
I am building a baseball standings table.
I currently have a Single section setup in Craft to handle some basic info.
It contains a table field with 3 rows: Team, Wins and Losses.

I am able to output this info via the following code:

{% for records in standings %}
    {% for row in records.southStandings %}

            {{ row.team }}
            {{ row.wins }}
            {{ row.losses }}

            {{ row.wins + row.losses }}
            {{ (row.wins / (row.wins + row.losses))|round(3, 'common') }}

    {% endfor %}
{% endfor %}

However I am needing to do a few things for these standings.

Needing to sort the teams via their winning percentage (W%), if W% is same then alphabetically.

The W% is calculated this way:
{% set wP = (team.wins / (team.wins + team.losses))|round(3, 'common') %}

Calculate the games behind (GB).

Games behind is another equation, like so:
{% set gamesBackA = ((teamA.wins - teamB.wins) + (teamB.losses - teamA.losses)) / 2 %}

GB is how far back teams are from the leading team (1st place).

I am not even sure how I would set this and output the correct number at all, so any guidance on this would be wonderful.

I have tried setting an new empty array before my for loop and setting it within the loop. But the only way it outputs more than won W% number in that array is another for loop, like so:

{% set standings = craft.entries.section('standings') %}
{% set wPArray = [] %}

{% for teams in standings %}
    {% for team in teams.southStandings %}
        {% set wP = (team.wins / (team.wins + team.losses))|round(3, 'common') %}
        {% set wPArray = wPArray|merge([wP]) %}
    {% endfor %}
{% endfor %}

{% for t in wPArray %}
    {{ t }}
{% endfor %}

I can then sort using SuperSort but that doesn't allow me to output the Team, Wins, Losses, Games Played (GP), and Games Back.

What am I missing with the arrays?

What is the best approach to output the table, sort them by W%/alphabetically and calculate Games Back as well.

I do have the SuperSort plugin installed.

Any help with this would be greatly appreciated.

Thanks in advance!


texts: My live preview for blog entries is not working on my computer, but is working for my account on other computers

texts: When I go to live preview to view my blog entry in draft mode, all I see is a white screen. My co-workers have tested under my account on their computers and it works just fine. Does anyone have any kind of insights for this?


texts:
I have a layout in Craft with twig that gets the first 3 entries and applies them to the first three containers in the grid.

I can't figure out how to loop through the remaining entries to add to the grid-remaining div.  With the current code it will repeat entries 1-3 in the grid-remaining div.

Here's what I have at the moment:

{% set firstEntry = craft.entries.section('shows').first() %}
{% set secondEntry = craft.entries.section('shows').nth(2) %}
{% set thirdEntry = craft.entries.section('shows').nth(3) %}

{% extends "_layout" %}

{% block content %}

            {% include "_partials/card" with { entry: firstEntry } %}

AD

            {% include "_partials/card" with { entry: secondEntry } %}

            {% include "_partials/card" with { entry: thirdEntry } %}

        {% for entry in craft.entries.section('shows') %}

            {% include "_partials/card" %}

        {% endfor %}

{% endblock %}

EDIT

The following works, but I feel like there must be a cleaner way to achieve the same result.

    {% for entry in craft.entries.section('shows') %}
    {% if loop.index != 1 and loop.index != 2 and loop.index != 3 %}

        {% include "_partials/card" %}

    {% endif %}
    {% endfor %}


texts: Is it possible to create fields in a Matrix block from frontend?

texts: My clients wants its restaurant owners to create FAQs from frontend where each owner can add its questions from frontend and the users will have to submit its answers. I thought to implement it through creating a matrix field which will be available for each restaurants entry. The name of the field could be the question and the text field could be the answer. Each users could save there answers to a new block. I know how to put data into matrix fields that are already made. But i can't find anything from which i can add fields in a matrix block. Is it even possible? Is there any type of plugin available which would help me in it? Any other ideas for this issue would be appreciated.


texts:
I'm trying to redirect at the end of the saveasset function in init().

This is my code:

craft()->on('assets.saveAsset', function (Event $event) {

     // a lot of code here ##########################

     //#############################################

     //at the end:

     craft()->request->redirect('myurl.com');
}

When I save an asset with the redirect function at the end I get the following alert:

Upload failed for filename.csv.

The upload works when I leave the redirect out.

Thanks!


texts: Merge two queries of entries ordered by publication date

texts:
I got a section called news which contain 2 types of entries:
news and press.

Those entries are linked with 2 different categories :
news entries have category newsType
and press entries have category pressType.

In twig template I want to make 2 entries listing:

one from news entries and category newstype = A
the other from press entries and category presstype = X

Then merge those 2 lists to display them ordered by publication date?


texts:
Let's say I have an auction website:

'Ads' would be a section -> channel
The ads in it would be entries in the channel

Let's say guest users can make an offer on the action/ad. I would like to save all the offers in the entry, so I could read them out front-end.

What would be the best way to save these entries? I'm having difficulty understanding this structure-wise.


texts: How to handle URLs of entries with no category?

texts:
I have a section where most entries have a category assigned to them, but a few ones have no category at all.

I need help how to connect these entries' URLs to my entry template.

So far I used a route to catch these cases and assign them to the entry template:

"Route URLs like section/slug to template /section/_entry."

Then I realised that this also catches all entries that have a category, so both these URLs would be valid: /section/category1/slug1 and /section/slug1

But all entries with a category assigned to them should raise a 404 if their category is missing from the URL.

This looks like a common scenario, but so far I only found a solution where those entries are given a default category.

How can I handle my case?


texts: Many versions of the same structure of entries?

texts:
If I had a structure representing the user guide of a product; is it possible to select a specific version of user guide entries from a URL?

http://www.example.com/myproduct/docs/v2.0/installation

Where the logic would be something like (pseudo-code):

craft.entries('myProductDocs').versionLowerOrEqual('2.0').slug('installation')

I see that Craft has some provision for versioning entries since you can select from the drop-down in the entry editor interface. Is there a way to tame this?


texts: Extra margin in Default System on subpages like news

texts:
On the default install, taking out all css. There is an extra margin space at the top of Chrome, and IE Edge but firefox is fine. I also checked out the error 404 page, and it too is fine like the standard layout page at home.

However, if I click news or create a new extends sub folder, they will have an extra 26 pixels at the top.

I noticed this trying to have a top bar flushed to the very top. I rolled back everything to stock and used the default template, took out all CSS from it, and still notice this issue.

here is an image comparison of the two pages, no css using Chrome.

Thanks,

Logan.


texts: Plugin uploads an asset, need the final url

texts:
I have a plugin which

uploads one or more files
creates a new entry with those files as new assets in a subfolder whose name is the new entry's slug
sends e-mail which includes links to the new assets.

The problem I have is that the url for the new assets is not their final url (in the subfolder), but /cpresources/tempassets/field_###/filename

The relevant bit of code:

if (craft()->entries->saveEntry($entry))
{
  // send the e-mail
  ... here when I send the e-mail, the url is wrong ...
}

What do I need to do after the saveEntry?


texts: chain of random entries based on relations

texts:
I'm developing a bio section for a client. Every bio is linked to another bio creating a chain of bios. The order of this chain should be random. The schema would be as following:

Bios: Bio a, Bio b, Bio c, Bio d

Links: a-b, a-c, a-d, b-a, b-c, b-d, c-a, c-b, c-d, d-a, d-b, d-c

One possible example would be:

"Anna is born in England..." (Bio a)
"Anna met Bob during summer..." (Link a-b)
"Bob works a taxi-driver..." (Bio b)
"On this evening Bob met Charles..." (Link b-c)
"Charles ..." (Bio c) and so on..

This schema generates a ton of possibilities. Currently there are 4 bios, but later on there will be probably 10. I know how to hard-code this, but it's a ton of if and elseif and not really flexible.

I'm flexible regarding the entry and field side, what ever fits best.

How would you code this? Any help appreciated!

EDIT:

Here how it should look in the end:

When you navigate to "Biography" it generates a bio chain, if you click "shuffle" it generates a new one. I made different approaches so far, but all seem to involve to much code.

Here is my latest:

// set all bios & pick one randomly, assume it's Luka's
{% set allBios = craft.entries.section('biography') %}
{% set bioA = allBios.order('RAND()').limit(1).first() %}
{{bioA.text}}

// Chose a random link connecting Luka to another member
// every bio has matrix fields holding the bio link texts
{% set linkA = bioA.biographyLink.type("bioLink").order('RAND()').limit(1).first() %}
{{linkA.bioLink}}

// every matrix bio link has one tag to identify what connection it is
{% set tags = linkA.linkTag.first() %}
{% for tag in tags %}

  // is it connecting Luka with Nemanja?
  {% if tag == "con-luka-nemi" %}
    // display bio Nemanja
    // pick random bio link Nemanja-?
    // display picked link

      // search for next bio based on the chosen link above
      {% if tag == "link-nemi-emma" %}
        // diplay bio Emma
        // pick random bio link Emma-?
        // display picked link

          // is it connecting Emma with Guillaume?
          {% if tag == "link-emma-guillaume" %}
            // display bio Guillaume
            // pick random bio link Guillaume
            // display picked link

You see the problem, this generates many ifs and is only 4 levels deep, at the end there will be 10 bios.


texts: How do I get to the web UI in CraftCMS to install it?

texts:
I initially tried this with Ubuntu Linux and a .tar.gz file without the composer tool.  I was using MySQL and PHP 7.4.  My problem is about the same with my second attempt.  I will now describe my second attempt and ask for help with it (instead of my first attempt).
I am trying to install CraftCMS on Debian 10 with composer.  Everything seems to work on the back-end.  I am using PostgreSQL and PHP 7.3.
I finally went to the web front-end portion of the directions.  In a web browser I go to /index.php?p=admin/install
It resolves to /dashboard.  The web page that is rendered says "Not Found   The Requested URL was not found on this server"
When I just go to "" in the web browser, I see "Welcome  Thanks for installing Craft CMS!"  I can click on the "Control Panel", but that takes me to a page that is Not Found.
I expect to see the screen to install CraftCMS in a web browser when I go to /index.php?p=admin/install
What am I doing wrong?


texts: Is there a way to output more Matrix fields than one?

texts:
I'm struggling to get an element criteria model of more matrix fields at once for entry related to tagField.

Example:
I have two matrixFields, where I want them in {% for block in entry.matrixFieldhandle %} loop.

I could do

{% for block in entry.matrixFieldhandle1 %} My stuff {% endfor %}

and

{% for block in entry.matrixFieldhandle2 %} My stuff {% endfor %}

but it's kind of silly to always set element model for each field. Anything simpler?

Couldn't find anything explanatory in documentation or here.


texts: Getting current entry element via plugin in Craft 3 without a hook

texts:
Is it possible to query the current entry or category element via a Craft 3 plugin/module?

In the 2.6 era, I would use a hook. The Craft 3 iteration of a hook looks something like this:

$currentElement;

Craft::$app->getView()->hook('someHook', function(array &$context) {
  if (isset($context['entry'])) {
    $currentElement = $context['entry'];
  } else if (isset($context['category'])) {
    $currentElement = $context['category'];
  }
});

With an accompanying Twig snippet in the template:

{% hook 'someHook' %}

I'm wondering if there is a cleaner practice to accomplish the same goal? I find relying on Twig snippet reduces the flexibility of my plugin.

I've noticed the SEOMatic plugin is able to append entry specific data without any hooks in the template. I can't figure out how, but it gives me hope.


texts:
I have got a problem with an asset field in a Matrix in an _entry template.
The Matrix is for a step-by-step feature. Each step has his own image.
So the asset field in my Matrix calls: stepImage.

Now in my _entry template I loop over the step Matrix like:

{% for row in entry.steps %}
    ...
{% endfor %}

In this loop I try to get the asset URL like:

  {% set image = row.stepImage.first() %}
  {% if image %}
      {{image.url}}
  {% endif %}

but it does not work. If i dump it, it returns bool(false).

Do you have any ideas?


texts: How can I get all child categories - of a child category based on url segment?

texts:
I am missing something very obvious I think. I am trying to get all child categories based on url segment.

For example: "mysite.com/foo"

I have a category Group called Sections Within Sections I have a category called Foo.

Categories:

Sections  <-- Category Group
    |- Foo
        |- One
        |- Two
        |- Three

Using this url as an example: www.mysite.com/foo

twig

{% set categoryGroup = craft.categories.group('Sections').level(1).slug(craft.request.getSegment(1)).first() %}
{% set categories = craft.categories.ancestorOf(categoryGroup) %}

Doing this:
Group: {{ categoryGroup }}

Renders this: Group: Foo

Great!

{% if categories|length %}
    {% for cat in categories %}
        {{ cat.title }}
    {% endfor %}
{% else %}
    NOTHING
{% endif %}

I am always getting back my NOTHING statement. When I navigate to mysite.com/foo, I would like to show One Two Three


texts: Debugging a Failed Custom Task in Craft CMS

texts:
I am trying to debug a failed task in craft.  However I'm not really sure what I'm looking for.  I've dug though the log files and found traces of the task but no real errors to speak of.  I have set:

'runTasksAutomatically' => false,

in my general.php file so that when I create my task:

craft()->tasks->createTask('WassermanNews_SocialTask');
craft()->end();

it will become a pending task rather than run automatically. That part seems to work as I end up with a pending task in my control panel.

So I think I've got the process up to this point.  From here I'd simply like to kick off that pending process which I am attempting to do by though cURL.

curl -H "X-Requested-With: XMLHttpRequest" myurl.dev:32769/actions/tasks/runPendingTasks

I know that this is firing because the tasks moves from a pending state to a failed state:

However as I previously mentioned I have no idea why the task is failing and the logs do not seem to be my friend today.

Any ideas on what I could be doing wrong/where I could look for errors?

Below is my task which should be firing (it fires 1 subTask):

<?php
namespace Craft;

class WassermanNews_SocialTask extends BaseTask
{
  $TWITTER = 1;
  $INSTAGRAM = 2;
  $VINE = 3;

  public function getDescription()
  {
    return 'Social Grab';
  }

  public function getTotalSteps()
  {
    return 3;
  }

  public function runStep($step)
  {
    WassermanNewsPlugin::log("Social Grab stepz izz happening",LogLevel::Info);

    switch($step){
        case TWITTER:
            return $this->runSubTask('WassermanNews_TwitterTask');
        case INSTAGRAM;
            return $this->runSubTask('WassermanNews_InstagramTask');
        case VINE:
            return $this->runSubTask('WassermanNews_VineTask');
    }
  }
}

All the sub tasks look more or less identical to this:

<?php
namespace Craft;

class WassermanNews_TwitterTask extends BaseTask
{
  public function getDescription()
  {
    return 'Twitter Task';
  }

  public function getTotalSteps()
  {
    return 1;
  }

  public function runStep($step)
  {
    return "twitter step";
  }
}

Any help figuring this out would be much appreciated!

UPDATE:

I just attempted to run the an example and it failed as well.  Do certain settings affect how tasks are run?
Installed PixelAndTonic's Power Nap and it failed as well!  I did however find a log for this example saying:

Encountered an error running task 95 (PowerNap): Could not find the task component type.

This makes me wonder what the type of the task has to be!  I took a look in TasksService.php and saw that the error is derived from not having a type so what type do tasks need to have?


texts:
A plugin that is using a Guzzle request is now throwing an exception that the class cannot be found.

I'm running Craft CMS 2.6.3000. Where is Guzzle being pulled from? I can see it within craft/app/vendor/guzzle and also within plugins/oauth/vendor but for some reason this plugin cannot cannot use this class anymore.

It is being referenced as $client = new \GuzzleHttp\Client();

Why can't the class be used?


texts: Return message when no users are found in element index page

texts: How can a 'no users are found' message be displayed when the search returns no matching results in index page ?


texts: How can I set a Neo field's values from my plugin/module?

texts:
I wish to programmatically set the value of a Neo field.
This is my current approach:

$entryData = self::setupEntryData($item);
$entry = new Entry($entryData);

$fieldValues = [
    'heading' => $entryData['title'],
    'blocks' => [
        'blocks' => [
            'new0' => [
                'modified' => 1,
                'type' => 'wysiwyg',
                'enabled' => 1,
                'collapsed' => 0,
                'level' => 0,
                'fields' => [
                    'grayBackground' => true,
                    'wysiwyg' => '
test
',
                    'buttons' => null,
                ]
            ]
        ]
    ],
];

$entry->setFieldValues($fieldValues);

Of course this doesn't work.
Can someone point me in the right direction?
Here is a screenshot of the Form Data that is passed when setting the value manually from Craft CMS.

Just to confirm, my Neo field is called blocks.
My target blog type has a handle of wysiwyg.
The Redactor field I target has a handle of wysiwyg.

Thank you!


texts: How to do CSS/JS bundles/minifying in Craft 3

texts:
I would like to combine all of my sites JS-files into one bundle - and perhaps also obfuscate it.

Same goes for CSS-files.

How would I do that in Craft CMS 3?


texts: Ajax - How to create a Category through actionTrigger

texts: I'm trying to create a jQuery/Ajax script to import data from a Wordpress API service and want to import the WP categories and tags into my database. I've managed to import the tags using an Ajax call to /actions/tags/createTag, is there any endpoint that does the same with categories?


texts: Don't output specific category on entry page

texts:
With

{% for category in entry.categories.all() %}
    {{ category.title }} {{ not loop.last ? '| ' }}
{% endfor %}

How do I exclude a specific category from displaying?