texts:
I have two sections: 'reviews' and 'games'.
Games has an field called 'GamesReviews' which is type entries and points to 'reviews'.
An example of a games entry is located at:
http://www.colorcomputergames.com/games/donkey-king

Towards the bottom, I link to the related reviews for this entry.
That sends me to:
http://www.colorcomputergames.com/reviews/1983-06-01/donkey-king

At the bottom of the review, I want to link back to the related entry of that review.

I am able to display the name of the game 'Donkey King', but the URL is not pointing to:
http://www.colorcomputergames.com/games/donkey-king

But instead:
http://www.colorcomputergames.com/reviews/1983-06-01/donkey-king

The code I am usinng in the template (reviews/_entry.html) is:

{{ entry.title }}

    {% if entry.ReviewsAuthor|length %}
Reviewer: {{ entry.ReviewsAuthor }}
{% endif %}
    {% if entry.ReviewsMedia|length %}
Media: {% for category in entry.ReviewsMedia %}{{ category.title }}{% endfor %}
{% endif %}
    {% if entry.ReviewsDate|length %}
Date: {{ entry.ReviewsDate.format('F Y') }}
{% endif %}
    {% if entry.ReviewsRelatedLink|length %}
Related Link: {{ entry.ReviewsRelatedLink }}
{% endif %}

{{ entry.body }}

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

Info:

{{ entry.title }}


texts:
I am currently developing my first website using Craft 3 and I'm loving it overall. I seem to have a small issue that I can't quite figure out. When I go to the updates section in the admin panel, I am proposed multiple updates to Craft and 2 of my plugins (see screenshot). However, I can't figure out how to actually do these updates! According to this page in the docs, a button should appear at the top of the page.

I've also tried via composer : composer update craftcms/craft, but it says 'Package "craftcms/craft" listed for update is not installed'.

And I've tried : composer update craftcms/cms and that gives 'Nothing to install or update'. Same thing if I try to update plugins such as redactor that way.

I had started out on RC14 and I was able to update to RC15 properly via the button, but since then, the button no longer shows. Since I am new to Craft, I am not sure which log would contain pertinent information for the problem. I will be glad to share some logs if necessary. If it changes anything, I purchased a Pro license before the license changes on Apr 04.

Sorry if this is a noob question, any help is appreciated!


texts: "uploaded" files don't actually get uploaded in folder

texts:
I created an asset source and the paths are 100% correct. When I upload the file it doesn't seem to get uploaded at all. I get no error when I upload the file and craft behaves like the file is uploaded. When I do
{{ entry.pdf.first.url }}
I get an url with the exact location where the file would be. When I got to the folder, there is no file visible. When I go to the Url no file can be found.
I have no idea what I can do anymore. Any advice?
(I am using Craft 2)


texts: Trying to template a post's image on an index page with a default image if it does not exist

texts:
This is for an index page (again).  I want to list the 10 most recent articles.  There is a field postImage.  It is not required.  If it exists, I want to use postImage.  If not, I want to use a default image.

The relevant code is under the img tag.

I get the following error:  Impossible to invoke a method ("getUrl") on a null variable..  I can verify that 7 of the first 10 entries do have a postImage.

  {% for item in craft.entries.section('posts').limit(10) %}
                              {% set pic = item.postImage.one().getUrl() %}
                              {% if loop.index is divisible by(2) %}

Enterprise

                                        {{ item.title }}

                                       {{ item.introParagraph }}
                                         Read More

                                        by

                                            x
                                        , 2 days ago

                        {% else %}

There are 2 if / else statements.   Only the 1 associated with the img tag is relevant.

Thanks.


texts:
I now know the answer to this but I’m posting it here as a note to myself and in case it helps people.
Let's say you are looping through some entries and storing values in a hash…
{% set myHash = {} %}

{% for entry in entries %}
    {% set value  = entry.intro %}
    {% set myHash = myHash|merge({
        (entry.id) : { intro : value }
    }) %}
{% endfor %}

The entry.id is a variable so it needs to be wrapped in brackets as a dynamic key.
But when you {{ dump(myHash) }} it turns out the numeric keys have just become index numbers – [0] in the truncated example below…
array(10) {
  [0]=>
  array(1) {
    ["intro"]=>
    string(13) "My intro text"
…

But there is a straightforward answer…


texts: Add entry ids to a session cookie/variable array on button click?

texts:
I'm looking for a way to add entry ID's to an array in either a session cookie or a session variable.

I've installed the LJ Cookies plugin (https://github.com/lewisjenkins/craft-lj-cookies) in the hope that it is possible with this, however I am stuck.

To give an idea of the user process for this:

I have channel entries that are courses
When a user goes to a course there will be a "Save this course" button
When the user clicks the button it will add the ID of the course to a session variable/session cookie array
These saved courses will then be available to the user if they click on a "View saved courses" button during their session
Once their session is over, the cookie can be deleted

Any help on this will be very much appreciated.


texts: Installing other PHP app in sub directory

texts:
My question is the opposite of this question: Installing Craft in sub directory

I have a Craft website and I need to put a Laravel application in a sub directory, it almost works. I have made the directory and created a symbolic link to the public folder for the Laravel application.

This works with the default route in Laravel but as soon as I try any nested routes I just get a Craft 404.

Is is possible to get Craft to completely ignore a folder or something, or do I need to figure out an alternative solution.

Thank you!


texts: Extracting an attribute from top level node of a Feedme XML feed using template

texts:
I'm trying to extract an attribute from a top level XML node but having some difficulty.

Given some XML:

<?xml version="1.0" encoding="UTF-8"?>
<slots>
  <slot start="Monday" finish="Tuesday">
    <title id="1234">John</title>
  </slot>
  <slot start="Thursday" finish="Friday">
    <title id="5678">Fred</title>
  </slot>
</slots>

and some Twig:

{% set params = {
        url: 'http://above.xml',
        type: 'xml',
} %}
{% set feed = craft.feedme.feed(params) %}

I can extract values and attributes from the inner nodes

{{feed.slots.slot.0.title.attributes.id}}
{{feed.slots.slot.0.title}}

which yields 1234 John as I would expect. But now, how do I get the attributes from the slot node e.g. I want the 'Monday'. I've tried something like

{{feed.slots.slot.0.attributes.start}}

but that just throws an error.

EDIT: If I change the XML (remove the inner title nodes) to

<?xml version="1.0" encoding="UTF-8"?>
<slots>
  <slot start="Monday" finish="Tuesday">
  </slot>
  <slot start="Thursday" finish="Friday">
  </slot>
</slots>

then

{{feed.slots.slot.0.attributes.start}}

works. So maybe the question now is how do I extract attributes from a node that has sub-nodes?


texts:
I'm using this Import plugin https://github.com/boboldehampsink/import.
 It has a hook called modifyImportRow, which would let me process single .csv rows with my custom logic.

In this case I have to process a Matrix field.

I'm not sure where and how to call hooks in general. In the plugin? In another plugin like businessLogic? Is there a specific file?


texts: How can i get API-Response that includes localized data using json_expand?

texts:
My index.html endpoint in the templates folder looks like this:

    {% header "Content-Type: application/json" %}
    {% set basics = craft.entries.section('basics').find('') %}
    {{ basics | json_expand | raw  }}

I did enable the fields and put some localized strings inside,
still json returns this:

[
 {
"id": "261",
"enabled": "1",
"archived": "0",
"locale": "de",
"localeEnabled": "1",
"slug": "wimpern-richtig-tuschen",
"uri": null,
"dateCreated": {
  "date": "2015-11-26 12:08:01",
  "timezone_type": 3,
  "timezone": "UTC"
},
"dateUpdated": {
  "date": "2015-12-07 15:03:51",
  "timezone_type": 3,
  "timezone": "UTC"
},
"root": null,
"lft": null,
"rgt": null,
"level": null,
"sectionId": "7",
"typeId": "9",
"authorId": "153",
"postDate": {
  "date": "2015-11-26 12:08:00",
  "timezone_type": 3,
  "timezone": "UTC"
},
"expiryDate": null,
"parentId": null,
"revisionNotes": null,
"title": "Wimpern richtig tuschen",
"basics_text": "Wimpern richtig tuschen", (etc...)

is there a way to make an endpoint just for the english version, like basics_en ? Is there even any way to get the localized data using this method? The CMS is for a mobile-app, so i just need the raw data from the endpoint.


texts: Import Plugin on localhost Craft 2 crashes

texts:
I'm using the import plugin by Bob Oldehampsink on a localhost Craft2 site, but, although it appears to have installed successfully, when I attempt to upload the .csv file and click on 'next,' I'm met with a blank screen.
I've checked the format of the .csv and have made various changes, but I still get the blank screen (I only ever see the first screen in the Import plugin).
Thanks for any help or suggestions.


texts: How to remove Link To Category from Redactor

texts:
Is there a way to remove the 2 Craft specific menu items from Redactor's Link menu without losing access to the "Insert link" menu item?

Removing the Link button in the redactor configs is too draconian as I don't want to lose access to the basic Insert and Unlink functions previously in that menu.

I've dug into the src, and the only hook/event I can find related to the redactor settings allows addition of menu items to the Links menu, but not removal of the Craft added "Link to an Entry" and "Link to a Category".


texts:
any idea why this: %20AND%20foo%3A%22(.+?)%22 won't match this: %20AND%20foo%3A%22some random string of characters%22 in the Twig |replace filter?

If i do this:

{% set foo = '%20AND%20foo%3A%22some random string of characters%22' %}
{% set bar = '%20AND%20foo%3A%22(.+?)%22' %}
{{ foo |replace(bar, 'replaced') }}
{# OR THIS #}
{{ foo |replace((bar), 'replaced') }}

The result is foo. Nothing gets replaced. I'd expect the result to be the string "replaced". What am I doing wrong?


texts:
Here we go:

{% set state = craft.categories.group('locations').level(1).title(entry.title).one() %}
{% set solution = craft.categories.group('institutionSolutions').title(entry.parent.title).one() %}
{% set entries = craft.entries.section('institutions').relatedTo('and', state, solution).limit(4) %}

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

The following code does work as expected in Craft 2. According to the docs in Craft 3 we have to use the array brackets. So this

{% set entries = craft.entries.section('institutions').relatedTo('and', state, solution).limit(4) %}

will become to this

{% set entries = craft.entries.section('institutions').relatedTo(['and', state, solution).limit(4) %}

as a result I see the following message:

array_merge(): Argument #2 is not an array

What am I doing wrong? :(


texts: How do I order by _entry type_ when looping through entries in a template?

texts:
I currently have multiple sections like so:

{% for craft.entries.section('mySection').type('oneType')... %}
   ... {% endfor %}
{% for craft.entries.section('mySection').type('anotherType')... %}
   ... {% endfor %}

But I would rather have a single loop like this:

{% for craft.entries.section('mySection').order('type, title')... %}

However, the type referred to in order() will in the DB query refer to craft_elements.type which in this case always will be Entry.

Is it possible to order by entry type?


texts: Add optional segment to Craft Commerce product Url

texts:
I currently have a Craft Commerce site where the product url is setup like this:

{productCategory.level(1).first().slug}/{productCategory.level(2).first().slug}/{productCategory.level(3).first().slug}/{slug}

So this gives an example url of category1/category2/category3/my-product

This all works fine. What I'd like to do is add an optional segment onto the end of this url, so for example:

category1/category2/category3/my-product/optional-thing.

I'd like the current urls to continue working, but if you add the extra optional-thing segment to the url you also get the same product.

Ultimately this is so that I can preselect a variant in a carousel on the product detail page.

I've tried doing this with routes, but so far I've been unsuccessful. Is this the right approach or is there a better, more Commerce specific way?


texts: Getting entries from different structures and level

texts: I need to loop through the 6 latest entries from 3 different structures. The problem is, the entries are located on different levels. One of the structures has entries on level 3, and the other two has entries on level 1.


texts:
I'm trying to build a plugin that has relations with Craft entries.
The plugin db table has field called entryId that defines a foreign key to the {{%elements}} table. Then my Record class extends ActiveRecord and set the relationship like this:
public function getEntry()
{
    return $this->hasOne(Element::class, [
        'id' => 'entryId'
    ]);
}

In the service class I can get the related record doing so:
$record = MyRecord::findOne([
       'entryId' => $entryId
]);
var_dump($record->entry);die;

The relationship seems working fine... anyway I think I'm relating to the wrong model. I mean... I would like to get the entry with title, slug and other properties, instead I get and object of data from the elements db table.
    object(craft\records\Element)#227 (10) {
    ["_attributes":"yii\db\BaseActiveRecord":private]=>
  array(11) {
    ["id"]=>
    int(48)
    ["draftId"]=>
    NULL
    ["revisionId"]=>
    NULL
    ["fieldLayoutId"]=>
    int(1)
    ["type"]=>
    string(20) "craft\elements\Entry"
    ["enabled"]=>
    int(1)
    ["archived"]=>
    int(0)
    ["dateCreated"]=>
    string(19) "2020-07-30 11:29:10"
    ["dateUpdated"]=>
    string(19) "2020-08-04 19:38:57"
    ["dateDeleted"]=>
    NULL
    ["uid"]=>
    string(36) "85c2f79c-5ee7-434d-8c29-d3d807a64b6c"
  }

Can anyone point me where I'm wrong? Thanks for help!


texts: Is it possible to have different plugin settings per locale?

texts:
I'm looking into the possibility of using Foxycart for a multilingual, multi currency site. Currently it is not possible to have multiple currencies in Foxycart so it would require having separate Foxycart accounts for each currency. I would therefore need to store the cart url and api keys for each Foxycart account within the foxycart plugin.

What would be the best way of going about this? Is it possible to store different plugin setting based on locale?

The other idea I had was to store the api key etc in the config file but not sure if that is best practice or not.


texts: Freeform - get option label & value on submissions page

texts:
On the form I'm building, I've got a question with radio buttons. And the answers have custom values. e.g.

Q: What is your favorite color?

red (value: 10)
blue (value: 20)
yellow (value: 30)

On my submissions page, I have the following code

{% for field in submission.fieldMetadata %}

        {{ field.label }}/b>:

        {% set fieldValue = attribute(submission, field.handle).value %}
        {% if fieldValue is iterable %}

            {% for value in FieldValue %}

{{ value }}

            {% endfor %}

        {% else %}
        {{ fieldValue }}
        {% endif %}

{% endfor %}

And this returns:

What is your favorite color: 10

I'm using the values to do some funny math - so it's necessary (but unimportant to the issue at hand).

How to do I get the value "red" to show, instead of the 10?

attribute(submission, field.handle).value - shows the selected option's value (10)
attribute(submission, field.handle).label - shows the question (What is your favorite Color?)
attribute(submission, field.handle).handle - shows the question handle (whatIsYourFavoriteColor)

There should be another function to get the option's value, but I can't find what it is.


texts:
Instead of writing a lot of logic in twig in my template, I tried to create a service and get the fields related to the requested entry in a module. I then want to create a new twig variable to output the whole block in my template. After a lot try and error and reading the docs I'm still not able to achieve this. Maybe someone can give me a hint where to start.

So the question is: How can I get the fields related to the requested entry in a module?


texts: How to fire a custom event from another plugin?

texts:
I have some questions about events. I want to fire a custom event from another plugin. The event handler is in MyHelpers_PostService.php (plugin A).

public function onSavePost(Event $event)
{
    $this->raiseEvent('onSavePost', $event);
}

My init() method (plugin B):

public function init()
{
    craft()->on('myHelpers_Post.savePost', function(Event $event)
    {
       // delete a cache key
       craft()->pluginB->clearCache('forum-home-desktop');
    });
}

This is my first time working on Craft events, so please bear with me. I tested this by saving a new Helpers Post on the front-end and nothing happens.

The clearCache() method is just using Craft's deleteCachesByKey();

Is myHelpers_Post.savePost correct?
What else do I need to make this work?
How do I test this properly? Can I use Craft::dd() inside the handler?


texts: Why do image Transformations never finish rendering regardless if I use GD2 or ImageMagick?

texts:
I'm running Craft 2 with PHP 5.6.40 on a Windows 2019 Server under IIS (x64, non-thread-safe, FastCGI).
PHP -m doesn't show any issues with my extensions, regardless if I use GD2 or ImageMagick.
But if I have either extension enabled, then I get this processing / loading spinner where the images should be rendered if Craft was applying my Transformations:

I realized my php.ini had the defaults for max_execution_time = 30 and memory_limit = 128M. I bumped them up to Craft's minimum recommendations of: max_execution_time = 120 and memory_limit = 256M. When that didn't work, I even tried max_execution_time = 0 and memory_limit = 1G. Still no luck, regardless if I used GD2 or ImageMagick.
If I disable both extensions, the processing spinner goes away and my images load untransformed. They are really big images, about 7 MB file sizes that are about 8,000 pixels width by 4,000 pixels height.
I also noticed that if I have GD2 or ImageMagick enabled, and the spinner is loading, the request transformation Task hangs (infinitely?) in the database's "craft_tasks" table.
Is there some other setting I could be missing in my php.ini configuration file?
UPDATE: I receive the following error in my Craft logs (no errors in my web server though), regardless if I have GD2 / ImageMagick enabled or not. So not sure if it's relevant? (It's the only error in the logs.)
2020/10/30 12:53:58 [error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in D:\Websites\MyWebsite.us\craft\app\controllers\TemplatesController.php:72
Stack trace:
#0 [internal function]: Craft\TemplatesController->actionRender('FPURL.xml', Array)
#1 D:\Websites\MyWebsite.us\craft\app\framework\web\actions\CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#2 D:\Websites\MyWebsite.us\craft\app\framework\web\actions\CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Object(ReflectionMethod), Array)
#3 D:\Websites\MyWebsite.us\craft\app\framework\web\CController.php(308): CInlineAction->runWithParams(Array)
#4 D:\Websites\MyWebsite.us\craft\app\framework\web\CController.php(286): CController->runAction(Object(CInlineAction))
#5 D:\Websites\MyWebsite.us\craft\app\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#6 D:\Websites\MyWebsite.us\craft\app\framework\web\CWebApplication.php(282): CController->run('render')
#7 D:\Websites\MyWebsite.us\craft\app\framework\web\CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#8 D:\Websites\MyWebsite.us\craft\app\etc\web\WebApp.php(290): CWebApplication->processRequest()
#9 D:\Websites\MyWebsite.us\craft\app\framework\base\CApplication.php(185): Craft\WebApp->processRequest()
#10 D:\Websites\MyWebsite.us\craft\app\index.php(62): CApplication->run()
#11 D:\Websites\MyWebsite.us\public_html\index.php(46): require_once('D:\\Websites\\MyW...')
#12 {main}
REQUEST_URI=/FPURL.xml


texts: How can I restrict assets on a per-file basis?

texts:
I found this post about restricting an entire asset source and placing it below the root level: Is it possible to have secure (private) assets?

What I'd really like to do is be able to set the members-only restriction on a per-file basis, perhaps with a lightswitch field.

The imagined flow would be:

user clicks a file link (anywhere, or even has a direct URL to the file)
.htaccess sends all .pdf, .doc, etc requests to a download checker page
download checker page sees if the requested file has the lightswitch checked
if no, download the file
if yes,

if logged in, download the file
if not logged in, show the registration / login page

upon login or registration, start the file download

I'm still relatively new to Craft and have the feeling there may be specific twig/craft abilities that make this — or something very similar — simple. I don't necessarily need the code handed to me, just some ideas about what tools are available to help with this process.


texts:
I was looking for a way to clear the “template caches” and “compiled templates” from the CLI, as I want to automatically do this after every auto-deploy of the site I've created.

For this I was looking into the craft binary and its cache/list command. However, when running ./craft cache/list it only returns me cache (yii\caching\FileCache).

This felt kind of strange to me, as I was expecting a list similar to the one to be seen in the admin at the URL /admin/utilities/clear-caches:

So hereby I'm wondering if it's possible to clear any of these caches show above from the CLI. Or is the cache/clear command for something else that I'm not aware of?


texts: First and Last day of Week + Month in Twig

texts:
If i provide the week#, how might i go about getting the first day (and month) and the last day (and month) of that particular week?

This week for instance would be April 26 and May 2

I know in PHP i can do the first and last day of the week like so:

$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));

But i'm not sure how to translate that to twig and of course also include the month.


texts: How to move repeating code into an include template

texts:
I'm new to Craft and have created some SEO fields similar to this, and the template code appears in all templates as shown below. I don't want to be repeating all that code in every template though, so I thought I'd be better of putting it in an include template (assuming that's how best to handle this in Craft).

But I'm getting an error when I try to do this, so can anyone show me the correct way of doing this please?

Here's my starting code, where I'm repeating the SEO code in every template (see the start and end comments):

{% extends "_layout" %}

{# START OF SEO CODE #}
{% if entry.metaTitle != '' %}
  {% set title = entry.metaTitle %}
{% else %}
  {% set title = entry.title %}
{% endif %}

{% if entry.metaDescription != '' %}
  {% set description = entry.metaDescription %}
{% endif %}

{% if entry.metaKeywords != '' %}
  {% set keywords = entry.metaKeywords %}
{% endif %}
{# END OF SEO CODE #}

{% block content %}

{{ entry.title }}

    {{ entry.body }}

{% endblock %}

And for completeness, I have the following in my _layout template:

{% set metaTitle = globalMetadata.metaTitle %}
{% set metaDescription = globalMetadata.metaDescription %}
{% set metaKeywords = globalMetadata.metaKeywords %}

<title>{% if title is defined %}{{ title }}{% else %}{{ globalMetadata.metaTitle }}{% endif %} | {{ siteName }}</title>
<meta name="description" content="{% if description is defined %}{{ description }}{% else %}{{ globalMetadata.metaDescription }}{% endif %}" />
<meta name="keywords" content="{% if keywords is defined %}{{ keywords }}{% else %}{{ globalMetadata.metaKeywords }}{% endif %}" />

So I've tried moving the SEO code out of the entry template, and into the following include template: _includes/seo_meta:

{# START OF SEO CODE #}
{% if entry.metaTitle != '' %}
  {% set title = entry.metaTitle %}
{% else %}
  {% set title = entry.title %}
{% endif %}

{% if entry.metaDescription != '' %}
  {% set description = entry.metaDescription %}
{% endif %}

{% if entry.metaKeywords != '' %}
  {% set keywords = entry.metaKeywords %}
{% endif %}
{# END OF SEO CODE #}

And am trying to call it from my entry template like this:

{% include "_includes/seo_meta" %}

But I'm getting the following error message, and the error is highlighting my include line:

A template that extends another one cannot have a body.

Thanks in advance for any help, Stephen.


texts: Intercepting Sprout Forms "onSaveEntry" Event In Craft 3 Plugin

texts:
I've built lots of Craft 2 plugins that catch Sprout Forms submissions and integrate with external services (CRM's etc). It was easy, you'd make a plugin and catch the event going:

craft()->on('sproutForms.onSaveEntry', function(SproutForms_OnSaveEntryEvent $event) {
    // Hand submission off to your service to do some rad stuff.
});

But in Craft 3, that events functionality appears to be more complicated. All the Events & Hooks area in the Sprout Documentation just show "Example needed." in all the places where code samples would usually be. The Craft 3 plugin docs on events show a new system for registering and intercepting events - but my coffee deficient mind is struggling to figure out how to map that to Craft3/Sprout Forms 3.0.0-beta.17.

Has anyone built a Craft 3 plugin that works with Sprout Forms Beta yet? I'm even struggling to find examples of any event integration in plugins at the moment.

Halp!!!


texts: How can I repopulate my dropdown on a front-end form?

texts:
I am allowing guest registrations - everything is working fine. I am hung up on getting my drop down menu to repopulate/hold its value if there are any errors while submitting.

I have a states field in the CP which is a dropdown.

Within my twig template I have this:

{#
 # Get all of the states.
 #
 #}
 {% set states = craft.fields.getFieldByHandle('states').getFieldType.options %}
 {% if states|length %}

         State
         <select id="state" name="fields[address][state]" class="form-control">
             <option value="">Select</option>
             {% for option in states %}
                 <option val="{{ option.value }}"
                     {%- if account is defined and option.value in account.address.state %} selected {% endif -%}>
                     {{ option.label }}
                 </option>
             {% endfor %}
         </select>

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

I am using SmartMap to capture my address hence the name of fields[address][state].

Just doing this:

{%- if account is defined %} selected {% endif -%}

Gets the last option selected, so I know account is getting defined, its something in my and part.

All of my data is getting captured correctly, I just can't see past the obvious here I guess.

SOLUTION

Thanks to @carlcs I found that the value of my state field was getting saved as the label. I'm not sure if thats a function of SmartMap, or something else I might have done.

Here is what I ended up with:

...
<option value="">Select</option>
{% for option in states %}
    <option val="{{ option.value }}"
        {%- if account is defined and option.label in account.address.state %} selected {% endif -%}>
        {{ option.label }}
    </option>
{% endfor %}

Alternatively, here is how I was able to repopulate a "normal" drop-down (not address/SmartMap):

...
<option value="">Select</option>
{% for option in myField %}
    <option val="{{ option.value }}"
    {%- if account is defined and option.label in account.myField.label %} selected {% endif -%}>
       {{ option.label }}
    </option>
{% endfor %}

I think it's also worth noting that by setting myField as a required field in the CP, I needed to hard-code the <option value="">Select</option> in the template rather than putting it as a field value. When I had it as a field value, I (think) Craft was accepting that as a selected value and I was not getting the error message.


texts: Only display entries based on a field conditional

texts:
Hey I am trying to get 4 entries, but only want 4 that have a body length > 100.

How would I accomplish this?

{% for entry in craft.entries.section('artists').order('RAND()').limit(4) %}
  // only display 4 entries with entry.body|length > 100
{% endfor %}

Thanks!


texts: Cannot install custom Twig extension plugin

texts:
So I started building this plugin to add a twig extension to escape but leave &nbsp; intact. For some reason when I try install it or use it without the force argument on the import command in the plugin file set to true it does not work. If i set it to true, though, it installs fine and works fine.

My plugin Directory Structure:

craft
 - plugins
   - nbsp
     NbspPlugin.php
     - twigextensions
       NbspTwigExtension.php

Here is my NbspPlugin.php file:

<?php
namespace craft;

class NbspPlugin extends BasePlugin {

    function getName()
    {
        return Craft::t('&nbsp Twig Filter');
    }

    function getVersion()
    {
        return '1.0';
    }

    function getDeveloper()
    {
        return 'Rick';
    }

    function getDeveloperUrl()
    {
        return '';
    }

    public function addTwigExtension()
    {
        Craft::import('plugins.nbsp.twigextensions.NbspTwigExtension');

        return new NbspTwigExtension();
    }
}

Here is my NbspTwigExtension.php file:

<?php

namespace Craft;

class NbspTwigExtension extends \Twig_Extension
{

    public function getName()
    {
        return '&nbsp; filter';
    }

    public function getFilters()
    {
        $returnArray = array();
        $methods = array(
            'escapeNonNbsp',
        );

        foreach ($methods as $methodName) {
            $returnArray[$methodName] = new \Twig_Filter_Method($this, $methodName, ['pre_escape' => 'html', 'is_safe' => array('html')]);
        }

        return $returnArray;
    }

    public function escapeNonNbsp($content)
    {
        // perform filter operations
        return str_replace('&amp;nbsp;', '&nbsp;', $content);
    }

}

I cannot install the plugin. I get an exception
Can't find Craft\NbspTwigExtension referencing the return line of the addTwigExtension() Method. If I add the force = true argument to the import above it, it installs it, but then upon attempting to use the filter in the twig template it fails even with the import being forced.

What am I doing wrong?

EDIT - I found one bug in my set up where the name of my method in the extension class needs to match how I call the filter from twig. I changed it to:

<?php

namespace Craft;

class NbspTwigExtension extends \Twig_Extension
{

    public function getName()
    {
        return '&nbsp; filter';
    }

    public function getFilters()
    {
        $returnArray = array();
        $methods = array(
            'nbsp',
        );

        foreach ($methods as $methodName) {
            $returnArray[$methodName] = new \Twig_Filter_Method($this, $methodName, ['pre_escape' => 'html', 'is_safe' => array('html')]);
        }

        return $returnArray;
    }

    public function nbsp($content)
    {
        // perform filter operations
        return str_replace('&amp;nbsp;', '&nbsp;', $content);
    }

}

However it still requires "force" true on the import command to work or install. Why!!?


texts: Plugin Settings: Attribute Types, and how to receive

texts:
I have two small arrays I want to store in my plugin settings, though I'm stuck at what the AttributeType:: should be, as well as how to retrieve the actual values. The arrays I want to store look like:

'active_features' => [
     'change_team' => false,
     'change_series' => false,
     'change_user_settings' => false,
],

In my plugin file (pluginHandlePlugin.php) I see I can do something like this:

protected function defineSettings()
{
    return array(
        'pluginSettings1'   => array(AttributeType::Mixed, 'active_features' => array('change_team' => false, 'change_series' => false, 'change_user_settings' => false)),
    );
}

And getting those values through the service file works like:

public function getPluginSettings()
{
$plugin = craft()->plugins->getPlugin('pluginHandle');
$settings = $plugin->getSettings();

return $settings;
}

Which works, and returns the object for me. However I'm unable to get to the actual key/values from the original array, I've tried:

return $settings->pluginSettings1;

But that returns NULL

So, how do I retrieve the keys/values, and also, what is the best AttributeType:: to set for this? I've looked around for AttributeType:: options and details but didn't find anything.

Any help would be GREAT! Thanks!


texts: Output raw html from if statement and combining strings?

texts:
I have the following code:

If imageWidth is specified as 120, it should output:

However it is outputting this:

I've tried using |raw but that doesn't work.

Any ideas?

Thanks


texts: Feed me - Trouble importing table and matrix with translation

texts:
I'm trying to import entries to a chanell using Feed me but having some issues with table and with some multilingual texte in a matrix field.

Craft edition & version  Craft Pro 3.3.2
Feed Me  4.1.2

1. Table field

The Table field has 3 columns

From date : date field
Starting time : time field
Ending time : time field

I've try to format the date and time with different format (2012-04-23T22:00:00.999Z, 2019-08-11 22:00:00, 2019-08-11, 2019/08/11 ...) but the Feed me log always show empty value for those fields.

Feed me logs

{
    "title":"Family Breakfast",
    "webpageMatrix":{"new1":{"type":"blockBody","enabled":true,"collapsed":"1","fields":{"body":"
To bring ... <\/p>"}}},
    "subtitle":"Tour and workshops",
    "datesTable":[{"col1":null,"col2":null,"col3":null}],
    "lacentraleId":"189"
}

Json Feed

{
    "entries": [
        {
            "id": "189",
            "title": "Family Breakfast",
            "subtitle": "Tour and workshops",
            "body": "
To bring ...
",
            "images": [
                {
                    "url": "http:// ... .jpg",
                    "caption": "..."
                },
                {
                    "url": "http:// ... .jpg",
                    "caption": "..."
                }
            ],
            "categories": [
                {
                    "title": "Finishing"
                }
            ],
            "datesTable": [
                {
                    "col1": "2019-09-01",
                    "col2": "09:30",
                    "col3": "10:30"
                },
                {
                    "col1": "2019-09-02",
                    "col2": "09:30",
                    "col3": "10:30"
                }
            ]
        }
    ]
}

2. Matrix Field

I'm trying to import the body as a first block of webpageMatrix (a matrix field) and all is going well for the first language.
But when I'm updating the second language with a second feed my body is overwrite with the new language value for all the three sites while I dont have this problem with my title and subtile.

The Matrix field webpageMatrix is set to be saved in all sites
The body field (redactor) in the blockBody is set to have a different value by site.


texts: Image Transforms adding white to edges of image

texts:
I have my image transforms set to crop centre-centre with quality 100, but for some reason the images that are rendered have a high change of having 1 or 2 pixels of white added to at least one set of parallel sides.

See below for an example of what is being output (black background added after the fact for emphasis):

The original image was a JPG with no white border. As far as I can tell, the issue is most prevalent when trying to crop in only one direction. For example, the the image above should only be being cropped on the top and bottom, as the width of the original is the same as the width of the outputted image.

Has anyone else come across this issue? If so, is there a fix?

Running locally on MAMP with PHP 5.6.10, using GD. Craft Pro 2.4.2679


texts: How can I query entries based on a Matrix Block Type?

texts:
I'm using Element API and trying to create a query that returns a list of entries based on if the entry is using a specific Matrix Block Type.

I've tried a few different things including a query that does a search where the field contains any value, but it's not returning any entries.


texts: Migrating assets from remote volume (Cloudinary) to local folder

texts:
I need to migrate an asset volume from Cloudinary to local folder.
What is the appropriate strategy to execute the change while maintaining database integrity?
Can I simply change the volume type to Local folder and manually transfer my images from Cloudinary to this folder?


texts: Sensible way to have different number of entries on page one of pagination?

texts:
I have a blog where page one has a big "feature" thumbnail and after that each subsequent thumbnail is half the size.
I want that to only happen on page one, which i have done using:

{% if paginate.currentPage == 1 and loop.index == 1 %}

That works perfectly fine.

The problem is that because of this design choice, page one shows 13 entries, but page two onward needs to show 12, otherwise it will look wonky! Any ideas on how i could achieve this?


texts: Best practise to use translate in admin panel

texts:
I am using a lot of translation with the |t / |translate filter. But the client wants to be able to edit those translations in the admin panel.

So, I thought about different ways to achieve that. Please drop your opinion.

Create a new filter, refering to a table under the globals in admin panel. Never did that, but should be possible, right?
Try to get and edit the translation arrays in the phps in the translation folder (dont know how thats possible)
Don't use the |t filter at all. Instead maybe a matrix field type with 2  fields: one not translateable with the origin language and one translatable text field that is translateable. Disadvantage: instead of the convinient |filter I have write code to get the right translation. Also: what about performance?


texts: Why do I get 'Could not resolve the subpath “{slug}” after trying to add a category select to a Neo field?

texts:
I tried to add a Category Select field into a Neoblock but when i first saved the entry I received the following error:

  Internal Server Error

  Could not resolve the subpath “{slug}”.

I removed the Neo Block with the Category Select but the error persists.

Any ideas?


texts:
Craft Personal 3.0.0-RC2 doesn't show the Pro Trial offer anymore? Is that correct?
I did install a Pro License however this triggers the system to change the domain (from local dev to live) which is unwanted.


texts: Can I auto-update to a specific version of Craft?

texts:
Is it possible to auto-update to a specific version of Craft CMS – in particular, to 2.4.2726, the last version prior to 2.5?

I'd like to update some sites that haven't got the latest builds, but I'd prefer to wait for the confirmations of plugin developers regarding compatibility with the changes in 2.5. Can I easily move up to the latest 2.4.x release?


texts: console.groupCollapsed("Application Log"); - what is it?

texts:
If I "View source" in my browser I get a bunch of stuff in the end of my html output. It starts with console.groupCollapsed("Application Log");.

I guess this is something Craft does automatically. Is it possible to turn it off when I launch my site?


texts:
I work with VUE CLI and I want to build a entry form.
My first Idea to bind in the data was props. They work but i can't modify the data (because it's props :D).
To correctly integrate the data, my second idea was to import a JSON File to the data.

So my questions are:
Is it possible to save a entry automatically as a JSON File?
Is there a better solution to binding the entry content to the VUE data?
How can i create a Entry Form with JSON? I can put out a table with |json_encode – is it possible to change this json and to safe it?

Many Thanks!


texts: populateModel usage with eager loading related records

texts:
When retrieving a record in a service and returning a model the static methods: populateModel and populateModels on BaseModel are useful.

When eager loading a related model in the record query, for example:

$variantRecord = Market_VariantRecord::model()->with('product')->findById($id);

This will load the related Record's product into the $variantRecord accessible with $variantRecord->product

when casting this variant record into a Model, using VariantModel::populateModel, will the product also being retrieved be cast into the model->product (AttributeType::Mixed) of the variant?

Or should we manually be manually assigning the ->product attribute as casting it to a model with populate model like this?

$variant = Market_VariantRecord::model()->with('product')->findById($id);
$variantModel = Market_VariantModel::populateModel($variant);
$variantModel->product = Market_ProductModel::populateModel($variant->product);
return $variantModel;

This seems clunky and am looking for suggestions on improving the population of models from records with eager loading of relations.

This is one area


texts: Save as a new entry doesn't seem to copy all locales

texts:
I have a website with 2 locales set up, and have an entry that has content in both.

When I Save as a new entry, Craft only saves the locale that is open at the time, and then copies that same content to the other locale, instead of copying the original localised content.

So I end up having one entry with the same content on both locales, instead of having an exact copy of the previous entry (with different content in the 2 locales)

Is this a bug, a normal behaviour or am I doing something wrong?


texts: Display custom field content instead of full name for user field in craft admin

texts: Is it possible to display custom field content attached to user profile instead of user's first and last name in the admin area for User field?


texts: Craft creating dirty transparent background on image transformations / resizing

texts:
for anyone experiencing dirty transparent backgrounds when you transform transparent PNG images with Craft like this:

Source Image:

Resized, dirty:

Craft Command: craft.assets.id(2).first().getUrl({width: 300})

If you don't see the dirt, watch screen from the side!


texts: Clear template cache after update sale on Craft Commerce

texts:
How can I clear products template cache after update sale ?
Because product price don't change ...
Thank you.


texts: How to utilize unique slugs for plugin elements that extend the BaseElement class

texts:
I have my slug saving to the element_i18n table but it's not unique. When saving a non-unique slug using the default Craft entries, the slug gets appended with "-1".

How can I extend the default functionality for a slug?


texts: Categories field that allows duplicate values

texts: I have a categories field where I would like to be able to include the same category more than once. Any suggestions on how to do this?


texts: How to overwrite base controller beforeAction method

texts:
How do you override the beforeAction method of Craft's base controller? I'm disabling CSRF for a specific route.

public function beforeAction($action): bool
{
    $requestOrigin = \Craft::$app->getRequest()->headers->get('Origin');
    $origin = getenv('ENVIRONMENT') === 'dev' ? getenv('ORIGIN_DEV') :getenv('ORIGIN_PRODUCTION');

    / Disable CSRF validation for valid origins
    if ($requestOrigin === $origin) {
      $this->enableCsrfValidation = false;
    }

    if (!parent::beforeAction($action)) {
      return false;
    }

    return true;
}

I know that there have been similar questions asked before on overriding plugin methods and there's also the blueprint inside the controller itself. Just struggling to understand how to override the craft\web\Controller's method for this


texts: Comparison with an integer from a dropdown list not working

texts:
I'm not sure if this is a bug or not, but there is something weird going on if I try to compare an integer form a dropdown field to an integer in the template. In short, it doesn't work.

I'm working with a dropdown level field for users from 1 to 15 and use conditionals for content:

{% set integer = 7 %}
{% set mylevel = currentUser.level %}

My level: {{mylevel}}

Number: {{integer}}

{% if mylevel >= integer %}
    {{mylevel}} bigger than or equals {{integer}}
{% else %}
    {{mylevel}} smaller than {{integer}}
{% endif %}

This outputs:

My level: 8

Number: 7

8 smaller than 7

HOWEVER if I replace the code "currentUser.level" with 8 like:

{% set integer = 7 %}
{% set mylevel = 8 %}

My level: {{mylevel}}

Number: {{integer}}

{% if mylevel >= integer %}
    {{mylevel}} bigger than or equals {{integer}}
{% else %}
    {{mylevel}} smaller than {{integer}}
{% endif %}

Then the output is:

My level: 8
Number: 7
8 bigger than or equals 7

I checked the database and reinserted all numbers, but nothing changes.

Database had this:

{"options":[{"label":"SG1","value":"1","default":""},{"label":"SG2","value":"2","default":""},{"label":"SG3","value":"3","default":""},{"label":"SG4","value":"4","default":""},{"label":"SG5","value":"5","default":""},{"label":"SG6","value":"6","default":""},{"label":"SG7","value":"7","default":""},{"label":"SG8","value":"8","default":""},{"label":"SG9","value":"9","default":""},{"label":"SG10","value":"10","default":""},{"label":"SG11","value":"11","default":""},{"label":"SG12","value":"12","default":""},{"label":"TG01","value":"13","default":""},{"label":"TG02","value":"14","default":""},{"label":"TG03","value":"15","default":""},{"label":"TG04","value":"16","default":""}]}


texts:
I have three channels: Events, stages and artists.

An artist is added to a timetable super table field in the stage channel. In the event, I have a stages field where I select stages. Events also have a category field.

So: Event ---> stage --(ST field)--> artists.

I basically need two queries for now:

1.- In a filter page, I'd like to display the artists based on a category through events.

2.- In the artist profile, I'd like to show all the events he/she plays.

This is what I have so far, but I feel I could be waaay more efficient, at least the first one, cause the 2nd one I think is not that bad:

1.

// Artists for category through events

{% set category = craft.categories.slug('rock').one() %}

{% set events = craft.entries.section('event').with('stages.timetable.artists').relatedTo(category).all() %}

{% for event in events %}
    {% for stage in event.stages %}
        {% for timeslot in stage.timetable %}
            {% for person in timeslot.artistsSpeakers %}
                {{ person }}
            {% endfor %}
        {% endfor %}
    {% endfor %}
{% endfor %}

2.

// Events of an artist

{% set artist = craft.entries.section('artists').one() %} {# Any artist #}

{% set stages = craft.superTable.getRelatedElements({
  relatedTo: {
    targetElement: artist,
    field: 'timetable.artists'
  },
  section: 'stages'
}) %}

{% set events = craft.entries.section('events').relatedTo(stages).all() %}

{% for event in events %}
  {{ event.title }}
{% endfor %}


texts: Can a user photo support a remote image?

texts:
User photos don't appear to be saved in the same method as Assets. I'm looking to do a remote image (from plugin) as the user profile image. I've got the path saving to the column, but the image is not rendering. Anything special I need to do to get that to render?

$user = craft()->users->getUserById($userId);
$user->photo = $gravatarPath;
craft()->users->saveUser($user);


texts: Pulling entries that have a thumbnail image?

texts:
I'm trying to get only entries with added thumbnail (Assets field with handle 'thumbnail'). Is there a way to check this in this query?

{% set entries = craft.entries.section('blog').limit(4) %}


texts:
I need to group a set of entries alphabetically and I don't get a working and clean solution.
Taking this documentation entry, I am doing it as follows:

  {% set fromAtoF = craft.entries.section('shops').type('shops').order('title').search('title:a* OR A* OR b* OR B* OR c* OR C* OR d* OR D* OR e* OR E* OR f* OR F*') %}
  {% set fromGtoL = craft.entries.section('shops').type('shops').order('title').search('title:g* OR G* OR h* OR H* OR i* OR I* OR j* OR J* OR k* OR K* OR l* OR L*') %}
  {% set fromMtoR = craft.entries.section('shops').type('shops').order('title').search('title:m* OR M* OR n* OR N* OR o* OR O* OR p* OR P* OR q* OR Q* OR r* OR R*') %}
  {% set fromStoZ = craft.entries.section('shops').type('shops').order('title').search('title:s* OR S* OR t* OR T* OR u* OR U* OR v* OR V* OR w* OR W* OR x* OR X* OR y* OR Y* OR z* OR Z*') %}

Problem 1: I get entries starting by 'A' like 'Amazon' in the fromStoZ group, and 'Walmart' in fromGToL...etc
Problem 2: It's not clean nor elegant. There must be other ways to query this but I haven't found the good one yet.

I also tried:

  {% set fromAtoF = craft.entries.section('shops').type('shops').order('title').search('title:a* OR b* OR title:c* OR title:d* OR title:e* OR title:f*') %}
  {% set fromGtoL = craft.entries.section('shops').type('shops').order('title').search('title:g* OR title:h* OR title:i* OR title:j* OR title:k* OR title:l*') %}
  {% set fromMtoR = craft.entries.section('shops').type('shops').order('title').search('title:m* OR title:n* OR title:o* OR title:p* OR title:q* OR title:r*') %}
  {% set fromStoZ = craft.entries.section('shops').type('shops').order('title').search('title:s* OR title:t* OR title:u* OR title:w* OR title:x* OR title:y* OR title:z*') %}

But neither it works; entries like 'Best Buy' and 'JC Penney' don't get into any group, but 'Best Buy2' goes correctly into fromAtoF


texts: What is the optimal place to store CSS files?

texts:
I'm trying to figure out the best place to keep my one master CSS file in craft.

I had the CSS linked in my template as

link rel="stylesheet" href="../craft/css/master.css">

But now Blog entries can't get to it, as they are looking in www.domain.com/index.php/blog/craft/css/master.css now.

Is there a better place to put the CSS, or a better way to link to it in templates?


texts: Element API plugin - Return message when no results are found

texts:
Per this code example, it's clear that the API is expecting to return results based on an existing element...

'transformer' => function(EntryModel $entry) {
    ...
}

And when the criteria finds a matching entry, everything works great!

But when there is no matching criteria results, the API seems to simply return a generic 404 error.

How can I make the API return a message (in JSON format) instead of a 404?

EDIT:

The solution provided by @megatrond is helpful, but doesn't really nail the problem here. I'm actually using that workaround for a different problem I encountered... I needed to guarantee that the user is authorized to ping my endpoint. In implementing that solution, I created a unique access key, included it in the URL, and checked against it before potentially returning a JSON-formatted error message. Under those circumstances, I was able to run a useless query for the sake of allowing me to return JSON.

However, for the issue in this thread... The criteria will either return some results, or no results, and it's not possible to tell before allowing the query to run.

Consider this scenario...

Someone uses my endpoint to target the entry with id 42. Assuming entry #42 exists, the endpoint will successfully return data for it. But, if entry #42 has been deleted or disabled, the endpoint doesn't give me the opportunity to return an error message. Instead, it just kicks out a "404 Not Found" error. :(

Ideally, I'm looking for a fallback for when the criteria returns zero results.


texts: Price formatting thousands/decimal signs

texts:
In the webshop we're building we're outputting the price like so:

{{ cart.itemSubtotal|commerceCurrency(cart.paymentCurrency, convert=true) }}

which displays for example:

€1,680.00

We will be using multiple currencies in the webshop. Is it possible to set the thousands/decimals signs? Or does the CMS take these settings from the locale? We can't find the settings for this anywhere.

Thanks in advance!


texts: Paginate entries with offset / limit when templating

texts:
I've got the pagination function working nicely for a simple for loop of news entries. However I want to split the template up into the first 2 entries as featured items then the next 6 as smaller items. As I paginate through the entries I'd like to keep that layout, however it seems that I cannot use paginatedEntries.limit(2) or paginatedEntries.limit(6).offset(2). Is there another way of doing this?

{% paginate craft.entries.section('news').limit(8) as paginatedEntries %}

News

        {% for entry in paginatedEntries.limit(2) %}
            {# Show first 2 entries #}
        {% endfor %}

        {% set tagentries = craft.entries.section('news').limit(null) %}
        {% if craft.tags.relatedTo(tagentries)|length %}
            {% import "_macros/_news.twig" as news %}
            {{ news.tags(tagentries, 'News', 'news') }}
        {% endif %}

Search in News

            {% import "_macros/_search.twig" as searchForm %}
            {{ searchForm.simple('news') }}

        {% import "_macros/_util.twig" as util %}
        {% if currentUser %}
            {{ util.link('/member-news', 'Browse Member News Articles') }}
        {% endif %}

    {# 6 entries as grid #}

        {% for entry in paginatedEntries.offset(2) %}
                {# Show next 6 articles #}
        {% endfor %}

        {% if paginate.prevUrl %}Previous Page{% endif %}
        {% if paginate.nextUrl %}Next Page{% endif %}
{% endpaginate %}

As soon as I remove .offset(2) or .limit(2) the code functions correctly without errors.


texts: Importing content from EE with FeedMe leaves some data out

texts:
I've posted an issue on the FeedMe repo, but I'm not sure whether that's the correct place for it. Also, there are quite a few issues on there with no reply for a few weeks.
The problem I'm having is I'm importing some data from an EE channel that contains a fluid field into a Craft section that has a matrix field and some of the data isn't being imported and the order of rows is wrong too. This is an example of what I'm trying to import:
<?xml version="1.0" encoding="UTF-8"?>
<entries>
  <entry>
    <count>1</count>
    <total_results>1</total_results>
    <unique>166</unique>
    <author>email@gmail.com</author>
    <title><![CDATA[Newsletter - October 2017]]></title>
    <url_title>newsletter-october-2017</url_title>
    <entry_id>166</entry_id>
    <entry_date>1506996780</entry_date>
    <status>1</status>
    <![CDATA[
October appears to be…
]]>
    <forumThread></forumThread>
    <coverImage></coverImage>
    <modularContent>
      <blockHeading><![CDATA[News 1]]></blockHeading>
      <blockContent><![CDATA[
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure rerum in tempore sit ducimus doloribus quod commodi eligendi ipsam porro non fugiat nisi eaque delectus harum aspernatur recusandae incidunt quasi.
]]></blockContent>
      <blockHeading><![CDATA[News 2]]></blockHeading>
      <blockContent><![CDATA[
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure rerum in tempore sit ducimus doloribus quod commodi eligendi ipsam porro non fugiat nisi eaque delectus harum aspernatur recusandae incidunt quasi.
]]></blockContent>
      <blockHeading><![CDATA[Modding News]]></blockHeading>
      <blockImage>https://www.domain.com/images/content/news/image1.jpg</blockImage>
      <blockContent><![CDATA[
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure rerum in tempore sit ducimus doloribus quod commodi eligendi ipsam porro non fugiat nisi eaque delectus harum aspernatur recusandae incidunt quasi.
]]></blockContent>
      <blockHeading><![CDATA[News 3]]></blockHeading>
      <blockContent><![CDATA[
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure rerum in tempore sit ducimus doloribus quod commodi eligendi ipsam porro non fugiat nisi eaque delectus harum aspernatur recusandae incidunt quasi.
]]></blockContent>
      <blockImage>https://www.domain.com/images/content/news/image2.jpg</blockImage>
      <blockContent><![CDATA[
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure rerum in tempore sit ducimus doloribus quod commodi eligendi ipsam porro non fugiat nisi eaque delectus harum aspernatur recusandae incidunt quasi.
]]></blockContent>
    </modularContent>
  </entry>
</entries>

With the above, the matrix field is being populated with all of the images first, then all of the text content, and none of the headings.
I'm pretty sure all the mapping is correct. The heading block shows up and I've assigned it to blockHeading.
I'm also getting the following error relating to the date:

News: Date parse error: 1506996780 - Could not parse '1506996780': DateTime::__construct(): Failed to parse time string (1506996780) at position 8 (8): Unexpected character.

In EE, that's being output by <entry_date>{entry_date}</entry_date> which is the same as a feed template I did for another channel that imports in Craft with no errors.


texts: How can I display the number of related entries?

texts:
I have a template which displays a table of all the bookings on the website. The booking channel entries consist of two fields: a related user, and a related event, 1:1. There's a drop-down list of all the events at the top of the template which lists all of the events on the site. When a user clicks on an event title, the table updates to only show bookings related to that event (done by applying a class to all rows, and hiding every row which doesn't have the same class as the chosen event slug). The filter code looks like this:

<form class="event-filter">
    <label for="filter">Filter event: </label>
    <select id="filter" name="filter">
        {% for event in craft.entries.section('event') %}
        <option value="i{{event.id}}">{{event.title}}</option>
        {% endfor %}
    </select>
</form>

The bookings table displays all the events using something like this:

{% set bookings = craft.entries.section('booking').order('postDate desc') %}

Is there a way for my filter form to list my events, and display the number of bookings for each event? So it would say, for example:

First event (3 bookings)
Second event (8 bookings)

I'm sure it must be possible using relations, but I can't work out the syntax.


texts:
Struggling to debug this one.

The full log is as follows:

Next exception 'Twig_Error_Runtime' with message 'An exception has been thrown during the rendering of a template ("") in "book/poll-availability" at line 4.' in /var/www/craft/app/vendor/twig/twig/lib/Twig/Template.php:355
Stack trace:
#0 /var/www/craft/app/vendor/twig/twig/lib/Twig/Template.php(314): Twig_Template->displayWithErrorHandling(Array, Array)
#1 /var/www/craft/app/vendor/twig/twig/lib/Twig/Template.php(325): Twig_Template->display(Array)
#2 /var/www/craft/app/vendor/twig/twig/lib/Twig/Environment.php(293): Twig_Template->render(Array)
#3 /var/www/craft/app/services/TemplatesService.php(223): Twig_Environment->render('book/poll-avail...', Array)
#4 /var/www/craft/app/controllers/BaseController.php(74): Craft\TemplatesService->render('book/poll-avail...', Array)
#5 /var/www/craft/app/controllers/TemplatesController.php(55): Craft\BaseController->renderTemplate('book/poll-avail...', Array)
#6 [internal function]: Craft\TemplatesController->actionRender('book/poll-avail...', Array)
#7 /var/www/craft/app/framework/web/actions/CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#8 /var/www/craft/app/framework/web/actions/CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Object(ReflectionMethod), Array)
#9 /var/www/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#10 /var/www/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#11 /var/www/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#12 /var/www/craft/app/framework/web/CWebApplication.php(282): CController->run('render')
#13 /var/www/craft/app/framework/web/CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#14 /var/www/craft/app/etc/web/WebApp.php(279): CWebApplication->processRequest()
#15 /var/www/craft/app/framework/base/CApplication.php(184): Craft\WebApp->processRequest()
#16 /var/www/craft/app/index.php(62): CApplication->run()
#17 /var/www/public-imperialhotels/en/index.php(22): require_once('/var/www/craft/...')
#18 {main}
REQUEST_URI=/en/book/poll-availability?token=9923444c-13b4-41bb-b7ab-9e339277bacc&iframe=true&room-urns=

And the template in question looks like this:

{% set token = craft.request.getParam('search') %}

{% if (not craft.request.isAjax and not token ) %}
    {% exit 404 %}
{% endif %}

{% hook 'microsGetAvailabilityResults' %}

{% header 'Content-Type: application/json' %}

{% set data = {
    'complete': results.complete,
    'urn': results.urn,
    'pollUrl': craft.request.url ~ '?' ~ craft.request.queryStringWithoutPath
} %}

{{ data | json_encode | raw }}

So line 4 specifically is this:

    {% exit 404 %}

That should only be called if token is blank and as you can see from the REQUEST_URI, it should be set:

REQUEST_URI=/en/book/poll-availability?token=9923444c-13b4-41bb-b7ab-9e339277bacc&iframe=true&room-urns=

Any suggestions?

What's most frustrating is that this has been picked up in server log monitoring on a live box and we can't replicate it.

The template exits correctly if we hit the URL with a non-Ajax request and if no token is defined, so what gives?


texts:
Has something changed recently regarding the ocalized {siteUrl} setting? I'm setting up a new localized site on MAMP PRO and the old config code I used on several other projects is throwing an error "Array to string conversion".

This works fine:

return array(
'*' => array(
    'omitScriptNameInUrls' => true,
),

'pazzo.dev' => array(
    'devMode' => true,
    'environmentVariables' => array(
        'fileSystemPath' => '/Applications/MAMP/htdocs/pazzo/',
        'siteUrl' => 'http://pazzo.dev:8888/'
    )
),

'*.pazzo.be' => array(
    'devMode' => false,
    'cooldownDuration' => 0,
    'environmentVariables' => array(
        'fileSystemPath' => '/opt/www/pocopazzobvba/web/www.pazzo.be/',
        'siteUrl' => 'http://www.pazzo.be/'
    )
)

);

This (what I have used before) throws the error.

return array(
'*' => array(
    'omitScriptNameInUrls' => true
),
'pazzo.dev:8888' => array(
    'devMode' => true,
    'environmentVariables' => array(
        'siteUrl' => array(
            'en' => 'http://pazzo.dev:8888/en/',
            'fr' => 'http://pazzo.dev:8888/fr/',
            'nl' => 'http://pazzo.dev:8888/'
        ),
        'fileSystemPath' => '/Applications/MAMP/htdocs/pazzo/'
    )
),
'www.pazzo.be' => array(
    'cooldownDuration' => 0,
    'devMode' => false,
    'environmentVariables' => array(
        'siteUrl' => array(
            'en' => 'http://www.pazzo.be/en/',
            'fr' => 'http://www.pazzo.be/fr/',
            'nl' => 'http://www.pazzo.be/'
        ),
        'fileSystemPath' => '/opt/www/pocopazzobvba/web/www.pazzo.be/'
    )
)

);

Am I missing something obvious??


texts: Craft on Vagrant: Please advise on initial install (Craft can’t connect to the database with the credentials in craft/config/db.php.)

texts:
I am trying to install a craft playground using vagrant and puppet.
After firing the default installation for a LAMP stack and creating related DB and User, granting privileges, ... I want to start the craft installation, all I get is:

  Craft can’t connect to the database with the credentials in craft/config/db.php.

The commands I am using to create the DB:

CREATE DATABASE craftdb CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER craftadmin@localhost IDENTIFIED BY 'ThisPassword';
GRANT ALL PRIVILEGES ON craftdb.* TO craftadmin@localhost;
FLUSH PRIVILEGES;
EXIT

The dp.php looks like this:

// The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
'server' => 'localhost',

// The database username to connect with.
'user' => 'craftadmin',

// The database password to connect with.
'password' => 'ThisPassword',

// The name of the database to select.
'database' => 'craftdb',

// The prefix to use when naming tables. This can be no more than 5 characters.
'tablePrefix' => '',

PHP Packages installed:

"php5",
"php5-common",
"php5-cli",
"php5-mysql",
"php5-sqlite",
"php-pear",
"php5-dev",
"php5-gd",
"php5-curl",
"php5-mcrypt",
"libapache2-mod-php5"

Any suggestions are much appreciated


texts: Should I pluralize a channel's index slug?

texts:
Lets say I have a channel called places, which has the following URL :

http://example.com/places

The url points to a directory of individual places.

However, when you click into an entry, each entry is a place, so it might make more sense to have each entry's url to be :

http:/example.com/place/place-name

Am I right in assuming that the best way to go about this would be to use a route for entries? Or is it best practice to keep things the same for consistency?


texts:
I just moved a site over to a Windows server, and my homepage loads fine, but sub pages are not loading. I just get an error message that the connection was reset. Adding index.php to the url doesn't do anything.

My control panel is also loading fine, it's just the sub-pages.

I don't really have any experience with Windows servers, so I'm not sure how to go about troubleshooting this. I'm using the standard craft web.config file. Is there a config setting I need to add?


texts:
I can't work out how to output <link rel="alternate"> for each language variation?

Is there any easy way to do this please?

Many thanks!


texts:
What I'm trying to do is add two checkbox in the entry edition page, just under the dates or special notes, somewhere here :

Then if the checkbox is checked, I check it with an event and perform an action. But I dont know how to display my two checkboxes, I know it's all about the hook but I can't find the one.

Any advices ?


texts: Front-End Entry (Guest) saving correct values on error

texts:
I'm building a Guest Entry Form, and one of the fields is a dropdown. Everything feeds through fine, but if one of the other fields has a validation error, I can save any inputted data with the code as outlined in the Entry Form

<input id="customField" type="text" name="fields[customField]"
{%- if entry is defined %} value="{{ entry.customField }}"{% endif -%}>

But, with the dropdown, I can't get the value to stick, it always defaults to the first option (It's to grab a name title - eg, Mr. Mrs, Miss etc) on an error:

<select name="fields[honorific]">
    {% for honortitle in entry.honorific.options %}
        <option {%- if entry is defined %} value="{{ honortitle.value }}{% endif -%}">{% if entry is defined %}{{ honortitle.value }}</option>
    {% endfor %}
</select>

So, if I've already selected the option at the bottom of the list, how do I get the field to remember what I've selected if there's an error elsewhere?

Thanks, Simon


texts: Use url segment as querystring parameter [Craft 3]

texts:
I have mysite.com and I need to use a segment as if it were a querystring parameter for accomplishing this:

mysite.com/us         ->  same template as: mysite.com
mysite.com/pricing/bz ->  same template as: mysite.com/pricing
mysite.com/shops/ag   ->  same template as: mysite.com/shops
mysite.com/team/mx    ->  same template as: mysite.com/team
...etc

In my templates I need to know the value of the country code used in the first segment for using country-specific values for small details like illustrations and prices. Just as if it was a querystring parameter, but it has to be a segment.

Note: This has nothing to do with language. I also have already a multi-site configuration for two languages: mysite.com and mysite.com/es

So I would also need to support these too:

mysite.com/es/us        ->  same template as: mysite.com/es
mysite.com/es/bz/shops  ->  same template as: mysite.com/es/shops
mysite.com/es/ag/team   ->  same template as: mysite.com/es/team
... etc

What's the way to go? How do I tell Craft to render the template for mysite.com/{section_name} when requesting mysite.com/{section_name}/{country_code} So I can use country_code as a parameter from the craft.request segments? I'm struggling with this


texts:
When trying to update CraftCMS I'm getting the following errors:

Error: An error occurred

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

Problem 1
- Installation request for craftcms/cms 3.0.21 -> satisfiable by craftcms/cms[3.0.21].
- craftcms/cms 3.0.21 requires enshrined/svg-sanitize ~0.9.0 -> satisfiable by enshrined/svg-sanitize[0.9.0] but these conflict with your requirements or minimum-stability.
Problem 2
- craftcms/ckeditor 1.0.0-beta.2 requires craftcms/cms ^3.0.0-RC1 -> satisfiable by craftcms/cms[3.0.21].
- craftcms/ckeditor 1.0.0-beta.2 requires craftcms/cms ^3.0.0-RC1 -> satisfiable by craftcms/cms[3.0.21].
- craftcms/cms 3.0.21 requires enshrined/svg-sanitize ~0.9.0 -> satisfiable by enshrined/svg-sanitize[0.9.0] but these conflict with your requirements or minimum-stability.
- Installation request for craftcms/ckeditor 1.0.0-beta.2 -> satisfiable by craftcms/ckeditor[1.0.0-beta.2].

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

The problem is, the following is all OK:

composer update comes back with "Nothing to Install"


texts: How to handle custom text on a channel index page?

texts:
I'm setting up a site with several channels, and the design requires an introductory paragraph at the top of each channel's index page (ie. before the list of entries) - essentially a post that corresponds to the channel's index page.

As I understand it, there's only a template but no entry corresponding to the index of a channel, so I'm wondering how best to handle this in Craft. I definitely don't want it hard-coded in the template, and ideally it should be somewhere reasonably intuitive for site admins to find and edit.

It feels like it should be straightforward to implement, but I just can't quite think how to do it. Any suggestions would be much appreciated!


texts: Craft Commerce: Creating Customer Accounts?

texts:
I just want to confirm how accounts are created for customers in Craft Commerce.

Currently in the the Craft Commerce download the checkout processes provides the option to "login" or proceed with as a "guest" just providin the email. Is this the method of creating a customer account OR do we have to activate public registrations and point people to a registration page?

I'm a little unsure what needs putting into effect here. Any documentation people can point me to would be useful.


texts: AJAX Front-end User Registration Form not displaying macro errorList

texts:
I have a user registration form on my Front-end which is submitted with Ajax which works fine.

The only problem is that if I have any errors, like an already in use username they wont be displayed. The still function but just wont be displayed. Same goes for empty required fields.

Without using AJAX the errors are displayed as they should though.

Here is my Ajax:

$('#registrationForm').submit(function(ev) {
    ev.preventDefault();

    var data = $(this).serialize();

    $.post('/', data, function(response) {

    console.log(response);

    if (response.success) {
        console.log("success")
    } else {
        console.log(response.error);
    }
});

Here is my form:

<form id="registrationForm" method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="/succes">

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}
    <input id="firstName" type="text" name="firstName" placeholder="Naam">
    <input id="username" class="hidden" type="text" name="username"
        {%- if account is defined %} value="{{ account.username }}"{% endif -%}>
    <input id="email" type="text" name="email" placeholder="E-mailadres"
        {%- if account is defined %} value="{{ account.email }}"{% endif %}>

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

    <input id="wachtwoord" type="password" name="password" placeholder="Wachtwoord">

    <input id="leeftijd" type="text" name="leeftijd" placeholder="Wat is je leeftijd?">

    {% if account is defined %}
        {{ errorList(account.getErrors('password')) }}
    {% endif %}
    <input id="userPhoto" class="button sec hover-btn blue-btn" type="file" name="userPhoto" value="{{ acc.uploadProfielButton }}">
    <input class="button hover-btn orange-btn" type="submit" value="{{ acc.aanmeldenButton }}">
</form>


texts:
I need to serve different home pages (structure entries) depending on the subdomain. For example:

foo.example.com -> this will render an entry with slug "foo"
bar.example.com -> this will render an entry with slug "bar"

So far I created a plugin and fetched the proper entry based on the subdomain:

class LocationsPlugin extends BasePlugin
{
    (...)
    public function init()
    {
        if (craft()->request->isSiteRequest()) {
            (...)
            // at this point $entry is the entry I want to render
            // the problem is the following doesn't work:
            craft()->templates->render("subdomains/_entry", ["entry" => $entry]);
        }
    }
}

I get the layout rednered but without the content. Twig's blocks aren't rendered at all and I suspect init() hook is called before some initializations required by render().

The question: How can I, having $entry in init(), just render it instead of the main page?

Thanks!
Jan


texts: Plug-In Store doesn't have the option for adding / trying plugins (post upgrade 2.6 -> 3.5)

texts:
Having recently upgraded a dev instance of CraftCMS 2.6 to 3.5, I'm trying to add the plugins via the store.  I can find all the plug-ins I want to add, however there's no option on the page to add / try the plug-in.  I figure I've probably missed something basic.
Anyone got an idea of what I should be looking for here?
(am pretty new to this environment...)


texts: Use a custom Element Type without sources?

texts:
I want to create a custom plugin (element type) that does not allow custom fields. Therefore, when digging through existing element types, do I really need to have the getSources method?

If this is the case, what is the P&T definition of "sources" and are there any base element types that don't use "sources"?


texts:
On one of our sites that runs the Sprout SEO plugin we recently keep getting a HTTP 500 Error on the redirect + when I'm trying to create a new redirect as a 404 Page redirect or even updating an existing Redirect.

Is this a server sided issue or could this be resolved due to some settings changes?


texts: Element API - Filter on a value from a multi value field

texts:
I am looking for some assistance with the Element API plugin. I need to filter on the bannerPageCategories field which is a multi select checkbox field. The value will be passed via a querystring value. I can filter on a field with a single value but how do I do this for fields which has an array of values.

Any suggestions will be greatly appreciated.

Sample code and json response is below.

Json Response:

    {
      title:"Test Banner 4",
      url:"http://localhost:8888/banners/test-banner-4",
      jsonUrl:"http://localhost:8888/api/banners/17",
      content:"Test.",
       page-categories:[
       {
         label:"ADSL",
         value:"adsl",
         selected:true
       },
       {
        label:"Fibre",
        value:"fibre",
        selected:true
       }
    ],
   campaignId:"sHKJJK",
   targetUrl:"http://xyx.xaws.co.za",
   image1:"//xyx.xaws.co.za/dev/images/banners/banner-lg.png",
   image2:"//xyx.xaws.co.za/dev/images/banners/banner-md.png",
   image3:"//xyx.xaws.co.za/dev/images/banners/banner-sm.png",
   date_published:"2018-05-22T14:06:05+02:00",
   date_modified:"2018-05-22T14:06:05+02:00"
  }

Code:

    'api/banners' => function () {
        \Craft::$app->response->headers->set('Access-Control-Allow-Origin', '*');
        $target = \Craft::$app->request->getQueryParam('target');
        $campaign = \Craft::$app->request->getQueryParam('campaign');
        return [
            'elementType' => Entry::class,
            'criteria' => [
                'section' => 'banners',
                'bannerPageCategories' => $target,
                'campaignId' => $campaign
            ],
            'transformer' => function (Entry $entry) {
                $image1 = $entry->image1->first();
                $image2 = $entry->image2->first();
                $image3 = $entry->image3->first();

                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'jsonUrl' => UrlHelper::url("api/banners/{$entry->id}"),
                    'content' => $entry->htmlcontent,
                    'page-categories' => $entry->bannerPageCategories,
                    'campaignId' => $entry->campaignId,
                    'targetUrl' => $entry->targetUrl,
                    'image1' => $image1 ? $image1->url : null,
                    'image2' => $image2 ? $image2->url : null,
                    'image3' => $image3 ? $image3->url : null,
                    'date_published' => $entry->postDate->format(\DateTime::ATOM),
                    'date_modified' => $entry->dateUpdated->format(\DateTime::ATOM),
                ];
            },
        ];
    },

Many thanks!


texts:
I have a plugin that has an onBeforeSaveUser event. This fires the mailchimpsubscribe plugin to subscribe users to selected newsletters.

Everything works correctly the user is subscribed and then the saveUser function saves the users newsletter preferences to the database.

I am now trying to get it to work with an ajax call, which again works correctly and subscribes the user to mailchimp. However after sending the json response it does not appear that the saveUser function is being fired as nothing is updated in the database for the selections made.

Could the ajax be stopping the saveUser from being fired?

Ajax:

// Get the post data
var data = $(this).serialize();

// Send it to the server
$.post('/', data, function (response) {

    if (response.success) {
      $form.parents('.question-box').fadeOut(function () {
        $(this).remove();
        $('.question-box').first().fadeIn();
      });
    } else {
        var message = response.message;
      alert('Unfortunately, we were unable to save your data at this point. Please try again later.'+message);
    }
});

Mailchimp Plugin:

if ($api->errorCode) { // an api error occured

      // Respond appropriately to Ajax Requests.....

} else { // list subscribe was successful

      // Respond appropriately to Ajax Requests
      if (craft()->request->isAjaxRequest())
      {
        return $this->returnJson(array(
          'success' => true,
          'errorCode' => 1,
          'values' => array(
            'email' => $email,
            'vars' => $vars
          )
        ));
      }

      //.....
}

Cheers


texts: Output entry title in subject line of notification when sprout form is submitted

texts:
I am new to this so, excuse the lack of proper terminology. But I am using the Sprout Forms plugin (v1.1.0) on a site we designed for a real estate client. What I am hoping is that a visitor could fill out a form, and then the notification email would include the page title {{entry.title}} of the page which the form was filled out on. Otherwise would I need to create a unique form for every page in a craft "channel?" The site url is http://sivelluxury.com...

I've currently got this in the subject line of the notification pane for that contact form - {fullName} Submitted a contact form on {{entry}} was filled on {{ siteName }} {dateCreated|date('Y-m-d')}

Anyone who can help me?


texts: Import / Aggregation DB - with 50 Million Records - Best Practice?

texts:
I'm working on my second Craft project ever. (First was an ultra-simple site just to learn the basics.)

With this new project I need to accomplish 2 things...

(1) - Private - Import/aggregate mass data from external sources based on my specific search parameters (think YouTube, CNN, BBC, Instagram, Reddit, Imgur, Pinterest, etc).  Then slice, dice, curate, categorize, headline, and editorialize that data to create content-rich, topical feeds.

(2) - Public - Present those content-rich feeds as dense Topical Resources for my website visitors.

Craft is a brilliant solution for building a robust (and lightning fast) Public front end.

But based on how Craft operates underneath the hood... What's the Best Practice for managing the Private raw data behind the scenes?

Is it smarter to have ONE Craft Install with one DB - and separate tables for the imported (but not yet published) data?

OR

Is it wiser to do TWO entirely separate Craft Installs - one for the Private back-end work (importing, compiling, editing, building newly curated feeds) - and another to grab and serve the Public (post-curation) results?


texts: How can I create a family tree hierarchy in Craft?

texts:
I'm struggling to think of a way to create a family tree hierarchy in Craft.

I've tried using categories and structures, but run into the problem of needing child nodes to have two parent nodes.

I.e.

Generally, what's the best way of achieving this?


texts: Target a certain entry type on the entries fieldtype

texts:
I have all of my entries as single pages, but of different types depending on the section. I need to create a field that allows users to link to another page entry, but I need to ensure they only select one of a certain type.

Is it possible to only allow users to choose entries of a certain type using the entries field? I can't see the option, so perhaps if not there's a plugin that could do this? Has someone come across a good solution.


texts:
I have a page that lists all of the property developments of my client, and am able to show the lists of the categories in the dropdown fields, but I can't work out how to get them to actually change the results below.

Attached is a screenshot

So how do I get the results below the filters to change to only show the selected item in the dropdown? Am completely stuck on this.

What would be really helpful is a simple walkthrough of what I need to do to make the selected filter output results on the page, as is a complicated subject. And need it explaining in detail if possible, as am a beginner at this.

And here's my code:

    <form class="form-inline" action="{{ url('developments') }}" method="get">

        Location

          <select id="county1" class="form-control" name="county1" onchange="this.form.submit()">
            <option>All</option>
            {% for category in craft.categories.group('counties').order('title asc') %}
            <option value="{{ category.slug }}">{{ category.title }}</option>
            {% endfor %}
          </select>

      ........more dropdown code...
    </form>

      {% for category in craft.categories.group('developments').order('title asc') %}
      ......code for block...
      {% endfor %}


texts: Editing entries on multisite Craft CMS implementation

texts:
We have a Craft CMS implementation with 3 sites enabled (multi-site). When I create an entry, it populates the entry to all 3 sites, which is fine. However, I would like to modify a link or content for only 1 of the sites. If I used the dropdown, select the site, then make my change and save, Craft still saves that change to all 3 mini sites.
Is editing 1 entry per minisite possible or do I have to create a duplicate?
Thanks!


texts: Matrix | Craft 3 Element API / Scout Plugin

texts:
I am trying to grab the contents a matrix field (Redactor).

Here is the section of code I am struggling with:

$bodyBlocks = [];
foreach ($entry->getFieldValue('pageBuilder')->all() as $block){
   switch ($block->type->handle) {
      case 'blockText':
      $bodyBlocks = $block->blockTextPara;
      break;
   }
}

// Begin defining the response data for this entry
$data = [
  'title' => $entry->title,
  'slug' => $entry->url,
  'status' => $entry->status,
  'textArea' => $bodyBlocks,
];

It is submitting to Algolia but the contents of the matrix block is empty.

{
  "title": "Transport",
  "slug": "http://xxxxx/boarding-at-bruern/the-london-link",
  "status": "live",
  "textArea": {},
  "heroBanner": "http://xxxx/images/uploads/banners/_algoliaTransform/ASC7795.jpg",
  "objectID": "1_408"
}

For reference here is my entire scout.php config file:

<?php

    return [
        "sync" => true,
        "application_id" => "xxx",
        "admin_api_key" => "xxx",
        "mappings" => [
            [
                'indexName' => 'xxx',
                'elementType' => \craft\elements\Entry::class,
                'criteria' => [
                    'section' => 'websitePages',
                    'type' => 'websitePages'
                ],
                'transformer' => function(craft\elements\Entry $entry) {

                    Craft::$app->getConfig()->getGeneral()->generateTransformsBeforePageLoad = true;

                    $bodyBlocks = [];
                    foreach ($entry->getFieldValue('pageBuilder')->all() as $block){
                        switch ($block->type->handle) {
                            case 'blockText':
                                $bodyBlocks = $block->blockTextPara;
                                break;
                        }
                    }

                    // Begin defining the response data for this entry
                    $data = [
                        'title' => $entry->title,
                        'slug' => $entry->url,
                        'status' => $entry->status,
                        'textArea' => $bodyBlocks,
                    ];

                    // Get the first asset in a "heroBanner" Assets field (if there is one) and then add it to the data array.
                    $heroBanner = $entry->heroBanner->one();
                    $data['heroBanner'] = $heroBanner ? $heroBanner->getUrl('algoliaTransform') : '/images/site/search-default.jpg';

                    return $data;

                },
            ],
        ],
    ];


texts:
I need to get the amount of a discount from orders to write that data into a json file (on EVENT_AFTER_COMPLETE_ORDER) which then will be consumed by an inventory management system and now am stuck with discount amounts. Currently I have:

"price": ' . $order->adjustment->one->type('discount')->amount . ',

which does not work. Could anyone help on how to do this and maybe point me to the documentation where I could read up on it?

Thanks
m


texts:
I've put together an entry form with a front end file upload, following the excellent answer here. It works perfectly, for logged in users only.

I'm wondering is this method is at all workable for guests?

When I attempt a file upload via the front end form when not logged in, I get:

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost/login

The form submission works with text data, but the file field is not populated.

I'm looking to accept resume pdfs on a public job application form, hence the need for this to work for non-authenticated users.


texts: Can you run Craft CP on one webserver and serve the front end content on a separate one?

texts:
Much of my work is for a corporate organisation, and there is some resistance to having the CP of a CMS externally exposed. Is it possible to run the Craft CP on one internal (not available outside the network) webserver, and the front end on a separate webserver in the external DMZ which has its access to the CP turned off? Both would talk to the same database (I can see how this could work for two full versions). This is how we run our homegrown CMS which also stores all assets (CSS, JS, templates, images and PDFs) in the database, so I know I would have to find a solution for that, but I am imaging a CDN would solve that problem. What are the technical and licensing issues that need to be addressed? I want to ditch the homegrown CMSes in use, for Craft.

It isn't just the CP that would only be available inside. I want to make all the end user form data be accessible for view and 'office use' update as well i.e. so the form submissions are managed internally only.

Also, I might want to expose separate Sections as standalone websites (these are small 6-10 page medium term sites for conferences, but sometimes have their own domain. The form submissions would be consolidated). These separate sites would all be on the same external server.


texts: Relating entries/users with a custom element (or custom database table)

texts:
Let's say I have a bunch of Craft entries and Craft users that I need to relate to another custom database table. How would one approach this?

Would I be correct in thinking that my plugin will need to:

Create a custom element type which ties back to this custom database table
Create a custom field type, based on an existing field type such as EntriesFieldType.php and is able to handle the GUI actions for creating the relationship
Apply that field type to any edit forms which need to relate to my custom table

Is there anything I'm missing, or any gotchas in implementing the above?


texts: How to add target to link within field instructions?

texts: I don't see anything in the documentation about how flexible the instructions fields are, as they use Markdown syntax. It's not clear how to add a target to a link, for example.


texts: Pass value in form using the amforms plugin

texts:
I've created a (apply for a job) form using amforms.
I'm using this form for multiple jobs. Whenever someone replies with this form, I want to pass the job name in the form.

I've tries many thing but can't find a solution.

Anyone?


texts: if I have a single that is available in English & Spanish, how do you edit the title for the non default language?


texts: Inconsistent search results in multi-site setup (prod/stage)

texts:
I have set up a staging site alongside production just like the docs describe (Craft Solo 3.4.24). I have copied the "Site Settings" for all sections and set the "Propagation Method" to "Save entries to all sites enabled for this section".
Because Craft had trouble replicating all entries in one queue job I did this manually via CLI using ./craft resave/entries --type=<type> and ./craft resave/entries --section=<section>. This worked beautifully.
But I have an issue with the site search. Locally, when I search e.g. for 'citizen', I get the expected results (count is 60). Same on production. But on stage I get only 2 results back.
When I add .site('*') to the query in Twig I get 120 results back, so the staging site does have all entries.
It appears as if the search index on stage is not complete? Is there anything I can do to refresh it?
Thank you!


texts: Contact form submission type in Contact Form Extensions

texts:
I have a site with three forms that use P&Ts Contact Form plugin. My client now wants the submissions to be visible in the backend and have a 'download to CSV' if possible.
I was looking into the Contact Form Extensions plugin to visualise the data, but I can't find a way to change the submission type from 'contact' so the three different form types can be easily filtered in the left hand column (see screen below).

Is there a way to do this with some custom code on submission? Also, is there a plugin to allow me to download the submissions as CSV?
I'm basically just trying to avoid a new form plugin entirely as the forms are built quite custom on the front end.
Thanks in advance!


texts:
I am trying to reset the default path to the dashboard from admin to something else. I have this in config/general.php:

return array(
    'cpTrigger' => 'new-url',
    'omitScriptNameInUrls' => true,
    'devMode' => true,
);

But when I go to devsite.myurl.co.uk/new-url, I get a 404 error. I got this working locally but not since I installed the site on a staging server, and imported the database and changed the general and db files. Any ideas?

If I take out the cpTrigger line, and just use devsite.myurl.co.uk/admin, everything is fine.


texts: Posting to plugin's action controller using Ajax + JSON

texts:
I want to use Ajax to POST to a plugin endpoint and get a JSON response. The plugin I'm using is for Mailchimp newsletter subscriptions and should allow for JSON responses:
https://github.com/aelvan/mailchimp-subscribe-craft
I have my form:
<form action="" method="post" novalidate>
  {{ csrfInput() }}
  <input id="email" name="email" type="email" >
  <input type="submit" value="Subscribe">

and my Javascript:
let json = this.toJSONString(this.form);
let xhr = new XMLHttpRequest();
xhr.onload = () => {
  if (xhr.status >= 200 && xhr.status < 300) {
    // ...
  } else {
     // ...
  }
};
xhr.open("POST", "actions/mailchimp-subscribe/audience/subscribe", true);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.send(json);

This hits the endpoint, but I get a 404 response:

HTTP 404 – Not Found – yii\web\NotFoundHttpException
Template not found: actions/mailchimp-subscribe/audience/subscribe

As I understand it, I'm correctly posting to the relevent plugin controller action by using the URL actions/mailchimp-subscribe/audience/subscribe. Furthermore, if I do a GET to that URL I get a 400 response which would lead me to believe the routing is correct.
The error therefore seems to be in the Craft controller/routing handler. It's not detecting that I've send a JSON string and that I want a JSON response (and not a template/HTML response).
What's going on here?


texts: How can I get field's value of entry in other site locale in my element-api endpoint?

texts:
I'd like to get a field value in 3 differents locales in the same element-api endpoint but I can't make a request similar to this one :  craft.entries.siteId($siteId).id($entryId).one() in twig.

<?php

use Craft;
use craft\elements\Entry;

return [
  'endpoints' => [
    'exhibitions.json' => function() {
      return [
        'elementType' => Entry::class,
        'criteria' => [
          'section' => 'exhibitions',
          // 'locale' => ['francais','english', 'deutsch']
        ],
        'transformer' => function(Entry $entry) {

          // -- Description --
          $description_fr = ($entry->summary) ? $entry->summary : ($entry->body) ? $entry->body : '';
          // $entry_en = $craft->entries->siteId(2).id($entry->id).one();
          // $description_en = ($entry_en->summary) ? $entry_en->summary : ($entry_en->body) ? $entry_en->body : '';
          // $entry_de = $craft->entries->siteId(3).id($entry->id).one();
          // $description_de = ($entry_de->summary) ? $entry_de->summary : ($entry_de->body) ? $entry_de->body : '';

          // -- Tags --
          $tags = '['.$entry->exhibitionsType->label.']';
          foreach ($entry->exhibitionsCats as $key => $cat) {
            $tags .= ',['.$cat['title'].']';
          }

          return [
            'type' => [
              array('target_id' => 'event')
            ],
            'title' => [
              array('value' => $entry->title)
            ],
            'field_subtitle' => [
              array('value' => $entry->subtitle)
            ],
            'field_description_fr' => [
              array('value' => $description_fr)
            ],
            // 'field_description_en' => [
            //   array('value' => $description_en)
            // ],
            // 'field_description_de' => [
            //   array('value' => $description_de)
            // ],
            'pictures' => [
              'url' => $entry->banner->one()->url,
              'copy' => $entry->banner->one()->legend,
              'alt' => $entry->banner->one()->legend
            ],
            'field_event_type' => [
              array('value' => '3') // Long or permanent event (3)
            ],
            'field_date' => [
              array(
                'value '=> $entry->fromDate->format('Y-m-dTH:i:s'),
                'end_value '=> $entry->toDate->format('Y-m-dTH:i:s'),
                'rrule '=> null,
              )
            ],
            'field_state' => [
              array('value' => 'scheduled')
            ],
            'field_type' => [
              array('target_id' => 6) // Audience - Pour tout public (6)
            ],
            'field_categories' => [
              array('target_id' => 24347) // Exhibitions (24347)
            ],
            'field_tags_rest' => [
              array('value' => $tags)
            ],
            'field_location' => [
              array('target_id' => 5179)
            ],
            'field_websites' => [
              array(
                'uri' => $entry->url,
                'title' => $entry->title)
            ],
            'field_email_address' => [
              array('value' => getenv('EIL_EMAIL'),)
            ],
          ];
        },
      ];
    }
  ]
];