texts: How to output 'selected' checkbox labels within a matrix

texts:
Newbie here.

First Craft 3 CMS build and fumbling with logic of Matrix blocks.

I've created a relatively simple matrix field, and I can output plain text and dropdown options, but not sure how to do a multiple choice field like checkboxes within a matrix.

Thanks


texts: Upgrading to 3.6 Impossible With PHP 8 Installed

texts:
After seeing that CraftCMS now supports PHP 8, I went ahead and upgraded my server to PHP 8 (formerly, PHP 7.1 was running).
The problem I am now facing is the following:

PHP 7.1 was too low to upgrade Craft from 3.5 to 3.6.
Craft 3.5 does not support PHP 8, so I cannot use PHP 8 to upgrade to 3.6 either.
I then installed PHP 7.4 alongside PHP 8, as it seems to be the only PHP version that is able to upgrade from 3.5 to 3.6.
Unfortunately, I get the following error whenever I try to run php7.4 craft upgrade all:

root@debian-4gb-nbg1-1:/files# php7.4 craft update all
Fetching available updates ... done
Performing 2 updates:

    - craft 3.5.18 => 3.6.4.1
    - campaign 1.18.1 => 1.18.2

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

Exit Code: 1(General error)

Working directory: /files

Output:
================

    Craft can’t connect to the database. Check your connection settings.

Yii Migration Tool (based on Yii v2.0.40)

Error Output:
================
PHP Warning:  Module "curl" is already loaded in Unknown on line 0
Exception 'craft\errors\DbConnectException' with message 'Craft CMS requires the PDO_MYSQL driver to operate.'

in /files/vendor/craftcms/cms/src/db/Connection.php:161

Caused by: Exception 'yii\db\Exception' with message 'could not find driver'

in /files/vendor/yiisoft/yii2/db/Connection.php:642

Caused by: Exception 'PDOException' with message 'could not find driver'

in /files/vendor/yiisoft/yii2/db/Connection.php:710

However, pdo_mysql is definitely installed.
Is anyone able to help me?


texts: Refresh "hidden" template after login with ajax

texts:
I am trying to create a seamless user login interaction with a modal form using ajax. Let's say I have a navigation template _navigation.html

    {% if currentUser %}
    {{ currentUser }}
    — {{ "My Orders"|t }}
    — {{ "My Addresses"|t }}
    — {{ "My Cards"|t }}
    — Logout
    {% else %}
      {{ "Login"|t }}
    — {{ "Register"|t }}
    {% endif %}

After successful login I would like to refresh the view by loading the template again (using jquery.load()). Since the template is "hidden" I can't access it. If I make the template "visible" all works, but naturally I would like the template to stay "hidden".

Is there any way to achieve this?


texts: Craft paginate not working in merge Queries

texts:
My Code:

{% set Entries              =   craft.entries.section('not loanConsultants').search(searchQuery).orderBy('dateCreated desc').all() %}

{% set loanConsultants      =   craft.entries.section('loanConsultants').type('loanConsultants').search('title:'~searchQuery).orderBy('dateCreated desc').all() %}

{% set Branch               =   craft.entries.section('loanConsultants').type('branches').search('title:'~searchQuery).orderBy('dateCreated desc').all() %}

{% set loanConsultantsMerge = loanConsultants|merge(Branch) %}

{% set mergeResults         = loanConsultantsMerge|merge(Entries) %}

Pagination code:

{% paginate mergeResults as pageInfo, pageEntries %}
{% for entry in pageEntries %}

{{ entry.title }}

{% endfor %}

{% if pageInfo.prevUrl %}Previous Page{% endif %}

{% if pageInfo.nextUrl %}Next Page{% endif %}


texts: Maintaining a relationship of parent from children selected through entry field

texts:
Not sure that is the best title but:

I have a Section called Research Projects. An entry from this section contains a number of images, videos and audio entries in a grid chosen through an Entry Field. At the moment when one of the grid items is selected it displays a modal showing the details of that entry. There is no issue is showing a relationship as the info is displayed on the same page.

My question is if I chose to show the entry selected on a new page how would I show the relationship to the page it appears on / came from? Perhaps as a title from the previous page or a back button.

I am not using a structure as video, image items can appear in multiple projects.

Hope that makes sense and thank for any help anyone can offer.

Scott


texts: Is there a way to merge multiple Plain Text fields into a Matrix or Table field?

texts: I have a site we are importing into Craft (using https://github.com/boboldehampsink/import/) and it has about 10 fields setup called feature1, feature2, ... feature10 that are Plain Text. After I import them, rather than leave them all as individual text fields, is there a way to merge them into a matrix block or table field?  I have the data in a CSV as well that I am using for the import.


texts: Import a large number of assets via feedme

texts:
I have 224,559 assets (images) I need to import and assign to entries. Assets are currently stored in folders that match their original asset id. Imported assets will be stored on s3. I'm using feedme for the import so far.

I have json for both the assets and entries. A typical record for assets looks like:

{
    "title": "Ceiling decor at The Atomic Tiki in Memphis, TN",
    "import": {
        "key": "asset-1197-16772",
        "source": "TikiTime",
        "sourceUrl": "https://tikitime.com/images/locations/1197/16772_jumbo.JPG",
        "outputPath": "/Volumes/Sites/Personal/mytiki.life/web/uploads/master-assets/tiki-bars/1197/16772.jpg",
        "date": "2020-04-23T08:09:01+00:00"
    }
},

A typical entry json entry looks like:

{
    "title": "Sun Hung Heung Green Bucket",
    "originalId": 2,
    "assets": [
        {
            "title": "Sun Hung Heung Green Bucket - 2-153663",
            "key": "ooga-mooga-asset-2-153663",
            "outputPath": "/Volumes/Sites/Personal/mytiki.life/web/uploads/master-assets/tiki-mugs/2/153663.jpg"
        },
        {
            "title": "Sun Hung Heung Green Bucket - 2-153664",
            "key": "ooga-mooga-asset-2-153664",
            "outputPath": "/Volumes/Sites/Personal/mytiki.life/web/uploads/master-assets/tiki-mugs/2/153664.jpg"
        }
    ]
}

The import.sourceUrl property is the local file path of the file. All the images are broken up into folders that match their original entry ids.

I've setup a field in the entry channel for the asset relationship that's restricted to a single folder with a subdirectory pattern: {section.handle|kebab}/{id} -> tiki-mugs/875

Obviously the new (imported) entry id doesn't match the old entry id so… I could export all the new entry ids and then rename all the folders to match but that would be painful.

I'm having trouble figuring out how to relate the assets with the entries and get them in the correct directories.

I thought I could possibly leave the files in their current location and run the asset index command. That would create the records. Then somehow assign them in feedme. If I did that would the assets be moved when the entry gets saved?

Any other ideas?


texts:
What's the most performant way to get reverse related entries within an Element Query?

Here's a contrived example of this.

I have thousands of "book" entries and thousands of "collection" entries. I need to generate a list of all the books and present a comma separated list of the collections it appears in. Some books might be in 10 collections, some might be in 50+.

Unfortunately, the code below creates the n+1 query problem. But I can't eager load this because this is a reverse relationship.

How could I achieve this in a more performant way?

<?php

$query = Entry::find()
    ->section('books')
    ->all();

foreach ($query as $book) {
  $data[] = [
    "title" => $book->title,
    "author" => $book->authorName,
    "inCollections" => $this->_getBookCollections($book)
  ];
}

// ... later in the class

private function _getBookCollections($book)
{
    $query = Entry::find()
      ->section('collections')
      ->relatedTo($book)
      ->all();

    return implode(", ", ArrayHelper::getColumn($query, "title"));
}


texts:
I am trying to migrate blog posts from WordPress to Craft CMS through the Feed Me plugin.

First, I export posts in .xml file from Wordpress. Then, I import in Craft CMS.

All things are good except the category and tags. It imports the category and tags from .xml file but it is not able to separate the category and tags.

Here the few code of category and tags means how it look in .xml

<category domain="post_tag" nicename="computer"><![CDATA[computer]]></category>
<category domain="post_tag" nicename="corporate"><![CDATA[corporate]]></category>
<category domain="post_tag" nicename="employee"><![CDATA[employee]]></category>
<category domain="post_tag" nicename="expert"><![CDATA[expert]]></category>
<category domain="post_tag" nicename="forensics"><![CDATA[Forensics]]></category>
category domain="category" nicename="forensics"><![CDATA[Forensics]]></category>
<category domain="category" nicename="infosec-training"><![CDATA[InfoSec Training]]></category>
<category domain="post_tag" nicename="warlock"><![CDATA[warlock]]></category>
<category domain="post_tag" nicename="witness"><![CDATA[witness]]></category>

And also the screen shot of mapping and and how it looks in section.

Mapping

Section View

How can I separate these?


texts: Trouble calling a plugin's controller function from within an event listener function

texts:
I am working on extending the formbuilder2 plugin to call and pass the $event variable to a custom Controller after FormBuilder2 has initialized the "onBeforeSave" event within the FormBuilder2 Entry_Controller.

Background Info

Trying to extend the Formbuilder2 plugin
My plugin is called FormBuilder2ExtensionPlugin
Trying to call a Controller Function from within my FormBuilder2Extension_NotifyController and pass $event variables.
Within my FormBuilder2Extension_NotifyController, I am calling the actionNotifyAdmin($event) function.

My Plugin Logic:

FormBuilder2 Plugin saves entry and initializes the "onBeforeSave"
event.
FormBuilder2Extension Plugin listens for "onBeforeSave"
event, and triggers a custom controller function to run. Note: Must be
able to pass the $event variables to the new FormBuilder2Extension
controller function as well.
FormBuilder2Extension Controller will then parse $event data, and
run other FormBuilder2 Controller & Service functions using the $data, so I will need to link from FormBuilder2Extension Controller functions to Formuilder2 Controller functions.

My Problem:

Cannot figure out how to run a Controller Function from within the init() event listener and pass the $event variables as well.

My Current Code: (within main plugin file)

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

       craft()->on('formBuilder2_entry.beforeSave', function(Event $event)
       {

         $url = UrlHelper::getActionUrl('formBuilder2Extension/notify/notifyAdmin', array('event' => $event));

         return;
       });
   }

Closing Remarks:

It works if I use a service function.

Example: craft()->formBuilder2Extension_notify->notifySubmitterOfSubmission($event);

But I would rather not rewrite the same Controller & Service functions that formbuilder2 has already written and place it within my service folder.

Any thoughts…? Thanks!


texts: Creating a modal warning for an external link?

texts:
I'm attempting to return a pop-up warning for users who click an external link on my site. The issue is, the functionality must still be there if JS is disabled. I think this would leave PHP as my only option, so would this be accomplished with a custom plugin? I've seen sites accomplish something similar with a separate redirect php include with the link destination in a query string. My experience developing Craft plugins is virtually nil so forgive my ignorance- but would that look like a plugin that finds and rewrites all the external links' hrefs on the existing page, returns the html for the modal (appends a fullscreen div to the dom), and populates a "continue to external link" anchor based on the original link in the query string? Am I on the right track here?

Thank you!


texts:
wonder if a guru could help, I am nearly there, just stuck on the right call.

Building a standard css/jquery responsive tab solution. I am pulling back child entries to populate a parent page with said tabs. The problem is the for loop, not being able to close the unordered list before the next part. I wonder if anyone could help please.

{% set entries = craft.entries.section('country').level(3) %}

{% for entry in entries %}

{{entry.pageTitle}}

{{entry.pageTitle}}

{{entry.pageTitle}}

{% endfor %}


texts: Simpler way to code up a category conditional?

texts:
I've coded up conditional for categories. I'm still new to Twig and curious if there is a simpler way of coding the following.

{% for feedItems in craft.entries.section('news').limit(null).offset(1).find() %}

{% set parent = craft.categories.slug('parent-category').first() %}
{% set child = feedItems.generalCats.descendantOf(parent).level(2) %}

{% set parentLvl = feedItems.generalCats.level(1).find() %}
{% set childLvl = feedItems.generalCats.level(2) %}

{% if childLvl | length %}
    {% for category in child.limit(1) %}
        {% if child.count() > 1 %}
            {{ parent.title }}
        {% else %}
            {{ parent.title }}
        {% endif %}
    {% endfor %}
    {% else %}
    {% for category in parentLvl %}
        {{ category.url }}
    {% endfor %}
{% endif %}

{% endfor %}

This is currently outputting the child category if there isn’t more than one child cat selected.
If there is more than 1 child cat selected it outputs the parent category.
If any of the former is false (no children or parent) it outputs one of the other 1st lvl cats (doesn’t have children)


texts: How can I add images to field instructions?

texts: I'd like to have images in my field instructions, but adding the Markdown code doesn't work, nor does HTML. Is there a way to include images and other HTML within?


texts: Using pagination with Ajax load.. help need on JS

texts:
I am using a template which has a 'LOAD MORE' button beneath a grid of entries (entries 1-10). Click this link loads addition content to the grid via AJAX from another page (which contains entries 11-20). There is also a second page which has entries 21-30. The code looks like this:

  Load More
  No more items to show

There is JS that will change the p2.html to p3.html when it is clicked, so the second time the button is click the 3rd set of entries is added.

I would like some help as to how to change the JS to make this work with craft pagination. I can add

{{ paginate.nextUrl ~ queryString }}

as the target URL which works for the first click (the link is rendering out as URL/section/p2 and the content is added via AJAX in the correct place) but I need this to change to /p3 etc with each click.

It seems as though the LOAD MORE function in the JS is mentioned in 2 places:

/* isotope load more function
------------------------------------------------*/
function isotopeLoadMore(grid,el,url,datas) {

  el.parent(".load-isotope").addClass('loading');

  if (url === '#' || !url) { url = srvars.ajaxurl }
  var addData = ''; if (datas) { addData = { action:'sr_load_more', o:datas }; }
  jQuery.ajax({
    type:'POST',      // this might lead to issues for html template
    url:url,
    data: addData,
    dataType:"html",
    error: function () {
      el.parent(".load-isotope").addClass("disabled");
    },
    success: function(response) {
      //console.log(response);
      if (response) {
        setTimeout(function(){
          var items = jQuery( jQuery(response).find('#'+grid.attr('id')).html());
          items.imagesLoaded(function(){
            grid.append( items ).isotope( 'appended', items);
            animateOnScroll(false);
            // init video bg for appended items
            if(jQuery().phatVideoBg) { grid.find('.videobg-section').phatVideoBg(); }
          });
          el.parent(".load-isotope").removeClass('loading');
        },500);
      } else {
        el.parent(".load-isotope").addClass("disabled");
      }
    }
  });

}

AND:

/* Load More isotope
------------------------------------------------*/
var loadMore = jQuery('.load-isotope:not(.disabled) a');

loadMore.click(function(){
  var el = jQuery(this);
  if(el.data("loadpage") === undefined) { el.data("loadpage","2"); }
  else { el.data("loadpage", parseInt(el.data("loadpage"),10)+1); }
  var   related = el.data('related-grid');
  var   href = el.attr('href').replace("/2", '/'+el.data("loadpage"));
  href = href.replace("2", el.data("loadpage"));
  var datas = '';
  if(el.data("options") !== undefined && el.data("options")) { datas = el.data('options').replace("paged=2", "paged="+el.data("loadpage")); }
  isotopeLoadMore(jQuery('#'+related),el,href,datas);
  return false;
});

Any help with this would be massively appreciated


texts: Is it possible to order related entries by relevance of tags?

texts:
I have a set of entries which each have 0 or more tags (no limit). For each entry, I am aiming to display 3 'related entries', related by the tags field.

e.g. If entry 1 is tagged with 'apples', 'bananas' and 'pears', then the first results returned would be entries with all 3 tags, followed by 2, followed by just one, then those with none of the tags.

Is this possible? I can't see anything in the documentation about ordering by relevance of the 'relatedTo' parameter.


texts: Does Craft Commerce support Worldpay refunds?

texts: If anyone else is using Worldpay with Craft Commerce (am starting to feel like I'm one of a very small number), do you have order refund functionality? As in, the Refund button that exists on the order page with the control panel.


texts: How to duplicate a matrix field programatically in Craft 3.1?

texts:
Is there a "Craft" way of handling this in 3.1?

Solutions to this question on SE are based on older versions of Craft which no longer work.

Custom fields can be duplicated by doing:

$newEntry->customFieldHandle = $masterEntry->customFieldHandle;

I've tested this with Plain Text, Number, Dropdown, Date/Time, Entries fields and it works fine.

I tried this with a matrix field (not expecting it to work, as I appreciate Matrix fields are handled differently). The matrix content and fields are copied across when a newEntry is generated, but is deleted from the masterEntry.

Example module:

protected static function createNewEntry()
{
    Event::on(
        Elements::class,
        Elements::EVENT_AFTER_SAVE_ELEMENT,
        function(ElementEvent $event) {

            // Ignore any element that is not an entry
            if (!($event->element instanceof Entry)) {
                return;
            }

            // Ignore entries that are new because they have no id
            if ($event->isNew) {
                return;
            }

            // Fetch current entry and assign siteid
            $masterEntry = Craft::$app->entries->getEntryById($event->element->id, $event->element->siteId);

            // Basic Craft fields...
            $newEntry = new Entry();
            $newEntry->sectionId = $masterEntry->sectionId;
            // more craft fields here...

            // Custom fields
            $newEntry->contentLongtitle = $masterEntry->contentLongtitle;
            // more craft custom fields here...

            // Matrix field
            // Doing this copies the matrix content to newEntry
            // but deletes it from masterEntry
            $newEntry->matrixSchedule = $masterEntry->matrixSchedule;

            $success = Craft::$app->elements->saveElement($newEntry);
            // Handle success/failure logic here...

        }
    );
}


texts: Users are always logged out on front end

texts:
Users are always logged out on the front end on my Craft website.  Even when logged in as admin I can access the CMS but on the front end user session always returns the following.

Craft\UserSessionService Object
(
    [_identity:Craft\UserSessionService:private] =>
    [_identityCookie:Craft\UserSessionService:private] =>
    [_userModel:Craft\UserSessionService:private] =>
    [_userRow:Craft\UserSessionService:private] =>
    [_sessionRestoredFromCookie:Craft\UserSessionService:private] =>
    [_dontExtendSession:Craft\UserSessionService:private] =>
    [allowAutoLogin] => 1
    [guestName] => Guest
    [loginUrl] => Array
        (
            [0] => /site/login
        )

    [identityCookie] =>
    [authTimeout] => 259200
    [absoluteAuthTimeout] =>
    [autoRenewCookie] => 1
    [autoUpdateFlash] => 1
    [loginRequiredAjaxResponse] =>
    [_keyPrefix:CWebUser:private] => 4e3924125ff89a395a13e8e5580209e2
    [_access:CWebUser:private] => Array
        (
        )

    [behaviors] => Array
        (
        )

    [_initialized:CApplicationComponent:private] => 1
    [_e:CComponent:private] =>
    [_m:CComponent:private] =>
)

Does anyone have any idea why this could be happening?


texts: Sprout SEO Re-saving Entries and metadata CPU 100%

texts:
I added an element metadata field to my Sprout setup so that I could control things and automate a bit: Element Metadata Field

However, upon saving these field layouts, Sprout wants to re-save all entries. Fair enough, I quickly went through and added the layouts to all my sections. However, I've got 8686 entries, and so far this has taken 5+ hours on a 2 CPU server on Digital Ocean where the CPU is absolutely pegged. This server has 2GB of memory, and 3/4 is reserved for php/craft.

It seems every time I saved, it created new tasks for saving all entries, new regenerating search terms (it created thousands of regen search term tasks), etc. With multi-locale support for 10+ languages, this seems like it unleashed destruction.


texts: Built in validate of title when using EntryModel?

texts:
The example below will continue to save entries with the same title and slug.

Is there a built in validation when using craft()->entries->saveEntry?

$entry = new EntryModel();
$entry->sectionId = $sectionId;
$entry->getContent()->setAttributes(array(
            'title' => '123',
        ));
$re = craft()->entries->saveEntry($entry);


texts: How to limit Expanded Search (plugin) query results for pagination?

texts:
I'm using the Expanded Search plugin to display results of the search query with an excerpt of the text matching the query for each result. I want to limit the results to 10 per page, using pagination.

Does anyone know how I could limit the expandedResults from the Expanded Search plugin?

The pagination works with the following code, but the Expanded Search results does not respect the limit to entries and instead shows all the results without limit, on each paginated page (e.g. If I have 14 results, the pagination will have 2 pages available, but all 14 results are displayed across both pages):

Expanded Search Results

  {# Get the user's search query from the 'q' query-string param #}
  {% set searchQuery = craft.app.request.getParam('q') %}

  {# Fetch entries that match the search query #}
  {% set entries = craft.entries()
      .search(searchQuery)
      .orderBy('score')
      .limit(10) %}

  {# Paginate the entries #}
  {% paginate entries as pageInfo, pageEntries %}

  {# Get the search result excerpts from the Expanded Results plugin #}
  {% set expandedResults = craft.expandedSearch.search(searchQuery, { length: 155 }) %}

  {% if entries|length %}

      {# List search result entries #}
      {% for result in expandedResults %}

{{ result.entry.title }}

              {{ result.entry.url }}

          {% if result.matchedValue %}
{{ result.matchedValue | raw }}
{% else %}
No preview available
{% endif %}

{% if result.entry.dateUpdated %}{{ result.entry.dateUpdated | date("j F Y") }}{% else %}{{ result.entry.postDate | date("j F Y") }}{% endif %}

      {% endfor %}

      {# Display pagination if there are more than 10 entries #}
      {% if pageInfo.prevUrl or pageInfo.nextUrl %}
            {% if pageInfo.prevUrl %}Previous Page{% endif %}
            {% for page, url in pageInfo.getPrevUrls(2) %}
                {{ page }}
            {% endfor %}
            {{ pageInfo.currentPage }}
            {% for page, url in pageInfo.getNextUrls(2) %}
                {{ page }}
            {% endfor %}
            {% if pageInfo.nextUrl %}Next Page{% endif %}

Page {{ pageInfo.currentPage }} of {{ pageInfo.totalPages }}

      {% endif %}

  {% endif %}

I've also tried it this way, where I'm using the expandedResults for the result excerpt only. As expected, the pagination and entry limit is this time respected, but this time, every result excerpt displays the excerpts from all the results (e.g. I have 14 results, split between 2 paginated pages but each result features all 14 excerpts):

Entry Results with Partial Expanded Search Result

{# List search result entries #}
{% for entry in pageEntries %}

{{ entry.title }}

        {{ entry.url }}

    {# Show excerpt with matching value if available #}
    {% for result in expandedResults %}
        {% if result.matchedValue %}
{{ result.matchedValue | raw }}
{% else %}
No preview available
{% endif %}
    {% endfor %}

{% if entry.dateUpdated %}{{ entry.dateUpdated | date("j F Y") }}{% else %}{{ entry.postDate | date("j F Y") }}{% endif %}

{% endfor %}


texts: How do I build a LIKE query with DbCommand/Query Builder?

texts:
I'm trying to construct a fairly simple LIKE query using the Query Builder, and I'm struggling. Here's the SQL that I want:

SELECT `id` FROM `craft_somecustomtable` WHERE ((`somecolumn` LIKE '%foo%') OR (`somecolumn` LIKE '%bar%'))

I've ran the above query in Sequel, with results.

For the Query Builder, here's what I've got so far:

$query = craft()->db->createCommand();
$query->select('id');
$query->from('somecustomtable');
$query->orWhere(array(
    'somecolumn' => 'LIKE %foo%',
));
$query->orWhere(array(
    'somecolumn' => 'LIKE %bar%',
));

This produces the following query, which obviously doesn't work as intended:

SELECT `id` FROM `craft_somecustomtable` WHERE ((`somecolumn`='LIKE %foo%') OR (`somecolumn`='LIKE %bar%'))

I've also tried adding the LIKE directive like this:

$query->orWhere(array(
    'somecolumn LIKE' => '%bar%',
));

This produces an error, however.


texts:
Is there a way to limit the number of sessions per user? That is, I can be logged into one machine/browsers only once.

It is essential that we limit the number of times a user can be logged in and I can't seem to find a way to do so.

Has anyone dealt with this situation?


texts: Can I convert rich text field to have plain text output - with carriage returns?

texts:
I am exporting some fields to an XML feed. There is a rich text field with typically 4 paragraphs in it.

The default export kicks out:

Some text
 tags as well as stuff like .

This is easy to remove with |striptags.

However, this results in text that doesn't have proper spacing and removes any intended carriage returns.

I can fix the spacing with a

|replace(".", ". ")

But I'd rather have the the Paragraphs to still have carriage returns as intended. I know I can add in the right UTF-8 symbol, but I don't want this in the data, I just want the spacing and carriage returns as if it were a plain text field and not to have the UTF-8 symbols in the feed itself.

http://www.fileformat.info/info/unicode/char/000D/index.htm

Any help, much appreciated.


texts: How to redirect requests from root to subfolder (if they exist)?

texts:
I am in the process of migrating a website from Wordpress to Craft and need to redirect the blog entries. In the existing site, the entries are in the root of the site, eg:

example.com/this-is-a-blog-post

In the Craft site, the post will be under a /blog subdirectory like so:

example.com/blog/this-is-a-blog-post

Assuming the slugs are the same, how would I go about creating 301 redirects for all existing posts?


texts: License alert message for mysite.com, but not www.mysite.com

texts:
I have a client website that is reachable at www.mysite.com and mysite.com. Everything on the site functions fine, and the Craft CP can be accessed at either www.mysite.com/admin and mysite.com/admin.

When accessed form mysite.com/admin, the user gets the "The license located at config/license.key belongs to mysite.com. Transfer it to this domain?" message.

This hasn't affected anything yet, but I'm worried that Craft might suspend the license because of the two different domains. It is also worrying the client anytime they login at mysite.com/admin.

Any tips on how to permanently clear the message on both domains, or somehow let the licesne know that it is the same site on both www.mysite.com and mysite.com?

Thanks!


texts: How to modifyPaymentRequest() in Commerce 2?

texts:
Looks that I really used every functionality in my plugin that changed or has been removed in Commerce 2. :(

I need to modify paypal transactionId and description what i did as follows in Commerce 1:

public function commerce_modifyPaymentRequest(array $request){
  // set (paypal) payment description
  $request['transactionId'] = substr($request['order']['number'], 0, 7) . "*";
  $request['description'] = "Bestell ID: " . substr($request['order']['number'], 0, 7) . "*";
}

How can I do that in Commerce 2?


texts:
I am going to build a boat catalog.

Boat products x 40
Types of product x 3
Suppliers of products

I was wondering what the best storage setup?

For boat and suppliers these could be entries and categories, eg:

Boats = entries x 40
Suppliers = Categories x 9
Type = Categories x 3

But does it make more sense to use suppliers as entries fields and relate them to products as 'parents'?

Are there specific template benefits later on that can help steer the decision?


texts:
I have a little issue with Redactor. Whenever I have a link within a link:

main link link within link

Redactor automatically modifies it to this:

main link link within link

Is there a way to stop this auto-modification?


texts:
Randomly getting the "Integrity constraint violation"  sql error on saving entry from backend.  There no apparent cause of this at least not that I can see, because the same post saves without errors when I try again.

Craft version is : 2.6.3017

Here is the error and Stack trace:

[error] [system.db.CDbCommand] CDbCommand::execute() failed: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db_production`.`craft_relations`, CONSTRAINT `craft_relations_targetId_fk` FOREIGN KEY (`targetId`) REFERENCES `craft_elements` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `craft_relations` (`fieldId`, `sourceId`, `sourceLocale`, `targetId`, `sortOrder`, `dateCreated`, `dateUpdated`, `uid`) VALUES (:row0_col0, :row0_col1, NULL, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7), (:row1_col0, :row1_col1, NULL, :row1_col3, :row1_col4, :row1_col5, :row1_col6, :row1_col7), (:row2_col0, :row2_col1, NULL, :row2_col3, :row2_col4, :row2_col5, :row2_col6, :row2_col7), (:row3_col0, :row3_col1, NULL, :row3_col3, :row3_col4, :row3_col5, :row3_col6, :row3_col7), (:row4_col0, :row4_col1, NULL, :row4_col3, :row4_col4, :row4_col5, :row4_col6, :row4_col7), (:row5_col0, :row5_col1, NULL, :row5_col3, :row5_col4, :row5_col5, :row5_col6, :row5_col7).

[error] [exception.CDbException] CDbException: CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db_production`.`craft_relations`, CONSTRAINT `craft_relations_targetId_fk` FOREIGN KEY (`targetId`) REFERENCES `craft_elements` (`id`) ON DELETE CASCADE) in /var/www/mysite.com/craft/app/framework/db/CDbCommand.php:358

Stack trace:
#0 /var/www/mysite.com/craft/app/etc/db/DbCommand.php(370): CDbCommand->execute(Array)
#1 /var/www/mysite.com/craft/app/services/RelationsService.php(74): Craft\DbCommand->insertAll('craft_relations', Array, Array)
#2 /var/www/mysite.com/craft/app/fieldtypes/BaseElementFieldType.php(291): Craft\RelationsService->saveRelations(Object(Craft\FieldModel), Object(Craft\EntryModel), Array)
#3 /var/www/mysite.com/craft/app/services/ElementsService.php(1608): Craft\BaseElementFieldType->onAfterElementSave()
#4 /var/www/mysite.com/craft/app/services/EntriesService.php(176): Craft\ElementsService->saveElement(Object(Craft\EntryModel))
#5 /var/www/mysite.com/craft/app/controllers/EntriesController.php(462): Craft\EntriesService->saveEntry(Object(Craft\EntryModel))
#6 /var/www/mysite.com/craft/app/framework/web/actions/CInlineAction.php(49): Craft\EntriesController->actionSaveEntry()
#7 /var/www/mysite.com/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#8 /var/www/mysite.com/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#9 /var/www/mysite.com/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#10 /var/www/mysite.com/craft/app/framework/web/CWebApplication.php(282): CController->run('saveEntry')
#11 /var/www/mysite.com/craft/app/etc/web/WebApp.php(836): CWebApplication->runController('entries/saveEnt...')
#12 /var/www/mysite.com/craft/app/etc/web/WebApp.php(287): Craft\WebApp->_processActionRequest()
#13 /var/www/mysite.com/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#14 /var/www/mysite.com/craft/app/index.php(73): CApplication->run()
#15 /var/www/mysite.com/public/index.php(15): require_once('/var/www/mysite...')
#16 {main}
REQUEST_URI=/admin/entries/blog/new
HTTP_REFERER=https://mysite.com/admin/entries/blog/new

Anyone ever faced this error? is this a Craft bug?


texts:
We have always utilised modules-forms to create our forms for our website. We've just downloaded Free Form to integrate with our marketing automation tool as the simple form wouldn't work how we wanted it to.
Now I'm trying to figure out how to actually embed a form within an actual page.
Modules-forms seems to be the only way to add forms to the site.
Please help
Bree


texts: onBeforeSaveUser event does not fire if basic user fields do not validate

texts:
I have additional fields I check for in the onBeforeSaveUser event and add the errors to the errors array. The problem is my code doesnt even run if they miss the main fields or if the email is already in use or something like that... I would like to return ALL validation errors, not just the default field errors first.

If I go to my form and just press submit without filling anything it out it only complains about the username, email address and password. If I just fill those fields out, then it comes back and complains about all my other fields (a la my event handler). This is unexpected behavior. Am I doing something wrong or is there a way to address this?


texts:
I've a trigger on my frontend that requires an action. I've started from the businessLogic template but I'm getting a 404 and can't find why.

My function

public function actionExampleAjax()
    {
      // Stuff
    }

How I call it

$.post('/actions/businessLogic/actionExampleAjax', data, function(response, textStatus, jqXHR) {
    // Stuff
});

The server response ( 404):

The system is unable to find the requested action "actionExampleAjax".

The action trigger is set to:

'actionTrigger' => 'actions'

The same approach works fine with a form submission, but I don't want to use a form in this case.

Any suggestion?


texts: Using an Entry's Added Form in a template in Sprout Forms

texts:
Using Sprout Forms and have added the Form Name > Select a Form to the Entry's field layout.

After I select a form on this Entry, what do I hook into to get this to display on my template?

I know from the documentation that you can specifically pass in the form's Handle {{ craft.sproutForms.displayForm('myForm') }}, but what do I need to do to get the drop-down form to display if there is one selected?


texts: How to set up Google Tag Manager correctly

texts:
First time user here, can any please provide information on how to best implement the GTM tag container?

Is it possible to hard code it? Or is the only way to add a plugin?


texts: Creating a web app notification system/center?

texts:
Ok, just thinking out loud and trying to work out the best way to achieve something. I have a community site with roughly 25k users.

I would like to create a way to send messages to those users within the front end of the site. This might be, for example, a notification of a new entry based on a set of criteria or even a message from the site admin to every user advising of a new feature.

The user should be able to view the message, which marks it as read and have the ability to delete it. All messages would live in a notifications page.

I’m just wondering if this is something that’s possible to achieve using Craft (via a plugin) or are there other services that are better suited to this. I can’t find anything online, everything seems geared towards push notifications which is slightly different to what I’m after.

Any thoughts as I can’t quite get my head around a way to achieve this.

Thanks!


texts: Running custom query save result to xml file

texts:
For an upcoming project one of the requests is that the client needs to be able to run a few custom queries on a specific section (queries are fixed, we know what these will be in advance) and then save the output to an xml file on the server. Bonus points if we can do this with a cron job, say daily.

I've been looking at several plugins (Sprout reports, Zenbu) but none really do what I need out of the box.

How would I go about handling this? Sorry if this question is too general, just looking for pointers on where to start. Any input appreciated!


texts: Craft.log showing Buggy iconv installed. Will fallback to mbstring

texts:
I'm curious if others are seeing a similar error in their Craft logs.  It says:

  Buggy iconv installed.  Will fallback to mbstring.

It's repeated over and over seemingly with almost every request.

It's a pretty simple server, setup using the default setting from Laravel Forge on Digital Ocean.

Any ideas on how to fix it?


texts: Using the Matrix field to output content in a slideshow

texts:
I want to use two block types in one Matrix field. These blocks will be output in a div. At the moment my code adds a new
 for each block type. How can I output two block types in the same
?

  {% for block in entry.homepageSlider %}

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

{{ block.sliderHead }}

{{ block.sliderText }}

        {{ block.sliderButton }}
      {% endif %}

      {% if block.type == "sliderImage" %}
        {% set image = block.image.first() %}
        {% if image %}

        {% endif %}
      {% endif %}

  {% endfor %}


texts:
I am trying to figure out how to only display the slider on the homepage so that it does not show in other page.

I am getting close but not sure what code I should write. Here is what I could think of but does not work..

{% if slider in homepage %}
    slider goes here...
{% endfor %}

I appreciate any suggestion to what the correct way of displaying content in specific page/section/entry ...


texts: How does "Use this field's values as search keywords" work with a Matrix field?

texts:
I'm fine-tuning a search results page and have noticed that "Use this field's values as search keywords" is included both on the matrix field itself, and within each block type / sub-field. I currently have the matrix field checked, but the Form block type / text field unchecked.

When I search my site using the following code:

{% set searchQuery = craft.app.request.getParam('q') %}
{% set entries = craft.entries.search(searchQuery).orderBy('score').limit(20) %}

The content inside the Text field of the Form block shows up in search results. This seems kind of backwards or broken; it's the main content Matrix field for the site, and there are some fields in there that I want to search by, and some that I don't. How do I achieve this?

Additional question; where is this checkbox actually documented? I can't find a description of what "Use this field's values as search keywords" actually does.


texts: getResourcePath() for folders in a plugin

texts:
I have a plugin that has an folder inside of it's resources. I need to iterate through those files.

To get the path, I tried craft()->resources->getResourcePath('folder-name'), but it seems to only succeed if the file exists, not a folder.

I want the folder so I can use IOHelper::getFolderContents($folder).

Do I just need to build the path myself ($folder = craft()->path->getPluginsPath() . 'myplugin/resources/svg/';), or am I missing something?


texts:
I have limited knowledge of PHP but I would like to try and create a widget. Basically all it needs to do is provide some text and a link to the user profile page as you can't route directly to that page on login. Would someone be able to point me in the write direction please. I have in my grWidget.php file:

<?php

namespace Craft;

class GrWidget extends BasePlugin
{
  function getName()
    {
      return Craft::t('Gareth Widget');
    }

    function getVersion()
    {
      return '1.0';
    }

    function getDeveloper()
    {
      return 'Gareth Redfern';
    }

    function getDeveloperUrl()
    {
      return 'http://garethredfern.com';
    }
}


texts:
The upgrade logs for ethercreative/seo says to backup before upgrading, but gives no explaination on how to fix the issues if you get them.

bash-4.4# ./craft  seo/upgrade/to-new-data-format
Exception 'yii\db\Exception' with message 'SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='
The SQL being executed was: SELECT `el`.`type`, `el`.`id`, `fields`.`handle`
FROM `craft_fields` `fields`
INNER JOIN `craft_fieldlayoutfields` `flf` ON `flf`.`fieldId` = `fields`.`id`
INNER JOIN `craft_fieldlayouts` `fl` ON `fl`.`id` = `flf`.`layoutId`
INNER JOIN `craft_elements` `el` ON `el`.`fieldLayoutId` = `flf`.`layoutId` AND `el`.`type` = `fl`.`type`
WHERE `fields`.`type`='ether\\seo\\fields\\SeoField''

in /var/www/codebase/vendor/yiisoft/yii2/db/Schema.php:664

Error Info:
Array
(
    [0] => HY000
    [1] => 1267
    [2] => Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='
)

Is this an issue anyone knows how to fix?


texts: How to pass the matrix attributes to views without too much ceremony

texts:
Consider the following example:

master.twig

{% for module in entry.main_contents %}
  {% include '_modules/' ~ module.type with module only %}
{% endfor %}

my_awesome_module.twig

<h1>{{ title }}</h1
{{ content | raw }}

In my case obviously I get the twig error Argument 1 passed to Twig_Template::display() must be of the type array
because I cannot pass objects to the include function. In your examples you use the following solution:

master.twig

{% for module in entry.main_contents %}
  {% include '_modules/' ~ module.type with {'data': module} only %}
{% endfor %}

my_awesome_module.twig

<h1>{{ data.title }}</h1
{{ data.content | raw }}

Isn't there a way to pass directly the matrix attributes without encapsulating them in an other array?

p.s.

I hooked in also a twig helper method that returns $model->getContent()->getAttributes() but it seems that the array returned looses all its nested properties ( like the assets list...)


texts: Getting Events from Solspace Calendar using Element API

texts:
I am trying to pull the events from my calendar or calendars through the element api but I am running into an issue with the element type. I found an older post that gave examples but they no longer function correctly. When I try to fetch the data I get this error {"error":{"code":404,"message":"Endpoint has an invalid elementType"}}.
I tried all the examples given in the link and as many other permutations as I could think of to fix the element type but to no avail. Here is the code I have right now:
use Solspace\Calendar\Calendar;

return [
    'endpoints' => [
        'api/events.json' => function() {
            return [
                'elementType' => Entry::class,
                'transformer' => function(Calendar_EventModel $event) {
                  $exceptions = [];
                  foreach($event->exceptions as $exception) {
                    $exceptions[] = $exception->date;
                  }

                  return [
                    'id' => $event->id,
                    'title' => $event->title,
                    'calendarId' => $event->calendarId,
                    'slug' => $event->slug,
                    'startDate' => $event->startDate,
                    'endDate' => $event->endDate,
                  ];
                }
            ];
        }
    ]
];

Any suggestions would be greatly appreciated. Thanks!


texts: When using Settings -> Routes in the CMS with wildcard, routes.php does not work

texts:
Not sure of this is intentional or a bug but, when we add a route using Settings -> Routes in the CMS, routes.php does not work. I guess maybe its due to us using a wildcard and this takes presedence over routes.php

The route we needed to add in the CMS was:

*/<teamid>

The reason we need a wildcard is because I don't want to hard code the page slug as this could be changed by a website administrator which would break functionality.

I added it in the CMS Routes because I can't find out how to add a wildcard in routes.php (perhaps worthy of another question as I would like that answer too!).

in the meantime I have to use routes.php and hard code the slug URLs as follows for each locale:

'contact-us/<teamid>'         => ['template' => 'pages/index'],
'cysylltu-â-ni/<teamid>'         => ['template' => 'pages/index'],

It would be great if I could either:
1) Use the CMS routes with this wildcard AND routes.php still works for all my others, or
2) Add a wildcard in routes.php (my preference)

Thanks


texts:
Apologies if this has been asked before, I couldn't find any documentation specifically about it.

I come from a largely WordPress background but am looking into using Craft Pro for a new client that'll need user registration (real estate website), but I don't want said users to be able to get to the actual CMS backend, rather a simple sort of 'my account' page where it saves their listed properties etc.

Are these sorts of things difficult to pull off in Craft? It seems like this aspect of site dev is quite strictly locked down from what I can extrapolate.


texts: Convert textfield to be used in html class or id?

texts: Does anyone know if it is possible to apply a Twig filter or use escaping to convert a Craft textfield into a html class/id safe string?


texts:
Regarding the Image Transforms and the handling of its files.

Is there a config setting that controls the location (file path) of the Image Transform Files?

By default there is automatically created a new folder which bases it name of the transform-behavior name from the CP (or the code) i.e. _crop1920x1440 in the same directory as the original image is located.

I would like to be able to store all the transformed images in one place i.e. /assets/transforms.


texts:
I'm new to Craft CMS. I have the following single level navigation code:

    Products

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

{{ entry.title }}

      {% endfor %}

How would i adjust this to show a second level navigation in within the parent li? I'm looking for something like this:

    Products

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

{{ entry.title }}
        if (child) { '

child.title
        }

        {% endfor %}


texts: Craft 3 version - How to get entries related to current category only (not children)

texts:
I need some help with syntax on this for Craft 3, please.

I want to use this piece of code:

{% set fruitEntries =  craft.entries.relatedTo({ relatedTo: catP,id: 'and, not '~str }) %}

from this answer here:

How to get entries related to current category only (not children)

It's exactly what I need to do but I'm not sure how to code it for Craft 3 so that I can pull in entries from JUST my 'products' section:

craft.entries.section('products')...

Thanks in advance.

UPDATED INFO.

Category Group = Products

Entry Sections using these categories = Products & Case Studies

My category structure is as follows:

Categories are:

Travelling Irrigators

Superseeded Models

Hydrants
Filters
Pontoons
Pumps

I'm trying to return just the product entries (not case studies) under 'Travelling Irrigators' but not including the 'Superseeded Models'.

The other post does exactly what I need but it returns the case studies too.


texts:
I am trying to get a certain segment of the url. For this i’m setting the slug as a variable which seems to be best practice:

{% set slug = craft.request.getSegment(2) %}

I am interested in the second segment which is http://example.com/projects/awesome-project where “awesome-project” is the desired part.

I never had any problem with this method but in this case it always returns the first segment (projects), regardless of the passed argument. The site is localized.

I have tried various things but am completely clueless, atm. This can be reproduced with every template.

What could be the culprit?


texts:
I am new to Craft but loving its ease of use so far.

I am having a problem however when setting up a plugin to display an error to the user when using the onBeforeSaveEntry hook when a user saves an entry. I am looking to determine the value of a field and then take the user back to the entry page and display an error to the user based on a certain selection. Is this something that can be done with the Craft page when saving an entry?


texts: Feed Me import from CSV ignores decimal point

texts:
I use Feed Me to import values from a .csv file into my entries. Since a day i have an issue i can't explain. I didn't change anything.
Precisely, the issue concerns a number field.
In the .csv file, i have, for example, the value 769.00.
Then i import this value with Feed Me and get the value 76900 in the number field. The decimal point gets ignored:

Here's the csv row:
Artikelnummer,Bestellnummer1,Artikelbezeichnung,Grösse,Farbe,Modelljahr,Notiz,Warengruppe,Hersteller,VKbrutto,UVP,Lagerbestand,Reserviert,Bestellt

18128,S20TONR2716,Stevens Tonga 27.5" Disc Shim. Alivio 22 Gang,16",Fire Red,2020,,Mountainbike,Stevens Bikes,769.00,,1,0,0

It's the same problem as here: https://github.com/craftcms/feed-me/issues/443

My website language is: de-CH

Can anyone give me a hint where this issue comes from?


texts: Password Update form accepting any data for currentPassword

texts:
I'm adding an update password form. This is not a reset password in case of a forgotten pw, but a form that allows users to update at their leisure. I have the current password field name="currentPassword" and the new password field name="newPassword".
When I run the form locally, it works as expected, and does not save the user when the currentPassword value is incorrect. When I run it on our production site, the current password field accepts any value at all, still saves, and changes the password to the new password value despite the current password not being correct. Is there some environment setting I could be missing here that's responsible for this?
Running Craft 3.4.30, no Commerce.


texts:
I have a multi-site Craft install.  I'd like to offer the ability for each site to upload an icon that will be used for favicons.  I noticed a lot of 404s for both /favicon.ico and /apple-touch-icon.png, which appear to be hardcoded in various clients.  I'd thus like to route those URLs directly to the requisite asset files, but on a per-site basis.

I can't just put the files into /web, since that's shared among all the sites, and I want site-specific icons.
I'm hosting assets on S3 (since we are using a load balancer).

Is there a way to do this in Craft without writing a custom plugin to do so?

If there exists a plugin to do this, or if I could do it via Craft directly, that would be wonderful, but I cannot find a way to do so.

If I have to write a custom plugin, I'd have it basically:

Respond to those URLs
Look up the requisite field in Globals for the assets on a per-site basis.
Download the asset file locally (and cache locally in /storage)
Set the proper MIME type
Serve the file from /storage directly

Does this sound reasonable or would there be a better way to handle this?

Thanks in advance for any assistance!


texts:
I am using the Many to Many plugin and wondering if the below is possible.

I have a channel called Model ID. Model ID is then related to two other sections, Memory and SSD. I want to be able to link entries from Memory to entries in SSD via the Many To Many Field within Model ID.

Below is a picture, edited, to show the field layout and the information I have within the Model ID entry. The information within the entry is what I need to pull in to my Memory and SSD section but can not figure it out.

I feel like I am missing something very simple that might not be in the read me document for the plugin.

Any help would be appreciated.

Thanks John


texts: Is it possible to use set the locale manually in a template?

texts:
I've got a generic newsletter template. Now some of our newsletters are in Spanish. It's overkill and more complicated for the admins to bother with settings up different locales, so instead I'd like to set the locale from the entry (currently using a dropdown).

All good, and I can use the |translate(language="") filter to achieve this using the value from the dropdown field.

Now the problem is that when formatting a date, it remains in English because it translated using the current locale, which is English.

I'm wondering whether I can manually override the locale in the template. {% set locale = 'es' %}
or something.

Or if I can force the date to format using a specific locale.

Cheers.


texts: How does the Craft CMS built-in web server works?

texts:
I just found this while using ./craft help in the Craft CMS command line utilities:

- serve                                      Runs the PHP built-in web server.
    serve/index (default)                    Runs PHP built-in web server.

How to use this built-in web server?
How can I edit these web server
settings?
Can i use multiple of these web server at once?

At this time of writing, I didn't find any documentation about that.

I'm using the latest version of Craft CMS (Craft Pro 3.3.17) under Mac OS (10.14.6).


texts: How can Craft-generated Content HTML be accessed via an external PHP app?

texts:
We have a CakePHP 2.5 app for which we'll very soon be building a learning centre/knowledge base. Craft is one of the tools we're considering for that due to its apparent suitability for content editors to create longform, mixed content consisting of text, images and videos without ending up with junk HTML.

For a couple of reasons, it might be preferable for us to have the learning centre content served as part of the app rather than via Craft at a subdomain, so we'd like to know how we would pull in just the generated HTML Content for the actual article content from Craft for embedding within the app's layout.

The learning centre will have four categories, each with an unknown number of articles.

We'd need to be able to reference each article, and maybe each category, from within the app as users can be set parts of the learning centre as tasks.


texts: Recommended High Availablity Architecture

texts:
We are looking to use Craft CMS for an upcoming web project, are there any documented architectures or topologies for deploying into a production setup. This would be for high availablity across multiple regions including both front end assets and databases.

We are likely to consider AWS or Azure for hosting. If there is nothing specific about Craft architectures then would a standard PHP site topology be appropriate?

Thanks

Luke


texts: In a plugin, how do I save an entry with a related entry

texts:
In my plugin, how do I save a relationship when creating a new entry? The example below works for all but the "quiz" relationship.

$triviaSet = craft()->entries->getEntryById($data['itemId']);
$entry = new EntryModel();
$entry->sectionId   = 3
$entry->typeId     = 2
$entry->authorId   = 1;
$entry->enabled    = true;
$entry->getContent()->setAttributes(array(
    'title' => 'My New Entry',
    'score' => $data['score'],
    'quiz' => $triviaSet
));
$success = craft()->entries->saveEntry($entry);


texts:
I'm attempting to create a simple route that points to a template from a plugin. Note that I am attempting to create a page on the front-facing website, not the admin panel. Plugin (named: 'curious') is created with the following method:

craft/plugins/curious/CuriousPlugin.php

class CuriousPlugin extends BasePlugin
{

    ...

    public function registerSiteRoutes()
    {
        return array(
            'example' => 'curious/templates/example'
        );
    }
}

I created a template in craft/plugins/curious/templates/example.html, however, going to the URL /example just gives me a 404. If I visit /admin/curious/example it does exist and works. However, I don't want the page to be in the admin, I would like it to be visible on the front-facing website.

Any thoughts?


texts:
I'm building a plugin in which I would like to use a vendor library, but just adding it to the plugin's composer.json file doesn't seem to be enough to get it installed.

It works when I run composer update in the plugin's root dir but I was hoping there would be a way to have it automatically installed when the plugin is installed?


texts: Adding new structure items to top of structure

texts: Is there a way to add new items in a structure to the top of the list? Now I have to drag it from the bottom to the top.


texts: Link to the product from the shopping cart

texts:
Is it possible to link to the product from the shopping cart?
Something like {{ item.url }} within cart.lineItems

When using {{ product.url }} looping through craft.commerce.products I am getting a list with all product entries.


texts: How to create an advanced route with query strings?

texts:
I have a main structure as my navigation.
Within this structure I have multiple image galleries.
I want to make the image gallery's urls dynamic.

If I define a gallery within the structure entry:
https://mysite.com/sport/gallery/

The url of the images in the gallery (which is a channel) should be:
https://mysite.com/sport/gallery/mygallerySlug?type=gallery&parent=parentEntryId

now I would like to have a route which catches all of the ?type=gallery entries and load the "gallery/_entry" template.

It shouldn't matter how deep in the structure the ?type=gallery is.

I don't seem to be able to do this within the CP, and I've never used advanced routing...

Any help appreciated!

EDIT:

Maybe I need to specify a little further:

I have a structure called "pages" which acts as the main structure.
I have a channel that is called "galleries" where I can upload images and assign a category.
In my main structure I can assign galleries from within a matrix block and choose a category. That way I can regroup multiple entries from the channel "galleries" in a structure entry.

The urls of the galleries should be completely dynamic:

https://mysite.com/sport/gallery holds multiple gallery entries where each of these galleries should have a url the following way:
https://mysite.com/sport/gallery/gallery1
https://mysite.com/sport/gallery/gallery2 ...

another gallery collection could be here:
https://mysite.com/karting/galleries/
whith links like that:
https://mysite.com/karting/galleries/gallery3
https://mysite.com/karting/galleries/gallery4
etc..

I know I could specify the entry url of one gallery the following way in the "galleries" section url settings:

{{ craft.entries.id(65).locale('de').first.uri }}/{slug}
where the id is the id of e.g. https://mysite.com/sport/gallery/ structure entry.

But that works only for one gallery.

I could create a route for "sport/gallery/*" and assign the "gallery/_entry" template to it. But that way I would have to create a route for every gallery, which is not completely obvious, nor intuitive on a editor's point of view.

In fact this is almost a duplicate of this question:
dynamic urls for channel/structure that's linked to the main structure

Cheers
Stefan


texts: Why are PNG images bigger in file size on the (S3) server?

texts:
We've got quite a few PNG image files for a site build, so naturally we're running them through tinypng to reduce size. This works great locally, but when we upload them to assets (S3) the file size is getting huge again.

Pic: https://cl.ly/152u2C2D3g2n

193kb to 440kb in this example ^ which is typical.

Any thoughts?


texts: Getting all the values out of a field as array of values

texts:
I have a multi-select field in my work section

I want to get the values either with the Element api as json or an array of simple values in my template.


texts: Craft 3 Upload To Bluehost - Index.php outside root issue

texts:
I'm having issues uploading my craft3 site to Bluehost.

I've uploaded all the files, ran composer install and it does actually work. However when I go to my domain it shows the raw files/folders and I have to go in to my 'public_html' folder to access the site.

I must note I changed the 'web' folder to 'public_html'.

Because the index.php file is inside the public_html folder my server can't find an index file and therefore shows the raw files.

That's my understanding.

What's the best approach for this?

Thanks


texts:
Having a really difficult times with variants.

Classic t-shirt example: The t-shirt comes in red and blue, where each color has 4 sizes. That means I create 4 variants for red, and the same for blue, thus the product "T-shirt A" contains 8 variants.

Each variant has their own stock level, differing prices, image etc.

For size I created a dropdown field and attached to the variants ("Small, Medium, Large" etc).

I can output all variants at the same time on the page, thus allowing the user to select which one they want, but it's not very slick.

How can I make this look like a single product to the user, and simply have a dropdown for Size and Color? When the user selects something in the dropdown, the size and color would update on the page. More importantly, Craft also has to check the color/size combo to see if it's in stock, and reflect that on the page as well.

In Expresso Store (EE) this was easily done with "modifiers", but I'm sure it's even easier in Craft, I just can't wrap my head around it without some help.


texts: Trying to create a new field returns "General Error: 1030 Got error 1 from storage engine"

texts: I recently updated the site to 3.5.5, so not sure if this has anything to do with it. It's been a while since the last field we created, so can not say for sure if this is correlated. Database on this site is fairly large, but my host dashboard shows no issue with DB memory or storage.


texts: "Single" Entry page gives 404, even though it's enabled

texts:
I added a new Single Entry on my site and populated it with content. When I try to access it at the URL I set, it only returns a 404 error, as if the page were disabled. It's not disabled, though. I also noticed that Live Preview also doesn't show up on the right side as it usually does when I edit this page; is that somehow related?
As far as I can tell, the page should be publicly accessible by all rights. I've set the URI correctly and every other setting that I know of. When I look under All entries, it gives me a clickable URI for my page as if it should work, but when I click this link, I get an inexplicable 404.
I'm using Craft CMS 2.6.3019.


texts: Importing images from external url and saving to entry using plugin

texts:
I'm looking for the correct way to import an image from a url and save it to an entry and in the correct subfolder (uploads/images/{id})

I've created a resource pointing to uploads/images
and the entry field will upload to resource/{id} by default.

As I understand the file also needs to be indexed in the database for it to be visible in the file browser so I can't just save it straight to the file system.


texts: How long will it take Pixel and Tonic to release Craft 3?

texts: I am just wondering, when will Pixel and Tonic release Craft 3 stable version?


texts: Craft CMS FeedMe plugin - Process Instagram JSON Feed

texts:
I'm trying out the new FeedMe plugin v2 beta 1 and am trying to download my recent photos posted on Instagram via the Instagram API. It appears Instagram is appending a cache parameters to the end of image URLs so when I try to download the images to a CraftCMS Assets folder Craft doesn't allow me to as it's not an allowed file extension.

The specific example is:

Instagram Request to get recent posts:
https://api.instagram.com/v1/users/self/media/recent/?access_token=ACCESS-TOKEN

example URL for image returned:
somepic_n.jpg?ig_cache_key=hghhh....

Does anyone have any bright ideas how to handle this so I can download the images at the URLs or some option / feature then could be incorporated into the plugin to remove querystrings from the end of asset urls?

Thanks


texts: Override the output of class S3AssetSourceType->getBucketList from a plugin

texts:
My issue is that for security I don’t have the s3:ListAllMyBuckets permission (as I can only see one bucket), but not list them. Craft needs this to function, so I need to manually force the list of one bucket.

I am trying to override the output of class S3AssetSourceType->getBucketList from a plugin (in Craft 2) to return my own list.

In Craft 3 I’d create my own AssetSource. I guess I’m going to need to amend the core (I know very bad), but I think its the only option I have at this stage (unless anyone has a bright idea). We won’t allow updates via the CMS, so I could write a unit test to check the output is as I have amended it after any core updates. Also, I’d assume that S3AssetSourceType won’t be edited much in Craft 2.

Not an ideal solution, but its the only way I can think of doing it. I have tried every other workaround I can think about (before editing the core code). I looked at mounting the filesystem using s3fs-fuse on Ubuntu, but Docker won’t allow it in our setup.

Anyway, any help would be much appreciated before I start hacking away… thanks.


texts: ElementCriteriaModel combine with 'and' and 'or' filters

texts:
Saying I want to convert the following SQL query into ElementCriteriaModel:

SELECT * FROM users WHERE fieldA = 1 AND (fieldB = 1 or fieldC = 1)

I can't find a way in ElementCriteriaModel to do so.

{% craft.users({
    fieldA: 1,
    fieldB: 1,
    fieldC: 1, // where can we put the 'or' filter?
}) %}

I can do this using DbCommand, but just curious if there's anyway we can do that via ElementCriteriaModel?


texts: Weird issue when upgrading Craft to 2.5 that the settings link in the revised dashboard redirects to the settings page for the Dukt twitter add-on. If I disable the add-on then works just fine. Anybody else experiencing this problem?


texts: Editing expired entries from the front end

texts:
I'm trying to edit an expired entry from the front end.

However, when I hit save, none of the changes persist and a redirect doesn't take place.

Entries that have a live status are fine. Even when I modify the postDate and expiryDate manually, it doesn't update.

I was using the auto-expire plugin and it works fine for new entries. Even disabling it temporarily, the editing of expired entries fails.

Have even stripped out all required fields

<form id="jobForm" method="post" accept-charset="UTF-8">
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="entries/saveEntry">
        <input type="hidden" name="redirect" value="{slug}/{id}">
        <input type="hidden" name="entryId" value="{{ entry.id }}">
        <input type="hidden" name="sectionId" value="3">
        <input type="hidden" name="enabled" value="1">

 Date
                <input type="date" id="postDate" name="postDate" value="{{ entry.postDate }}">

Expiry
            <input type="date" id="expiryDate" name="expiryDate" value="{{ entry.expiryDate }}">

        Title
        <input id="title" type="text" name="title"
                {%- if entry is defined %} value="{{ entry.title }}"{% endif -%}>

        {% if entry is defined %}
            {{ errorList(entry.getErrors('title')) }}
        {% endif %}

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

Has something changed in Craft because it did work on older versions?


texts: Plugin development - How to access actions?

texts:
I have a simple controller in /craft/plugins/craft-dns-notifier/src/conrollers/DnsNotifierController:
namespace kokesjan\dnsnotifier\controllers;
use craft\web\Controller;

class DnsNotifierController_DbController extends Controller
{
    public function buu() {
        echo "tradada";
    }
}

I would like to access the buu() action from src/templates/index.html twig file via Ajax.
I've had no luck for three days, unable to find any hint anywhere. Nothing I have tried worked. It seems like very easy task to me, but I just can't make it work.


texts:
Having successfully installed Craft 3 via composer – all seems fine but on each load of the admin dashboard I get a notice on red bg:
'An unknown error occurred' need I worry about this? couldn't see anything obvious in the logs – all else seems fine – using php 7.0.0 / Mamp Pro and used the line below when setting up:

PATH="/Applications/MAMP/bin/php/php7.0.0/bin:$PATH"

Or is a fresh install required?


texts:
I know Craft appends slugs with -1 if they already exist but I'm working on an app where the addition makes things awkward for us (we have to match the slug to a third-party service). I was under the impression they had to be unique but it seems you can edit an entry and change the slug to be the same as one that already exists.

This could be a good workaround for us, but I want to check whether it's a bug that's likely to get squashed or deliberate behaviour.


texts: $this->renderTemplate() breaks the CP navigation

texts:
I'm locally working on a Craft Plugin with a Page in the Control Panel where I have a form that posts to a controller.
<form action="/actions/import-products/product/create" method="POST" enctype="multipart/form-data">
...
</form>

The controller returns the following at the of it's action
// Render and return the plugin's 'index.twig' template
return $this->renderTemplate('import-products/index.twig', $variables, View::TEMPLATE_MODE_CP);

However, after the renderTemplate, the CP navigation is broken.
It seems that Craft is using the base URL to build the navigation items. Where it should be localhost/admin/dashboard, it's localhost/dashboard? How do I fix this?
Changing the Base URL of the site to localhost/admin breaks everything because the default routes are changed to localhost/admin/admin/dashboard.


texts: Need Swift Mailer to send emails as UTF-8

texts:
I have a Craft 3 site that used Freeform Pro for a contact form. All submissions from this form need to be sent, via email to a third party vendor who parses the information and submits it to a CRM. The format for the emails they receive is very specific: plain-text, utf-8 character set.

When I send a test email from the contact form, it appears to default to ascii if there isn't a utf-8 character in the message. Is there a way to have SwiftMailer to send all emails as UTF-8?


texts: How to wrap a matrix blocktype occurrence loop inside a ul?

texts:
I made a template including a matrix field. I want to wrap all occurrences of a certain block type into a
 element. How can I do this?

My current code:

 {% for block in entry.matrixField.all() %}
        {% switch block.type %}
            {% case 'blockType1' %}

                {{ block.field }}

            {% case 'blockType2' %}

                {{ block.field }}

            {% case 'blockType3' %}

                    {{ block.field }}

        {% endswitch %}
    {% endfor %}

Current output:

blockfield

blockfield

blockfield

But I want my output like this:

blockfield

blockfield

blockfield

That is, I want the ul tag to follow the loop of blockType3.


texts:
After redirecting a website to https environment I had the difficulty that .php/ was added to the url which resulted in double content. I have been able to get past this mistake but now I need to force a /  on in the end if the url’s does not have that yet.

Example

Domainname.com/example/

and

Domainname.com/example

Are now visible in Google. I want only the one with the /

Current .htaccess is:

DirectoryIndex index.php
ErrorDocument 404 /404.html

RewriteEngine On
### START WWW & HTTPS
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### END WWW & HTTPS
RewriteBase /
RewriteRule ^([^.?]+[^.?/])$ $1/ [R=301,L]
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*[^/])/?$ /$1.php [QSA,L]

RewriteRule ^index\.php$ / [R=301,L]

#1)externally redirect "/file.php" to "/file"
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
#2)Internally map "/file" back to "/file.php"
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,L]


texts: Image quality get low in Craft 3 after applying image transform

texts: As of now I am using Craft's image transform to render images according to the size.  If this still appears low quality even Image Transform setting with qulity "Maximum".


texts: Structure Nav: Output "Section" Title on both Landing and Decedents

texts:
Hi all… I have a Structure organized like this:

Arts

Journals

Submissions

Books

Sciences

Journals

Submissions

Books

…etc.

In my template, I want to grab the "Section" (e.g. Arts, Sciences) that I'm in and output it at the top of the page, both on the main page and subpages.

For decedents I can do that using:

    {% set currentSubject = entry.getAncestors().level(1) %}
    {% for entry in currentSubject %}
    {{ entry.title }}
    {% endfor %}

But if I'm on the main page (e.g. Arts, Sciences) itself getAncestors won't help. Is there a smart conditional that will give me the title of the top level page regardless of if I'm on it or a descendent of it?

For some reason, I find myself hoping this can be done without looking at segments, but maybe that's the best route for this kind of thing?


texts: Error when updating 2 to 3: Bad Request Unable to verify your data submission

texts:
Followed all steps on Upgrading from Craft 2 I have my .env, db.php, general.php and index.php in place... can't find any reference of this issue.

This happens after "To complete the update, some changes must be made to your database." and clicking on "Finish Up"


texts:
I have a structure with 1 main Entry and 3 descendants underneath it but I have trouble accessing the data in matrix fields in the entries. I'm trying to do this all on one page:

{% set tabs = entry.descendants %}
     {% for tab in tabs %}
          {{ tab.title }}
     {% endfor %}
{% endfor %}

I can get as far as the tab title, and it displays fine. But I want to access the matrix fields in the descendants. Here are the blocks in my field with the handle 'tab'.

So to summarise, I have a structure:

and then I want to use all those descendant data all one one page but I'm having trouble accessing it.


texts: How to handle mock / placeholder assets in a pattern library?

texts:
I'm currently building a site with a comprehensive pattern library (along the lines of Lonely Planet's), which Craft seems very well suited to. Each pattern is a partial template and I include it in a page like so:

{% include '_partials/card' with {
  title: 'Something',
  description: 'A bit of text',
  image: 'http://lorempixel.com/400/200/'
} %}

The above, with dummy data, allows me to create an example for the pattern library, but I can then easily reuse the above partial with real data by changing the string values to, eg. entry.title, entry.description, etc. This seems to work pretty well for everything apart from for assets: entry.image is not a string, so there's a type difference with my placeholder image.

So far I've got around this problem with a bit of logic that sets image to entry.image.first().getUrl() if entry.image exists. But it feels like this should really happen inside the partial: firstly it's messy and non-DRY to do this every time / everywhere I include it; secondly, the partial itself should really be able to be responsible for specifying the image transform (if there is one).

So it seems to me there are two possible solutions, but I can't quite figure out how to achieve either. The two options are:

Allow the partial to accept either a string or an asset as its image.
Create a mock asset object in my pattern page that will behave more like an asset if I feed it into the partial, so the partial will work unproblematically when I give it an entry.image.

In the former case, I can't figure out a neat way to handle an input that might be a string or an asset field (Twig doesn't seem to have, eg. an is string test). In the latter case I have no idea how you'd go about it or even whether it's possible.

If anyone has any ideas or experience of how you might achieve the above, I'd be really grateful!


texts: Can random be used for ordering with related/assets, in cached code?

texts:
I'm trying to determine if I can update this:

{% cache %}
[
{% set tags = craft.tags.group('color','season','style','venue').limit(null) %}
{% for image in craft.assets.relatedTo(tags).order('elements.dateCreated desc') %}
{% set thumbParams = {
    width: 300,
    height:300,
    mode: 'crop'
} %}
{% set smallParams = {
    width: 768,
    mode: 'fit'
} %}
    {
        "url": "{{ image.url }}",
        "filename": "{{ image.filename }}",
        "imageTitle": "{{ image.imageTitle }}",
        "imageThumb": "{{ image.getUrl(thumbParams) }}",
        "tagsColor": [
{% for tag in image.tagsColor %}
        {
            "slug": "{{ tag | slugify }}",
            "tag":  "{{ tag }}"
        }{% if not (loop.last) %},{% endif %}

{% endfor %}
        ],

        "tagsSeason": [
{% for tag in image.tagsSeason %}
            {
            "slug": "{{ tag | slugify }}",
            "tag":  "{{ tag }}"
            }{% if not (loop.last) %},{% endif %}

{% endfor %}
        ],

        "tagsStyle": [
{% for tag in image.tagsStyle %}
            {
            "slug": "{{ tag | slugify }}",
            "tag":  "{{ tag }}"
            }{% if not (loop.last) %},{% endif %}

{% endfor %}
        ],

        "tagsVenue": [
{% for tag in image.tagsVenue %}
            {
            "slug": "{{ tag | slugify }}",
            "tag":  "{{ tag }}"
            }{% if not (loop.last) %},{% endif %}

{% endfor %}
        ]

    }{% if not loop.last %},
{% endif %}

{% endfor %}
]
{% endcache %}

To randomize the order of images. Is that possible with .order and is that possible within cached template code? (As random would be "new" every instance.)

Note that I have the image crops and tag lookups inside the cached code, as those are intensive. The first answer, to shuffle the images after fetching them within the cached code, won't work, because the for loop on the image set is what needs to be cached.


texts: Why do the plugin resource paths include the localization prefix?

texts:
I'm using Craft in a multilingual setup with the Smart Map plugin. However, the CSS and JavaScript files are not being linked properly when the site isn't in the main language.

For some reason, the paths to the plugin resources contain the language prefix:

/en/cpresources/smartmap/css/smartmap.css

Is this normal behaviour? How can it be fixed?


texts: Error message regarding password in user registration form

texts:
I have a custom registration form in my Craft site based on this info.
https://docs.craftcms.com/v2/templating/user-registration-form.html

And I want to show error message when the password doesn't meet the requirement.

First of all, I made a password requirement like here, and defined a few error messages.
How do I enforce stronger password requirements on my Craft site?

However, no error message appears even if the password is not fine.
Just the form redirects to the same form page, without any message.

So, could you tell me how to set the error message?

Please not that it works fine in the login form to dashboard, like here;
{SiteURL}/admin/

My Craft version is 2.7


texts: Display thumbnail using defineTableAttributes for a custom Element Type

texts:
Hi,

I'm new to Craft and VERY new to plugin development.  I'd like to display a thumbnail image in my table list view and thought it would be possible to accomplish using a new Custom Element Type.  Does anybody know how to achieve this?

I have managed to output custom fields in the table using defineTableAttributes() but I can't output any related Assets - in particular their filenames. Do I need to define a relation in the ElementCriteriaModel using the defineCriteriaAttributes() function?  Can anyone explain how this is done?

Many thanks


texts:
I'm just coming over to Craft from Other CMSes Which Shall Not Be Named. Something I typically do for clients is create custom videos showing how to use the CMS. Now that I'm diving into Craft I'm thinking about creating a general Editor's Guide to show all the nice features of this lovely CMS. (realizing that Craft will be customized to each site's needs)

I've looked around and haven't yet found any similar attempt at showing Craft from an editor's perspective. Do you know of one?


texts: Deleting oldest 404 redirects task stalling

texts:
I have a site which has 100's of pending "Deleting oldest 404 redirects" tasks and they keep stalling so the list isn't clearing.

The client has added lots of custom rules to the .htaccess which I will need to investigate, could this be the cause?

Is there a way I can remove all the pending/stalled tasks manually?


texts: What is a good approach for building an aggregated newsletter?

texts:
I would like to auto create a an aggregated newsletter each month based on Craft content and have Mailchimp deliver it via their API. It doesn't need to be complicated so I was wondering whether a standalone PHP script or custom plugin is the best way to go......or custom API end point and feed content to Mailchimp that way.

I am open to suggestions and previous experiences as what would work effectively.


texts: Looping over categories, product variants, and subsequently applying adjuster(s)?

texts:
Using the Craft 3 and Commerce 2 APIs, how would one go about looping through products in the cart to apply adjusters, looking at the following example;

A category, "Product Packs" is set up where different "packs" for products are defined. In a product, the variants have a field where one can optionally add that category. If we then have a pack, named "summer kit" in that category applied to a couple of variants of a T-Shirt product, to one variant of a Pants product, and a couple of variants of a Sweatshirt product.

How would one go about looping over those products in the cart, check for the associated category, make sure it's the same category, and only applicable to 1 t-shirt, 1 pair of pants and 1 sweatshirt, while still being able to apply it again over another set of the same product variants? So if you had 1 white t-shirt, 1 red t-shirt, 2 pairs of pants and 2 different style sweatshirts, you end up with the pack discount for both those "kits", individually.

Are there any resources with examples of similar functionality, perhaps? Any hint is helpful, I'm a bit at a loss with the PHP/API side of Craft/Commerce.


texts: Use GET parameters to query for array of entry IDs

texts:
On my client side, I have an array of entry IDs that match with entries in Craft

const myIds = ['230', '249', '256']

I am trying to send that array over to an Element API endpoint and use it in the id criteria to only grab entries with the specified IDs.

I am constructing my GET request and add myIds to the request parameters, then send it to the endpoint.

How would I access that array in parameters within element-api.php? I found a response for Craft 2 that looks like it's similar to what I want:
(Passing multiple parameters to the Element API) which uses the getQuery() or getRequiredQuery() functions, but I'm not sure those still exist in Craft 3?


texts: Search for category and title in Element API for Jquery Autocomplete

texts:
I'm working on the search Autocomplete based on this article,
http://craftsnippets.com/articles/search-autocomplete-component-for-craft-cms

Besides the title, I want to search within the category too. How can I do that? The below code doesn't work as expected.

'/search.json' => function() {
    $criteria = [
        'section' => 'products',
        'search' => (Craft::$app->request->getParam('query')) ? 'title:'.'*'.(Craft::$app->request->getParam('query')).'*'.' OR ' . 'categories:'.'*'.(Craft::$app->request->getParam('query')).'*' : '',
        'orderBy' => 'title asc'
    ];

    return [
        'elementType' => Entry::class,
        'criteria' => $criteria,
        'pretty' => true,
        'paginate' => false ,
        'resourceKey' => 'search',
        'transformer' => function(craft\elements\Entry $entry) {
            return [
                'title' => $entry->title . '-' . $entry->categories,
                'url' => $entry->url,
            ];
        },
    ];
},

Here is my function,

$('#search').autocomplete({
    serviceUrl: '/search.json',
    appendTo: $('.auto-complete'),
    onSelect: function (suggestion) {
        window.location.href = suggestion.url;
    },
    transformResult: function(response){
        return {
            suggestions: $.map(JSON.parse(response).data, function(dataItem) {
                return {
                    value: dataItem.title,
                    url: dataItem.url
                };
            })
        };
    }
});

My category is under 'craft.categories.group('prodCats')'


texts:
I have created a new Category on a Craft 3 website but it will not load the template specified. Have other categories all working fine and can't get this one working at all.

Category Config below

I expect this to load my template /pupil-of-the-month/index.html

As per the below image in my templates folder.

But when I click on the category url - http://local.domain.com/pupil-of-the-month/class/p1

I get a not found error -

Template not found: pupil-of-the-month/class

Why is this Category not following the template specified in the admin settings?


texts:
I was setting up localisation and was a bit confused finding certain langugae locales.
Urdu is spoken in Pakistan also known as Bihari but in Craft or Yii i18n data there is only en_pk. Is this a holder for incoming translations?


texts: How can I translate static text in my templates that have accents?

texts:
Using this help page https://craftcms.com/support/static-translations I've created a fr.php file in a translations folder - and it's working OK. Except when I have "Telephone" => "Téléphone" in the array - the two é get output as black diamonds with a question mark in.

How should I be adding Téléphone in the array so that it outputs correctly?

Many thanks
Lee


texts:
When I attempt to run any ./craft it throws an error, for example:

$ ./craft resave/entries
Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: craft\console\Request::getSegment()'

in /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/base/Component.php:300

Stack trace:
#0 /var/www/examplewebsite.co.uk/plugins/core/src/Core.php(97): yii\base\Component->__call('getSegment', Array)
#1 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/base/BaseObject.php(109): cursor\core\Core->init()
#2 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/base/Module.php(158): yii\base\BaseObject->__construct(Array)
#3 /var/www/examplewebsite.co.uk/vendor/craftcms/cms/src/base/Plugin.php(130): yii\base\Module->__construct('core', Object(craft\console\Application), Array)
#4 [internal function]: craft\base\Plugin->__construct('core', Object(craft\console\Application), Array)
#5 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/di/Container.php(400): ReflectionClass->newInstanceArgs(Array)
#6 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/di/Container.php(159): yii\di\Container->build('cursor\\core\\Cor...', Array, Array)
#7 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/BaseYii.php(351): yii\di\Container->get('cursor\\core\\Cor...', Array, Array)
#8 /var/www/examplewebsite.co.uk/vendor/craftcms/cms/src/services/Plugins.php(897): yii\BaseYii::createObject(Array, Array)
#9 /var/www/examplewebsite.co.uk/vendor/craftcms/cms/src/services/Plugins.php(230): craft\services\Plugins->createPlugin('core', Array)
#10 /var/www/examplewebsite.co.uk/vendor/craftcms/cms/src/base/ApplicationTrait.php(1375): craft\services\Plugins->loadPlugins()
#11 /var/www/examplewebsite.co.uk/vendor/craftcms/cms/src/console/Application.php(65): craft\console\Application->_postInit()
#12 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/base/BaseObject.php(109): craft\console\Application->init()
#13 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/base/Application.php(206): yii\base\BaseObject->__construct(Array)
#14 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/console/Application.php(89): yii\base\Application->__construct(Array)
#15 /var/www/examplewebsite.co.uk/vendor/craftcms/cms/src/console/Application.php(54): yii\console\Application->__construct(Array)
#16 [internal function]: craft\console\Application->__construct(Array)
#17 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/di/Container.php(400): ReflectionClass->newInstanceArgs(Array)
#18 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/di/Container.php(159): yii\di\Container->build('craft\\console\\A...', Array, Array)
#19 /var/www/examplewebsite.co.uk/vendor/yiisoft/yii2/BaseYii.php(351): yii\di\Container->get('craft\\console\\A...', Array, Array)
#20 /var/www/examplewebsite.co.uk/vendor/craftcms/cms/bootstrap/bootstrap.php(244): yii\BaseYii::createObject(Array)
#21 /var/www/examplewebsite.co.uk/vendor/craftcms/cms/bootstrap/console.php(34): require('/var/www/examplewebsite.c...')
#22 /var/www/examplewebsite.co.uk/craft(21): require('/var/www/examplewebsite.c...')
#23 {main}

Any suggestions on what I need to do? I'm on the latest version of CraftCMS and also am using PHP7.2.

Thank you!


texts: Restrict each user to a single Assets folder

texts:
I need every control panel user to have a single assets folder that is private to them. Is there any way of achieving this in Craft?

I've tried using the "Restrict uploads to a single folder?" option and then used the {author.username} for the subfolder. This works as expected for uploading inside an entry form (although the entry must be saved before existing files can be added to the field, which isn't a great experience), but in the Assets area of the control panel, where users would need to go to be able to delete/manage their assets, the user then has access to ever other user's subfolder.

If anyone has any ideas for how I can achieve what I need, I'd greatly appreciate it.

UPDATE:

I found a plugin called Asset Subfolder Access (By P&T) which allows me to achieve what I want. Although, it's based on User Groups so I'll have to make a group for every user, which isn't ideal. I've also found that the "restrict to single folder" option on Asset fields doesn't allow the user to access subfolders of that location, which isn't great.


texts:
There's a section called locations and another called vacancies. In vacancies the admin can assign a location entry to a vacancy.

On the careers overview page we want to display selected vacancies block.vacancySelected.

In the template we loop through all locations and would like to display the number of vacancies per location.

{% set lparas = {
    section: 'locations'
    } %}
{% set locations = craft.entries(lparas) %}

{% if locations | length %}
   {% for location in locations %}
      {% set cEntries = block.vacancySelected.relatedTo(location) %}
      {% if cEntries| length %}
         {{ location.locationName }} ({{ cEntries | length }})
      {% endif %}
   {% endfor %}
{% endif %}

But for some reason it shows all locations and the total number of vacancies per locations. It seems to ignore that we only want to show the locations of the selected vacancies.


texts:
Good Evening,
This is probably something really simple, but I need to output the position of the entries in a query within the loop
{% set relatedEntries = craft.entries().section('memories').limit(10).orderby('RAND()') %}

{% for asset in relatedEntries %}

 **LOOP NUMBER HERE**  {{ asset.title }}

{% endfor %}

I want it to add the number between 1 and 10 depending on its position
Any help would be appreciated


texts: Checking if a plugin is installed or enabled are ignored by Twig Extensions

texts:
A while ago I asked how to check if a plugin is enabled/installed. I've since used a couple methods to do my checks:

{% set plugin = craft.plugins.getPlugin('myPlugin', false) %}

{{ plugin.isEnabled() ? 'plugin enabled' : 'plugin disabled'}}

{{ plugin.isInstalled() ? 'plugin installed' : 'plugin not installed'}}

{{ craft.myPlugin is defined ? 'plugin true' : 'plugin false' }}

Now I recall this working with Twig Extension functions and filters too. It wasn't pretty, but it worked.

I may wrong, but I think one of the Craft CMS Updates have broken this. Because as-of-late, when I do something like this:

{{ craft.myPlugin is defined ? myFunction() }}

or

{{ craft.myPlugin is defined ? someVariable|myFilter() }}

(myFunction being a twig function, and myFilter being a twig filter)... I get an error:

  Unknown "myFunction" function

Another new change/bug I've noticed (related to this); if a database can't be connected to and devMode is off, I will get this instead of the 503 error template.

  Unknown "myFunction" function in "_layouts/main" at line 85.

It's as if the Twig functions/filters get priority over anything else. Am I making this up, and this has always been the case? Or has something changed?


texts: How to browse uploaded assets on the front end?

texts:
I have a frontend entry form which included a file field to upload files to the entry. All works fine. I even have a delete function to remove individual uploaded files from the entry.

The problem is if a user wants to attach a file they have already uploaded. Uploading the file results in the same file uploaded but with a different filename (a timestamp added to the end).

This is going to result in unused files being left on the server and a nightmare version control going on - people left wondering what version is correct, which is being used, is it safe to delete the old ones etc.

So ideally what is needed is the user can browse the assets uploaded on the front end and ideally be able to upload within that.

Is there a facility to do this?

Thanks


texts:
I'm trying to setup aliases following the instructions in the docs, but I can't get them to work (for example they don't appear when setting paths for Assets).
I copied and pasted the code exactly as the example in the docs, and the env variable ROOT_URL shows up in the CP, but the alias @rootUrl does not. Is there another step? I tried clearing caches and logging out/in, but that didn't help.
In the config/general.php file I pasted the code last, right below Dev environment settings. Here is that last portion of the config:
    // Dev environment settings
        'dev' => [
            // existing settings ...
            'backupCommand' => getenv('BACKUP_COMMAND'),
            'restoreCommand' => getenv('RESTORE_COMMAND'),
        ],

    // -- config/general.php Code example from docs --
        'aliases' => [
            '@rootUrl' => getenv('ROOT_URL'),
        ],
];

Also, the 3.6 upgrade documentation states (emphasis mine):

The siteName and siteUrl config settings have been deprecated. We strongly recommend you set your sites’ names and URLs using environment variables instead.

So, does this mean I shouldn't even be bothering with aliases? Should everything be an environment variable only?


texts: Dynamic Asset Sub Folder Paths based on section and. if/else or turnery operators

texts:
How can I create dynamic paths for asset uploads?
Basically I want my structure to be like so;

company-name-slug
  company
    logo-1.jpg
    image-2.jpg
  products
    product-image-1.jpg
  services
    service-image-1.jpeg
    service-image-2.jpeg

I have a field called gallery for the above assets.

Then I have sections for company, products and services.
Each section uses the gallery field. Products and Services uses a related content field for the company (called company).

I want to use the gallery field across all sections, but then set the dynamic paths per service/product and company inline with the above structure.

Here is what I have tried but it just errors out. I have tried various combinations and some work some don't, but I cannot get to desired structure.

{% section == 'Company' ? slug : company.one|kebab %}/{section|kebab}

How can I achieve this or is there a way I can inject some better twig logic into the subfolder field?


texts: Craft 3 Plugin: Saved image asset has no width / height

texts:
In my Craft 3 Plugin I am saving an image (YouTube poster) to an asset volume like this:

$asset = new Asset();
$asset->title = $url;
$asset->tempFilePath = $tmpPath; // temp path for image in /storage/runtime/temp/
$asset->volumeId = $volumeId; // ID of my Asset Volume
$asset->filename = $filename; // filename like youtube_<youTubeKey>.jpg
$asset->newFolderId = $folder->id; // root folder id of the volume
$asset->avoidFilenameConflicts = true;
$asset->setScenario(Asset::SCENARIO_CREATE);
clearstatcache();
list ($w, $h) = Image::imageSize($tmpPath);
$asset->setWidth($w);
$asset->setHeight($h);
$result = Craft::$app->getElements()->saveElement($asset);

The image saved does not have width or height (so it's there while saving), so if I later output its width like this in TWIG: {{ dump(img.width) }} it will be NULL.

Any hints what I need to call so that craft persists the image width / height?