texts: Triggering JavaScript from back-end event

texts: I'm building a plugin and want to trigger some JavaScript on an event being fired (eg an entry being saved). What is the best way to achieve this? Coming up short looking through the documentation and Stack Overflow.


texts: I'm currently using the A&M Forms plugin and was wondering if I can import fields from the native Craft 2 fields?  I have already created 20 or so fields that I will use in both the native sections and the A&M Forms sections.


texts: Getting categories in elementAPI performance issues and help required

texts:
I am using elementAPI to get data from a directory.
The items listed in the directory have two categories assigned:
Category level 1 country
Category level 2 region

Below is how I am getting the data in the elementAPI plugin

'api/v2/country/<slug:{slug}>.json' => function($slug) {

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->slug = $slug;
$category = $criteria->first();
return [
    'elementType' => 'Entry',
    'criteria' => [
        'section' => 'directory',
        'relatedTo' => ['targetElement' => $category],
        'limit' => 1,
    ],
    'transformer' => function(EntryModel $entry) {

        return [
            'country' => (string)$entry->country[0],
            'port' => (string)$entry->country[1],
            'title' => $entry->title,
            'mapinfo' => $entry->mapaddress,
            'url' => $entry->url
        ];
    },
];
},

The addition of

'country' => (string)$entry->country[0],
'port' => (string)$entry->country[1],

adds 1.5 seconds to the request, compared to not putting them in which comes in at .656ms. It seems the category data is already requested outside of the transformer but i cant see how to get the category array into the transformer. I also can't see why the specifying the categories  in the transformer is so 'expensive'.

Any ideas on speeding up would be very welcome.


texts:
What is the different between url() and getUrl()
Ex:
   {% set solutionIcon = solution.solutionIcon.one() ?? null %}

      {% if solutionIcon %}

      {% endif %}

   {% set solutionIcon = solution.solutionIcon.one() ?? null %}

      {% if solutionIcon %}

      {% endif %}


texts: Database Exception with Sprout Forms after updating to Craft 3

texts:
I've recently updated a site from Craft 2 to 3. I'm getting this error after login in to the admin regarding Sprout Forms which was installed in my Craft 2 install.
What can I do to get the back-end functioning again? The front-end is fine apart from the pages which contained sprout forms, which I've removed.

Error Info: Array
(
    [0] => 42S22
    [1] => 1054
    [2] => Unknown column 'sproutforms_forms.saveData' in 'field list'
)
↵
Caused by: PDOException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sproutforms_forms.saveData' in 'field list'
in (path)/vendor/yiisoft/yii2/db/Command.php at line 1258


texts: Can plugin have two links in admin navigation?

texts: Is it possible to add another link to admin navigation? For example I have plugin clients which has it's own Button in the admin menu, in the same plugin i have newsletter so I would like to have that Newsletter in that menu as well.


texts: How do you check for a value in an array with the criteria model?

texts:
I am building plugin which has a function to return any users that have a specific interest checked in their profile. The interests field is an array. What I need to do is check if the specific interest is in the interests array and only return users that have selected that interest. So far I have the following but this returns all users and not just users with the flagged interest. So how can I use the criteria model to check if the interest exists in the array?

$interest = craft()->request->getPost('interest');

//Get all users with specified interest
$user_criteria = craft()->elements->getCriteria(ElementType::User);
$user_criteria->interests = $interest;
$users = $user_criteria->find();

Cheers


texts: I have a client that will only be accepting payments by check at this time.  It is a larger company that has same clients and they bill the client and check is mailed.  However they want to be able to take orders online and I really wanted to try Craft Commerce.  What I need to do is somehow bypass the payment step.  I would like to be able to send them an invoice, but not one that says paid.  Any suggestions.


texts: How to shorten 'craft.request.getUrl()' with the shortener plugin?

texts:
How can I use the shortener plugin to get and shorten the current URL?

I've tried both twig and plugin methods shown in the docs, but the twig method outputs the FULL url, and the plugin method doesn't work at all (no output).

Here is what I have in my template:

 {% set longUrl = craft.request.getUrl() %}

share link: {{ longUrl|shorten }}

The result with this is the full URL.

My configs in the plugin settings:

I cleared my system cache after I updated the settings as well.

Any ideas what I'm missing here?


texts:
I updated Craft to version 2.6.2798.

Since then I'm getting a PHP error:

Parse error: syntax error, unexpected '[' in /craft/app/fieldtypes/BaseElementFieldType.php on line 428

PHP version on the server is 5.53.

Any ideas to fix that issue?


texts: Is it possible to add an entries field to recurring events that can be changed per occurrence?

texts:
An event in Solspace Calendar that repeats weekly should have an entries field, that can be changed per single occurrence. E.g. Tuesday’s evening class is usually tought by teacher A, except next week, where it’s going to be teacher B (both teachers have an entry I’d like to link to in the event’s popover).

Is this possible?


texts: Craft 3: Prevent craft adding script filename to URLS

texts:
I'm running Craft 3 with multi-site.

Working well so far, but my hosting doesn't allow me to create traditional vhosts with their own directories and shared upper filesystem.

As such I have an htaccess at my webroot which rewrites the URL based on the subdomain being used.

foo.website.com -> server/web/foo
bar.website.com -> server/web/bar

This works, but it means the script filenames are actually rendered into the CP URLS.

So my CP URLs are rendering the server path to the script file:

foo.website.com/foo/admin/...

I want Craft to think the CP URL is just foo.website.com/admin since this loads correctly with the rewrite rule.

Looking at the URL helper, it seems to add the script filename in either way. Is there a way around it?

Thanks!


texts:
So I hope I am explaining this correctly.

I have some entries with a tag called 'hidden'. In my blog layout I want to exclude those entries.

I have the following:

{% set tag = craft.tags.name('hidden') %}
{% set hiddenentry = craft.entries.section('blog').relatedTo(tag).find() %}
{% set allentry = craft.entries.section('blog').limit(5).find() %}
{% set unhidden = allentry|without(hiddenentry) %}

{% for entry in unhidden %}

{{ entry.title }}

Posted on {{ entry.postDate.format('F d, Y') }}

            {{ entry.body.getPage(1) }}
            {# {{ entry.summary }} #}
            <button>Continue reading</button>

{% endfor %}


texts:
I'm building a simple low traffic website in Craft for a customer whose web server only allows access over ftp. How would you have done the work in practical terms? Building the site locally and then copy everything manually over FTP when done?

Is it for this kind of websites completely wrong to make minor adjustments directly on the server?


texts:
I want the list of entries in admin to allow sorting by entry type. It can sort by any arbitrary field, but not entry type or author (for some weird reason).
Is there any way to modify that without modifying the source?


texts: Commerce: Combining unwanted quantity discounts

texts:
quantity discounts

I have the following offer with quantity discounts for a series of my products:

Buy 1 item and get $5 off per item
Buy 2 items and get $10 off per item
Buy 3 items and get $15 off per item

I set these discount rules in my control panel under "commerce" > "promotions".

problem

The problem is that Craft combines the quantity discounts. So when I put 3 items into the cart, Craft will for each item add a $5 discount plus a $10 discount plus a $15 discount per item – so instead of a $15 discount per item I get a $30 discount per item.

I thought I might work around this by taking this process into account and simply reducing the quantity discounts in the control panel so they would add up to the desired amount.

But that's no solution if I want to display discounts per item and discounted item price correctly on the frontend.

Plus another issue: When I put 3 items into the cart, I will then see 3 types of discounts applied to my cart which is confusing.

Is there any way to avoid this sort of combining of discounts?
Will I have to create an Adjuster to accomplish my intended pricing structure?


texts:
We are still trying to make a custom mail plugin. We have one problem left. When someone makes a draft, and later publishes it, only the onSaveEntry fires but without NewEntry. So we were trying to use the onPublishDraft instead. But we can't get it to fire. I'm using Craft CMS 2.6.3 Pro

this is what we tried so far:

craft()->on('entryRevisions.onPublishDraft', function(Event $event){}
craft()->on('entryRevisions.publishDraft', function(Event $event){}
craft()->on('publishDraft', function(Event $event){}
craft()->entryRevisions->onPublishDraft = function(Event $event) {}
craft()->entryRevisions->publishDraft = function(Event $event) {}

this is the regular on save entry we use, maybe there is another way to catch a draft that is being published;

craft()->on('entries.saveEntry', function(Event $event){
if ($event->params['isNewEntry'] && $entry->status == 'live'){    }});

Hope you guys know how to do that

UPDATE

I did do a test with the exact code Brad gave, but it still didn't do anything... This is how my test starts;

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

    craft()->on('entryRevisions.onPublishDraft', function(Event $event) {
        Craft::log("draft published", LogLevel::Info, true);
    });

    craft()->on('entries.saveEntry', function(Event $event) {
        Craft::log("Entry saved", LogLevel::Info, true);
    });
}

Only the second one gets logged when I change the status of the post, the first never.

*****************************************
2017/12/21 21:29:54 [info] [application] [Forced] Entry saved
*****************************************


texts:
We are creating a new website using Craft CMS.

The main functionality of it is to let user to create their own mini-site.

All the users should have their own control panel and manage their pages and menu.
There should be url per user like username.site-name.com/nameofthepage
The administrator should be able to manage all mini-site

Does anyone already done something like this? Is there any plugin already done for this kind of functionality ?

Thanks!


texts: Server requirements for uploading large images

texts:
I'm experiencing the problem that I can't upload large images. Very similar to this problem: Craft CMS max image resolution? But I couldn't solve the problem so far.

My first question is: Where do I have to place the php.ini so the upload script knows about it? (My web hosters help pages tell me to upload the file in every directory that need the ini files settings) I've tried /craft/app (next to index.php and Craft.php) and /htdocs (the web root).

Plus: I've tried to upload the exact same images to Craft at another web hoster where it works fine. But the limitations there are even stricter than where the problem occurs).

That means: if the location of the php.ini was right the values of post_max_size, memory_limit and max_execution_time are not the problem. Also it doesn't depend on the file size but on the image resolution.

image1.jpg | 703 x 951 pixels | ~850,000 Bytes → does work
image2.jpg | 2520 x 1680 pixels | ~750,000 Bytes → doesn't work
image2.jpg | save with same resolution as: "image3.jpg" → doesn't work
image2.jpg | save with lower resolution as: "image4.jpg" → does work

Does anyone know what else I could check to solve that problem?

Thanks for any help.


texts: How do I target the 3rd entry and only that entry?

texts:
I am trying to build an Index page and assign a specific card template to the 3rd entry and only the 3rd entry.

{% set items = craft.entries.section('posts').all() %}

{% for cardC in items.offset(2).limit(1) %}

Marketing

{{ cardC.title }}

                   {{ cardC.introParagraph }}

                    subject Read Case Study

{% endfor %}

I also tried {% for cardC in items.nth(3 )%}.

I get the following **error message**:

  Impossible to invoke a method ("offset") on an array.

I created the set because I need to apply templates for the other entries, etc.


texts:
I've got a bizarre issue that is only happening on staging. Locally all urls work correctly.

on staging http://domain.com/archives and http://domain.com/photography/entry_slug both return a 404 page generated by the host see screenshot

However if I actually try to visit a page that truly does not exist the craft 404 page shows, which is what I would expect for a real 404 error. For example http://domain.com/foo

This is only my second craft site and I have no idea how to troubleshoot. All help is appreciated.


texts: Linking to specific entries in Twig: How performant is Reference Tags parsing?

texts:
I have a small menu of fixed entries that forms a sub-nav on a site.

I'm currently using Reference Tag parsing to grab links to these entries:

Help

Donate

About Us

I think this is a really clean/readable way to create this sub-nav, but I'm not sure about the performance implications. I could accomplish the same thing by calling up an ElementCriteriaModel using a fixedOrder:

{% entries = craft.entries.id(3666, 3667, 3668).fixedOrder(true) %}
{% for entry in entries %}

{{ entry.title }}

{% endfor %}

Does anybody know if one option is significantly performant over the other?

(I wouldn't be surprised if Craft is intelligently caching its entry data queries, such that it wouldn't have to create a new element query each time a Reference Tag is encountered/parsed... but I'm not knowledgable enough to say.)

Other SE questions about best-practice for linking to single entries:

What's the best way to link to an entry in a template?
How do I create a link to an entry using entry's id?


texts: Listing all entries which belong to an entry

texts:
Trying to list all the entries which belong to an entry. Currently I have the following field format:

Product

Has an 'retailer' entries field.

Retailer

Normal entry.

On the retailers _entry.html page I'm trying to display all the products which belong to said retailer. But the code I'm producing is running into trouble:

retailers/_entry.html

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

    {% for entry in relatedProducts %}

Some great entries

    {% endfor %}

This code seems to be showing the title but not actually looping over the length of the array?


texts:
Can I extract a transform's settings from its handle? I'm trying to avoid upscaling images using the workaround, and I'd like to set my transform handle dynamically within some conditionals. (see this link).

Say I'm looping through a matrix field as in the example below, using a dropdown variable to determine which transform is best. When outputting the image I'd like to replace that '970' with pixel width specific to that the asset transform. I'm sure this is wrong, but I'm imagining something like getTransform(transform).width.

{% if block.formation == 'twins' %}
    {% set transform = 'medium' %}
{% else%}
    {% set transform = 'large' %}
{% endif %}

<figure>
  <img src="{% if image.getWidth() > 970 %}{{ image.getUrl(transform) }}{% else %}{{ image.url }}{% endif %}" alt="{{ image.title }}" />
</figure>


texts: The Definitive Guide to Extending Twig in Craft CMS

texts:
So Craft's implementation of Twig is already very powerful and suitable to most common tasks. The Craft Docs already provide a great intro into using Twig and the handy extensions provided by Craft:

Craft Templating Overview
Craft Twig Primer
Craft Full Templating Reference

But what about when you need to go further and build in some sweet custom functionality?

This question serves to be a starting point that summarises all the different ways to extend Twig with custom functionality, including:

Filters, functions, objects, macros and statements – when to use which
Creating a custom Twig filter
Accessing variables and functions in a plugin
Creating a custom global function
Creating a custom global object
Creating a custom statement (or "logic tag")
Creating a custom operator
Calling a plugin service class from Twig
Making custom database calls from Twig
Post-processing HTML after Twig has finished rendering
Changing Twig settings


texts: Outputting Sprout Form from a matrix field

texts:
I'm using Sprout Forms to handle email forms on a website. Hardcoding a template with the code: {{ craft.sproutForms.displayForm('contactForm') }} works fine like in the docs.

But I have a Matrix field to build the page content so I'd like to add a new field type to that I can select which form to display. There is a Matrix field type 'sprout forms' which lets me select the form fine in the CMS.

My question is how do I now display the form in the template. I can't see any documentation on how to do this?

I've tried things like {{ block.customForm.displayForm() }} but with no luck.

Has anyone tried this before?
Thanks.


texts:
I have some Matrix blocks where I need to sum one of the fields within, but I only want to sum it when another field within that block is or is not empty.
{% set reimbursementAmount = craft.matrixBlocks()
  .relatedTo(cat)
  .fieldId(9)
  .sum('field_item_reimbursementAmount')
  .specialCase(':empty:')
  %}

With this, I get an error:
Impossible to invoke a method ("specialCase") on a string variable ("101.00").
How do I sum the desired field, but only where another field (specialCase) is empty (or is not empty, as the case may be).


texts: Commerce 2 — Guest checkout error: no customer email address exists on this cart

texts:
I'm having a problem with checking out as a Guest.

Below is the design so you can see what I'm talking about...

Although I'm entering an email address in the Guest Checkout email field — when I get to the payment page it won't allow payments to process due to an error pop-up message stating "no customer email address exists on this cart."

Both login options (on the Checkout index template) are using separate <form>'s so I know that isn't an issue. I've tried different email addresses and still nothing.

I've also checked the Craft Commerce GitHub repo templates and can see the action and redirects are the same as what I've got in mine.

Has anyone else came across this problem before and knows how to fix it?

Is it worthwhile switching to the new template structure (email > account > etc etc)?

Thanks in advance


texts: How to get a list of unique related entries from within a related entries loop

texts:
Bear with me as I am not sure the best way to explain this.
But to try and summarise... how can I loop through related entries (locations) inside a a related entries loop (exams -> related to the current entry/page) but ONLY output the locations and ONLY output the unique locations (ie. I don't want it t show location1, location1, location2, location1. I just want it to show location1 and location2 (once - unique).
This is where I am at, but not working yet.

Here is a screenshot to try and illstrate:

I only want Bushy to appear once, not 4 times.

So my page is setup like this;
First I set the Mock Exams to find all the Mock Exams related to the current entry (page).
Like so:

{% set mockExams = craft.entries
  .section('mockExams')
  .with('location')
  .relatedTo({
  targetElement: entry,
  field: 'mockExamCategory'
})
  .all() %}

I am then using this code to list all the mock exams in 2 separate areas on the page.
This works fine and as expected.

However, I need to then get all the unique location entries that are related to the mock exams.
I took me ages to fathom this out on how to to do this. I only managed with some great support through the Discord channel.

Anyway, the way this was finally achieved was as follows:

  {% set uniqueLocations = [] %}
  {% set uniqueLocationsIds = [] %}
  {% for entry in mockExams %}
    {% set locations = craft.entries.section('locations').relatedTo(entry.id).all() %}

    {% for location in locations %}
      {% if location.id not in uniqueLocationsIds %}
        {% set uniqueLocationsIds = uniqueLocationsIds|merge([location.id]) %}
        {% set uniqueLocations = uniqueLocations|merge([location]) %}
      {% endif %}
    {% endfor %}
  {% endfor %}

{% for location in uniqueLocations %}
  {{ location.title }}<br />
  {{ location.address }}
{% endfor %}

I have written this up for reference if anyone else comes across this.

But also for anyone more experienced in Craft - is this the most efficient way or is there a more efficient/streamlined approach?


texts: Form for admins to register users from the front end

texts: Is there a way to create a front-end form that would allow a user with appropriate privileges (Register users) to register new users?


texts: Combine Eager-Loading and relatedTo(category)

texts:
For a website I'm building for a client I've build a navigation where on hover an image changes dynamically to the image assigned to the entry. See this page for a better understanding: http://sandmandance.com/dev/projects/performance

It all works fine but at first page load the images are only loading when hovering over the navigation which causes a small glitch. What I'd like to do (and seems like the easiest solution) is to load all the assets on page load using Eager-Loading.

Thing is.. I can't seem to combine it with relatedTo(category). So in short; how can I combine Eager-Loading and relatedTo(category) in a way it works?


texts: Issue Devmode is still enable in multi-environment config file

texts:
I have an issue with a site I have just put live. devMode is still enabled even though the config site sets it as false for .com.

Code snippet:

'*' => array(
        'devMode' => 'false',
        'siteName' => 'sitename',
        'omitScriptNameInUrls' => true,
        'maxUploadFileSize' => 33554432,
        'defaultSearchTermOptions' => array(
            'subLeft' => true,
            'subRight' => true,
        ),
        ),
    '.com' => array(
        'devMode' => 'false',
        'env' => 'live',

I did have a .dev option as well but removed this to see if it would make any difference but it hasn't.

Next I cleared all caches and still no joy devMode is still active. How can I clear this for the the live site has it logged it in the DB somewhere and it's not removing it?


texts: How do I prevent Twig from encoding HTML?

texts:
I've created a field type that stores its value as a model. That model’s __toString() method returns the result of a craft()->templates->render() call:

public function render()
{
    $render = craft()->templates->render('myplugin/templates/mymodeltemplate');
    return $render;
}

public function __toString()
{
    return $this->render();
}

When I output the model from a template, like so:

{{ entry.myField }}

Twig encodes the resulting HTML as a string with HTML entities.  Running the string through html_entity_decode() before returning it in __toString() doesn't help.  I'm assuming this string formatting is happening somewhere at the Twig level.

Being new to Craft, I'd love to understand a little more of what's going on here.  How does the string representation of an element model get passed to and handled by Twig?


texts:
As Craft doesn't provide an all-in-one link field (that covers external as well as internal links) out of the box, I opted for LinkIt.

What I wonder, how do I

Obfuscate email-links?
Bring phone numbers to a working format, by removing whitespace and adding the + in the right spot?

I expected LinkIt would do that by itself, but I haven't seen where yet.


texts: Search, by just one user field - fullName?

texts:
I'm successfully listing user (authors) via search from the url, so

/author/Tom+Bowler lists data and entries by that name with

{% set getauth = craft.request.lastSegment %}
{% for authordetails in craft.users.search(getauth) %}

but we want to limit that search to 'fullName' (or what is best) ideally, as currently we are listing any authors not just the one that may mention "Tom Bowler" in their bio.

At what point, and how is best to filter down to that search?


texts:
Are nested matrices panned for the coming future releases?

I currently have a matrix where users can upload various assets. For each asset, they should be able to specify different details but this cannot be achieved with the current features as there is no way in which the details could be related to a particular asset that has just been uploaded.


texts:
I've read that you can set a variable inside of a loop, and set that same variable outside of the loop with "" to be able to use it outside of the loop. Although when attempting this, it is not working for me. Here is the code I am using (simplified for the purpose of troubleshooting):

{% requireLogin %}

{% if currentUser == user.username %}

{# -- Set Excludes Expenses here as well, to use out of the loop -- #}
{% set excludedExpenses = "" %}

    Excluded Expenses (Outside Loop): {{ excludedExpenses }}

{{ dump(excludedExpenses) }}

    {# -- Get All Expense Entries -- #}
    {% set userExpenses = craft.entries.section('expenses').authorId(currentUser.id).limit(null) %}

        {# --- Excluded Expenses Loop -- #}
        {% for expense in userExpenses if expense.excludeExpense.contains('Temporarily Exclude') %}
            {% set excludedExpenses = expense.expenseName %}

            Excluded Expenses (Inside Loop): {{ excludedExpenses }}

{{ dump(excludedExpenses) }}

        {% endfor %}
        {# -- End Excluded Expenses Loop -- #}

{% endif %}

This is the result - http://cl.ly/image/1Z2Q2r2Q102s

The variable is only being recognized and displayed inside of the loop. The actual variable I will use (beyond this simple test) is an integer. I tested with an integer variable and that failed also, so I am not sure if that would change anything for this example. Thanks in advance for any help you can give! :)


texts: One structure section for multiple menu's (navigations)

texts: I want to use one structure section for multiple menu's (navigations). So I want all pages under topmenu in the topmenu (header) and I want all pages in the bottommenu in a menu in the footer. How can I accomplish this most easily in my twig file?


texts: Knock Knock plugin throws »Request contained an invalid body param« after submitting password

texts:
I've freshly installed the Knock Knock plugin.
When I submit the Password for the first time, I get the following error: Request contained an invalid body param
After a Refresh it works just fine. But when I'm triggering it again (e.g. changing the needed password), I can reproduce the error.
I tried it with Knock Knock's default template as well as a custom one.


texts: Getting a single, random, related entry within a plug in

texts:
Given a Matrix with each row containing a text field and a multi relationship field. And I am picking 1 Matrix row based on the value in the text field. How would I go about selecting a single, random, related entry for that row?

I've tried to do this a couple of ways but I'm not really getting anywhere.

I'm selecting the Matrix row and getting the related entries using

$matrixRow = $entry->matrixField->textField($stringToMatch)->first();

$relatedEntries = $matrixRow->relationshipField;

But how can I now pick one of those related entries at random?
Is the only way to create an array and shuffle it?
Or is there a way I can do it when fetching the Matrix row?

I've tried adding the following in an attempt to get all the related entries associated with the Matrix row. Figuring I can then modify this query by adding a limit and ordering randomly to get my 1 related entry. But it's coming back empty.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section         = 'videos';
$criteria->relatedTo       = array(
    'targetElement'   => $matrixRow,
    'field'     => 'relationshipField'
);

$entries = $criteria->find();

foreach($entries as $entry){
    var_dump($entry->title);
}


texts: Empty page instead of 404 error when url contains channel slug

texts:
I have a website where my client can create entries in a couple of different channels.

Lets take a "news" channel. The url would be: "example.com/news/nameofpage"

Whenever a wrong url is entered manually behind "example.com/news/" (or maybe a wrong filled in link) it won't go to the 404 page but just enters the channel's template and display's an empty page. For everything else the 404 error works but whenever a channels slug is in the url as a first segment it only gives an empty template.

EDIT:

I figured out it happens all the time whenever there is a second segment in the url


texts: {% cache %} always creates new cache data, never uses existing cached data

texts:
Why would the {% cache %} tag be storing a new cache every time the page loads (instead of just loading the existing cache)?

Unless I'm misunderstanding how caching works, the system should never record duplicate cache keys, correct?

Despite the data apparently getting cached, the page never feels like it's pulling from cache. Every page load feels long and sluggish.

UPDATE:

I've done some additional testing, and was able to get the caching to perform as expected. Here's what changed...

In my original version, I was caching a giant chunk of the template. This included the large database query (100+ records with 100+ fields), some Twig-side data manipulation, and the entire HTML portion of the template. Within the HTML, I am looping through those records and rendering a chunk of HTML for each.

In the new version, I am only caching the HTML loop. This is making a huge difference, bringing the page load time from ~15 seconds to ~1 second.

What I've found...

It appears that the offending line which was causing multiple cache keys to be generated is this one:

{% set entries = craft.entries.section('mySection').type('myType').limit(null).find %}

I still don't know why, and would appreciate an explanation if anyone knows!


texts:
I am looking for some advice on how best to add error messages (eg incorrect password / username) on a custom Login form.

Tried the usual routes for documentation but have seen nothing as yet - all help appreciated.

Dan


texts: What purpose does the site-selector under assets fulfill?

texts:
I'm kind of confused about the site selector under Assets, because from what I can gather it actually doesn't do anything? See this screenshot, top left:

I was first under the impression that I would only see assets that have been uploaded for a specific site, but that doesn't seem to be the case. Every user seem to see all content for a volume, meaning I would have to create a volume per site in order to separate them?


texts: Show a table field's column headers in template?

texts:
The question says it all.

I have:

A Matrix field, with
A subfield with the type table
Two columns within that table of which I want to show the column headers in my template

Is that possible and if yes, how?


texts: Stripe is throwing a server error when trying to access a webhook to the Charge plugin. Some investigation revealed the error is triggered by an 'invalid or missing CSRF token.


texts: Delete all old versions from the database

texts: I've been working on a site for a while in beta. The number of versions for all the pages is getting big and the database is now over 2MB. I'd love to just delete all the old versions of all pages when I go live with the site. Is there any easy way to do this?


texts: Does the authenticate method in the User class work?

texts:
This doesn't work:
$user = User::find()->email("bob@example.com")->one();
if ($user->authenticate("myClearTextPassword")) {
  // This is never true, so you never get here
}

Is this method broken, or am I using it incorrectly?


texts: How can I get the correct folder ID when uploading assets from a front-end form/plugin?

texts:
I am able to upload images to an S3 bucket successfully, but I am really stumped as to how it's working.

I have a file input in my template, and in my controller I am doing this:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = craft()->config->get('section', 'mySection');
$criteria->limit = 1;
$criteria->status = null;
$criteria->authorId = craft()->request->getPost('userId');
// have also tried getting the user like this for sanity:
// get the same id either way
//$user = craft()->userSession->getUser();
//$criteria->authorId = $user->id;

$entry = $criteria->first();

if ($entry) {
    ...
    $folder = craft()->assets->findFolder(array(
        'sourceId' => $this->assetSourceId,
    ));
    error_log($folder->id) // 207

    $upload = craft()->assets->insertFileByLocalPath(
        $tempFilePath,
        $photo->getName(),
        $folder->id,
        AssetConflictResolution::KeepBoth
     );
     if ($upload->isSuccess()) {
         ...
     }
}

Everything works great. The image is uploaded to the correct S3 bucket.
But when doing the same in the CP the folder ID is actually different. It looks like it should be 27?

I'm also trying to upload another file my-file.json from the same front-end form. I am using the same technique above to get the folder ID, and it is returning the same number (207). However the asset is getting uploaded to the correct folder (207). But in my case that is actually the incorrect folder. It should be uploading to 27.

Is there a more effective way to get the correct folder Id? Thank you for any suggestions!

FWIW, folder 207 is the first folder in my asset list...

UPDATE

I'm just going to keep updating this as I fumble through it and revise it to an answer when I figure it out.

Using craft()->assets->findFolder() will find the first folder that matches a given criteria.

Since in my above example, I am only passing in the source Id, that means that I'm only going to get back the first folder for that resource. (In my case that would be folder 207).

By changing the findFolder() params to this:

$user = craft()->userSession->getUser();
...
$folder = craft()->assets->findFolder(array(
    'sourceId' => $this->assetSourceId,
    'name' => $user->username
));

I am now getting the correct folder Id back. How I was able to upload images successfully prior to this is still a mystery.


texts: How to add a custom button at the right section of an entry?

texts:
I would like to add a custom button in the right section of a channels entry form in the CMS.
The this button needs to go to a custom url of the plugin that I have created. The link should contain entry ID so that I can use this ID in my plugin.


texts:
I am looking for some support as the developer who built my site (www.lexiconthai.com) is no longer available.

I need a few small changes doing right now (adding meta tag plug in, changing fonts), but will need small jobs doing on a regular basis.

Any idea where I can find someone to support me?

Thanks in advance,

David


texts: Error uploading .bmp file format - gets rejected

texts:
I'm doing some testing on file uploads and discovered that the .bmp file format gets rejected even though defined in my config file as an allowed file extension.

I have added the following to my config file:

 'extraAllowedFileExtensions' => 'bmp, jpeg, tiff, pdf, cdr, gbr, gtl, dxf, dwg',
 'allowedFileExtensions' => 'bmp, jpeg, tiff, pdf, cdr, gbr, gtl, dxf, dwg',

This is the error I receive:

The file “/private/var/tmp/php7Md2bj” does not appear to be an image.

/shop/craft/app/etc/image/Image.php(138)

138    throw new Exception(Craft::t('The file “{path}” does not appear to be an image.', array('path' => $path)));

How do I fix this?


texts: How should I set an arbitrary session value in a plugin?

texts:
I have some data I want to store in session:

$data = array
(
    'id' => '23539471'
    'token' => 'cf310b81-9431-4303-804d-c1635ae29278'
);

In my plugin I am doing this:

new HttpCookie('myCookieName', $data, [ 'expire' => time() + 3600 ]);

When I dd() that I can see the cookie as expected:

Craft\HttpCookie#1
(
    [name] => 'myCookieName'
    [value] => array
    (
        'id' => '23539471'
        'token' => 'cf310b81-9431-4303-804d-c1635ae29278'
    )
    [domain] => ''
    [expire] => 1427328767
    [path] => '/'
    [secure] => true
    [httpOnly] => true
    [CComponent:_e] => null
    [CComponent:_m] => null
)

However on the next page load the cookie is null:

$cookie = craft()->request->getCookie('myCookieName');

What am I doing wrong here?

::::EDIT::::

I have also tried this which seems to make the cookie available in the current request, but it's null on the next request:

$cookie = new HttpCookie('myCookieName', $data);
$cookie->expire = time() + 3600;

craft()->request->cookies->add('myCookieName', $cookie);


texts: How can you check if a field exists in a section, not by entry?

texts:
For a plugin, I need to check if a certain field exists in a section. How can i manage that? I'm using the settings section from the plugin, looping through all sections by craft()->sections->getAllSections() and in the template with the following code:

{% for section in sections %}
    {% if section['specificfield'] is not defined %}
        do something
    {% endif %}
{% endfor %}

This doesn't seem to be working. Any ideas on how to check correctly?


texts: Output Entry with Super Table, Matrix, Table for Element API

texts:
I'm trying to output a table within a matrix of a SuperTable for element API.
I fail to output $projectList, I keep getting the error 'Invalid argument supplied for foreach()' or 'Trying to get property 'bizProjectItem' of non-object'
'transformer' => function(Entry $entry) {
  $bodyRows = [];

  foreach ($entry->bizTable as $row) {
    $bodyprojects = [];

    foreach ($row->bizprojectMatrix as $block) {
      switch ($block->type->handle) {
        case 'bizprojectBlock':
          $projectList = [];

          $bodyprojects[] = [
            'projectTitle' => $block->bizproject1,
            'projectDetails' => $block->bizproject2,
            'lists' => $projectList
          ];

          // Fail to output anything
          foreach ($block->bizProject as $project) {
            $projectList[] = [
              'projectList' => $project->bizProjectItem
            ];
          };

          break;
      }
    }

    $bodyRows[] = [
      'title' => $row->bizTitle,
      'projects' => $bodyprojects
    ];
  }

  return [
    'type' => 'projects',
    'details' => $bodyRows
  ];
},

The error not shown anymore after I update it as below, but it fails to output the details.
if (is_array($block->bizProject) || is_object($block->bizProject)){
  foreach ($block->bizProject as $project) {
    if(!empty($project->bizProjectItem)) {
      $projectList[] = [
        'projectList' => $project->bizProjectItem
      ];
    };
  };
};

Here is my front-end,
{% for bizRow in entry.bizTable %}
    {% for bizProjectItem in bizRow.bizProjectMatrix.type('bizProjectBlock') %}
        {% for bizProjectRow in bizProjectItem.bizProject %}
            {{ bizProjectRow.bizProjectItem }}
        {% endfor %}
    {% endfor %}
{% endfor %}

Here is my latest update, I manage to get the data by using this method, but I will only get the first data using this method. How my loop should look like if I want to get all the data?
'lists' => $block->bizProject[0]['bizProjectItem']


texts: Paginate based on date-based starting points

texts:
I'm working on creating a simple calendar based on only native Craft fields. While coding this, I'm having a hard time getting the pagination to work properly.

The calendar currently lists all upcoming events this current month. Next/Previous should then paginate the calendar 1 full month forward/backward (not 1 month backwards from todays date, but all entries in the next/previous month).

According to Brandon, paginate.prevUrl/nextUrl won't map to specific date-based starting points. So, how do I tackle this problem then?

Here's my current code:

Hva skjer i Filadelfia

            {% set startDateTime = now|date_modify('0:00')|date('c') %}
            {% set endDateTime = now|date_modify('first day of next month 4:00')|date('c') %}

            {% set startDateParam = 'and, >= ' ~ startDateTime ~ ', < ' ~ endDateTime %}

            {% set events = craft.entries.section('calendar').limit('15').startDate(startDateParam).order('startDate asc') %}

{% for event in events %}

{{ event.startDate | date("d") }}.

{{ event.startDate | date("M") }}

{{ event.title }}

{{ event.body | hacksaw(words='75', allow='') }}

{{ event.startDate | date("H:i") }}

{% endfor %}

{% paginate craft.entries.section('calendar').limit(15) as pageEvents %}
    {% for month, entries in pageEvents | group("postDate | date('F')") %}

            {% if paginate.prevUrl %}Previous Month{% endif %}
            {% if paginate.nextUrl %}Next Month{% endif %}

    {% endfor %}
{% endpaginate %}


texts:
We have a change profile page where members can choose out of the users table who of the other members is their mother (or father).

Below my (simplified) user profile form

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
<script>$(':checkbox').checkboxpicker();</script>
{{ getCsrfInput() }}
<input type="hidden" name="action" value="users/saveUser">
<input type="hidden" name="redirect" value="leden/wijzig-profiel?m=updated">
<input type="hidden" name="userId" value="{{ currentUser.id }}">
<input type="hidden" name="fields[mother][]" value="">

<label for="mother">{{ 'mother'|t }}</label>
<select name="fields[mother][]" >
    <option value="">There is no mother</option>
    {% for mother in mothers %}
    <option value="{{ mother.id }}">{{ mother.name }}</option>
    {% endfor %}
    {% for user in users %}
    <option value="{{ user.id }}">{{ user.name}}</option>
    {% endfor %}
</select>
<input type="submit" value="{{ 'Save'|t }}" name="proceed" >

I've tried to empty the field mother but that results in a CDbException error.

CDbCommand faalde tijdens het uitvoeren van volgend SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`familywebsite`.`craft_relations`, CONSTRAINT `craft_relations_targetId_fk` FOREIGN KEY (`targetId`) REFERENCES `craft_elements` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `craft_relations` (`fieldId`, `sourceId`, `sourceLocale`, `targetId`, `sortOrder`, `dateCreated`, `dateUpdated`, `uid`) VALUES (:row0_col0, :row0_col1, NULL, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7), (:row1_col0, :row1_col1, NULL, :row1_col3, :row1_col4, :row1_col5, :row1_col6, :row1_col7). Bound with :row0_col0='136', :row0_col1='1', :row0_col3='', :row0_col4=1, :row0_col5='2016-10-08 09:54:35', :row0_col6='2016-10-08 09:54:35', :row0_col7='e4211e99-5bbd-46c1-b703-c44e82bc4667', :row1_col0='136', :row1_col1='1', :row1_col3='2409', :row1_col4=2, :row1_col5='2016-10-08 09:54:35', :row1_col6='2016-10-08 09:54:35', :row1_col7='c0fb9927-89f1-4993-ba26-bc47a63bdc50'

This I can understand because the mother is a relation of the user, and by clearing the mother field value, it probably does not delete the relation and it will give and error like it does.

So question is how to delete the relation with mother field?


texts:
I want to include Parse SDK in my plugin. I created a folder lib and put the SDK in it. and called like that in controller:

namespace Craft;
use Parse\ParseClient;
use Parse\ParseQuery;

    $APPID = 'xx';
    $MASTERKEY = 'xx';
    $RESTKEY = 'xxx';
    $PARSEURL = 'https://api.parse.com/1/';

    $list = new parseQuery('Dance');
    $results = $list->find();

And it says: Fatal error: Class 'Parse\ParseQuery' not found in /vagrant/craft/plugins/xx not found.


texts: Entries object getting reset after a relatedTo query

texts:
This is from a template that worked in Craft 2, but doesn't in Craft 3.

{% set entries = craft.entries.type('publications').orderBy("postDate desc") %}

entries.count() outputs 80

{% for cat in allCats %}
    {% set catEntries = entries.relatedTo(cat) %}
    {% if catEntries | length or cat.slug=="all" or cat.slug=="toutes" %}

{{ cat.title }}

    {% endif %}
{% endfor %}

This iterates through all categories with correct entries associated

After that, entries.count() outputs 0

Looks like entries is getting set to the last value instead of just passing the resulting object to the variable.  This is not how it worked before.  Is there a way to reset this ?


texts: Craft is unable to determine if an update is available at this time

texts:
No chance to update on my local machine and on my live site.
On the staging site it works but that's the same server as the live site.

I've cleared the caches and checked the logs.

Local there is only this error:

2016/06/19 19:41:01 [error] [application] Error in Craft\Et::phoneHome. Message: Cannot overwrite an existing license.key file.

But I run the site in DEV Mode.

Any ideas? I'm a bit unhappy about it :/

Best
David


texts:
I am seeing warning icons on drop down fields like this

Where does this come from?


texts:
I am looking for a user-friendly, non-destructive way define an image crop when editing an entry with an asset field.

Should be able to visually define an image crop
Should be able to change the crop when editing the entry
Should not crop/overwrite the original image
Should not generate a new asset in the asset library for the cropped image

I am aware of the built-in cropping tool, but it is not very userfriendly since it either crops the original asset (destructive) or creates a new asset with the cropped image (confusing and messy). This (A) makes it confusing to edit the cropping (you need to hunt down the original asset and create a new crop) and (B) introduces the need to sanitize your asset folders to remove unused crops.

I am also aware of the Ansel plug-in which pretty much does what I want but seems to be abandoned by the author. It does not work with Craft>3.1, as acknowledged by its author here.

Does anyone know of a third option for this?


texts: Develop a plugin for outputting data in a loop

texts:
I am looking to develop a plugin which out put the data in a loop Or that plugin would populate the array data with template tag. Could anyone please help me or share a doc link.

Thanks,


texts:
Is there a way to pre-populate the 'New Entry' form in the back end?

The context here is a calendar where you can click on a day and see a list of events and have a "New Event" button. The "New Event" button should ideally open the CMS backend and pre populate the event date (and some other fields).

We've chosen not to build a a whole new form because the events are quite complex, containing more than one matrix and assets, and it'll only be admins creating events (they don't need all the glitz).


texts: My Craft admin panel is running fine locally but when I login remotely my entries aren't there. Do I need to change something in the config file?


texts:
I have a form that consists of two dropdown boxes. These dropdowns contain values that relate to two sets of categories for one type of entry.

So when the search form is submitted there are two params that are passed, an interest and a destination.

The result I need, if I were to write it literally would be:

Select all the courses where INTEREST = [interest] AND DESTINATION = [destination]

Having a hard time figuring out how this is done in Craft.

Any help appreciated.


texts: Element API: Remove additional set of square brackets from JSON-String

texts:
We're currently having an Android-App access some of the entries of our Craft-based website. We are currently still using a self built API, and for easier creation of new API-Calls we are trying to migrate over to Pixel & Tonic's Element API plugin.

The entries (or the blocks of a Matrix-field of that entry, to be more precise) are accessed like so:

'api/alloverlist' => function() { // GET ALLOVER-CHALLENGES
        return [
            'elementType' => ElementType::Entry,
            'criteria' => [
                'section' => 'challenges',
                ],
            'paginate' => false,
            'first' => true,
            'transformer' => function(EntryModel $entry){

                $allOverChallenges = [];
                foreach ($entry->allOverChallenge as $challenge){
                    $allOverChallenges[] = [
                        'elementId' => $challenge->id,
                        'field_allOverChallenge_allOverName' => $challenge->allOverName,
                    ];
                }

                return [
                    $allOverChallenges
                ];
            },
        ];
    },

The returned JSON-String has the following appearance:

[
[
    {
        "elementId": "1298",
        "field_allOverChallenge_allOverName": "Dein schönster Sonnenaufgang"
    },
    {
        "elementId": "1310",
        "field_allOverChallenge_allOverName": "AllOverChallenge2"
    },
    {
        "elementId": "1318",
        "field_allOverChallenge_allOverName": "Allover Challenge 3"
    }
]
]

However, the Android-App accepts the JSON-String just with single square-brackets, like so:

[
   {
     "key":"value",
      ...
   },

   {
     "key":"value",
      ...
   }
]

For the sake of not having to change the existing Android-App, is it somehow possible to remove the additional square brackets?

Thanks.


texts: Running Craft Console Commands on Webfaction

texts:
I'm trying to run a few of Craft's console commands on a Webfaction server to automate running Craft migrations and resolving Project Config changes, and it's throwing an error.
Here's what I'm doing:
php craft migrate/all
php craft project-config/sync


texts: Pre-fill fields when creating an entry in CP

texts:
I am using redactor plugin for my field type and I want to use global values of the same field type to be used as pre-fill value when creating a new entry.

Use case:

Each year there is an edition of a program with more or less the same text (multiple fields), but minor adjustments can occur.

So by creating a new edition (entry) in the control panel, I want to already pre-fill the standard values of the fields (configured as a global)
Then I can update, if necessary, some text for this new edition and save it.

Thanks a lot!


texts: Is there any way to create twig extension without a plugin?

texts: I want to create custom twig extension without any plugin dependency. Is anyone has solution for this?


texts: Redirecting "if entry is not defined" returns 404 instead

texts:
All the documentation, and answers here say this should work... But it returns the 404 instead of redirecting and I can't figure out why?

Section: Structure = help
Entry URL Format: Top-Level Entries =
help/{slug}
Entry URL Format: Nested Entries = help/{slug}
Entry 'sTemplate = help/_entry

Top line of the "help/_entry.html" template contains

{% if entry is not defined %}
    {% redirect "/help/welcome-to-help" 301 %}
{% endif %}

where "welcome-to-help" is an Entry slug in the Help Section.

If I hit "example.com/help/welcome-to-help/" (or any other valid Slug), everything works fine. But if I hit "example.com/help/asdf/" it returns the 404 instead of redirecting.

Am at a loss at this point??


texts: Checking if a field contains information

texts:
I have read docs on Craft CMS site and Googled some related articles but can't seem to get my head around checking for conditions for a field.

For example, if I have a 'Fruit' field drop-down:
Apple
Banana
Orange

Should I add a 4th value with 'null'? So in my template, I want to display the field if it is Apple, Banana or Orange but not if null.

I get confused when to to use '|length'  or 'is empty' or 'is not' conditionals.

In another example, I tried to setup a drop-down for a field called 'Rating'
The values were 1, 2, 3, 4, 5
I couldn't get the conditional to work, so I thought to make the field a number type. And then I tried a conditional 'rating > 0' but also didn't succeed.


texts: Is it possible to use useEmailAsUsername and see User Relations Fields display as First Name + Last Name?

texts:
We have a site where we want to use email addresses as the username.

The site also has a lot of related user content and the administrators on the site know many of the site members by name.

Currently, Craft User Relations Fields display the email address of each user.  This gets pretty confusing quick as recognizable names become long strings of letters and numbers after you relate them.  In some cases, we find ourselves triggering the User Relations modal just to figure out who is related to the Entry we are looking at.

We require Users to submit First Name and Last Name values so we can ensure that each user has that value. Is there any way to define what values we see for the User Relations Fields?


texts: FeedMe - Import to multi language sites, linking entries

texts:
How does one use FeedMe to import content to a multi language setup? I can have one feed with all languages, or a feed for each language, but I cannot see how to set the locale of the import content, nor then how to link them as tranlsations of the same entry.

The documentation here does not seem to include info about it:
https://docs.craftcms.com/feed-me/v4/

There is a small paragraph about Target Site, but I do not have that option on my multi-site install, and it does not detail how to link entries together.

Thanks


texts: PSR-0 Composer Autoloading causing class not found in plugin

texts:
I have composer setup at the root of the plugin folder with a few dependencies. I have custom classes in a folder at root we can call pluginX, I am autoloading its namespace with composer like such.

{
  "autoload":{
    "psr-0": {"PluginX": "PluginX/"}
  },
  "require": {
    "andrefelipe/orchestrate-php": "0.14.0"
  }
}

however when I try and use my class which resides at "PluginX/Models/Trips" like below I get a "Fatal Error: Class Not found..."

<?php
namespace Craft;

use \GoWander\Models\Trips;
use \andrefelipe\Orchestrate;
use \GuzzleHttp\Client as GuzzleClient;

class PluginX_TripController extends BaseController {

    protected $allowAnonymous = false;

    public function actionIndex() {

        // let's instantiate a Http client programatically
        $clientConfig = Orchestrate\default_http_config();
        $httpClient = new GuzzleClient($clientConfig);

        // instatiate the collection
        $trips = new Trips($httpClient);

        $trip = $trips->item('ING');

Any thoughts?


texts:
I've had trouble getting animated GIFs to transform properly on my Craft site.

I've installed Imagick on my server, and set $imageDriver to imagick explicitly. This seems to have allowed some GIFs to transform but not others. I've tried GIFs I've made myself in Photoshop, and GIFs found online, with completely mixed results. No rhyme or reason to it at all as far as I can tell.

Examples:

A GIF that resized correctly: http://craft.kingzog.com/img/_thumbnail/OH-TEE.gif

And one that didn't: http://craft.kingzog.com/img/_thumbnail/tennis_gif.gif

(I'm not allowed to post too many links, but of course you can remove /_thumbnail from the URLs to view the original, still-animated GIFs).

I'm stumped. Anyone have any knowledge about file formatting, config or anything else that might help?


texts: Swapping Hogan for other JavaScript template engine in the SearchPlus plugin

texts: For a JavaScript novice like myself, what steps would be involved in swapping out the hogan.js templating framework for something else? I have my eye on Swig, which comes with some 'twig-like' filters I need to utilize when outputting my search results.


texts: Is it possible to compress image transforms?

texts: I'm using image transforms to create 1x versions of hdpi 2x images but one area I get slammed on web page performance is loading these images. Is it possible to compress them and if so, how?


texts:
I am new to Craft 3 and never set up a local environment with composer, bitbucket and gulp. So I dived into all these things to get my hands on Craft 3. At the moment I am using a shared hosting without a ssh access so I have to deploy my site by using FTP Upload. Is it correct that I just need to upload the entire Craft folder with all its subcategories (/vendors, /config, /modules etc. etc.) after development to the production server and then just to adapt the .env file?

I am a little bit curious about this, since it is recommended not to upload some of the sensitive folders with access to a repo. I know that this due to the fact that nobody should see your logins public. This does not apply for the production server? If I point my subdomain to the /web folder with its index.php on the production server everything should be fine? Just want to be sure.


texts: Is there any way to replace the asset programatically?

texts:
In the CP, when we upload an image with a same name, craft will ask if we wanna keep both or replace.
So in plugin, is there any way to do the replace?


texts: How, in a plugin, can I check that a User's "Favourite Entries" field contains a specific Entry?

texts:
Users in my project have a Favourite Entries field. In my plugin I want to check whether a specific Entry is present in that field for that user. I'm passing the Entry ID to look for. I am not interested in getting the Entry itself - I just want to check to see if it's already in the Favourite Entries field or not.

I'd hoped that this would work:

if( $user->favouriteEntriesField->id($searchingForThisEntryId)->total() === 0 ) {
    ... doesn't contain the Entry yet ...
}

But it doesn't work ( Object of class Craft\ElementCriteriaModel could not be converted to string )

[edit]

A working solution is to loop through everything:

foreach ($user->favouriteEntriesField as $favouriteEntry) {
    MyPlugin::log("ID of loop iterations Favourite Entry: $favouriteEntry->id", LogLevel::Info);

    if($favouriteEntry->id === $searchingForThisEntryId) {
        craft()->userSession->setError(Craft::t('This document is already favourited.'));

        $this->documentFavourited = "yes";
    }
}


texts: contact form plugin conditional notification emails

texts:
I would like to be able to use case or if statements to include templates for the notification email, as overridden by the contact form extension plugin. However, no matter what I've tried, the first include is used. (in this case, an order form template, when sometime it should be the job application template or contact template).
example code:
% if submission.form == "Bestelformulier" %}
    {% include 'example template 1' %}
{% else %}
    {% include 'example template 2' %}
{% endif %}

I have tried using "submission.formName" as well.
The setting to override the notification works fine, using this file, its just what happens in the file doesn't seem to line up and work.
Is there a way of doing this?


texts:
I'm building my Craft site locally, but need to make it live. When I go into Utilities -> Database Backup and try to create a backup, I get the error "There was a problem backing up your database. Please check the Craft logs."
I checked the log and see this:
  Could not create backup: The shell command "mysqldump --defaults-extra-file="C:\wamp64\www\craft\storage\runtime\temp\my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --default-character-set=utf8 --set-charset --triggers --single-transaction --no-data --result-file="C:\wamp64\www\craft\storage\backups/build-your-firm_200624_180437_9nnsavzxmh_v3.4.24.sql" stw && mysqldump --defaults-extra-file="C:\wamp64\www\craft\storage\runtime\temp\my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --default-character-set=utf8 --set-charset --triggers --no-create-info --ignore-table=stw.stw_assetindexdata --ignore-table=stw.stw_assettransformindex --ignore-table=stw.stw_sessions --ignore-table=stw.stw_templatecaches --ignore-table=stw.stw_templatecachequeries --ignore-table=stw.stw_templatecacheelements --ignore-table=stw.stw_cache --ignore-table=stw.stw_templatecachecriteria stw >> "C:\wamp64\www\craft\storage\backups/build-your-firm_200624_180437_9nnsavzxmh_v3.4.24.sql"" failed with exit code 1. in C:\wamp64\www\craft\vendor\craftcms\cms\src\controllers\UtilitiesController.php:340

I don't really know how to resolve that. Can I get around this by making a database backup in PhpMyAdmin?Is there any difference?
Thanks in advance.


texts:
I'm creating a monthly archive page (for a specified year) for a section.

Standard code to output the months and entries as follows:

{% set entriesInYear = craft.entries.section('blog').limit(null).after(year).before(year+1) %}

{% for month, entries in entriesInYear | group("postDate|date('F')") %}

{{ month }}

            {% for entry in entries %}

{{ entry.getLink() }}

            {% endfor %}

{% endfor %}

That's all working perfectly, what I can't figure out is how to reverse the order of the output, so I get January -> December, instead of December -> January.

I'm sure this is simpler than my head is making out, but that will teach me to be coding on a Sunday.


texts: Can you use Craft to build a relational web app database in a Knapp or Caspio style?

texts:
I guess the answer is probably "No" but I have read this "relate anything to anything" feature here http://buildwithcraft.com/features/relations and I was wondering how powerful is that.

I want to create an Events website

In my project users should be able to:

Enter records via a form (Events)
Change their own records
Choose an event and say they attend it (subscribe)
Enter or choose how the travel to that event (by car, bus, plane)
To rate and add a comment to those events.

The Events should show for instance how many people attend to that event, who are those people and how they travel there.

Ideally users should be able to sell their own even tickets but that will need some custom developing for implementation.

I could reach that kind of functionality with an SaaS database online solution like knapp or Caspio, create their a relational database and embed their database views in a CMS like Craft but I would prefer to use just Craft for the whole project.

Would be that possible to build all that in Craft?


texts:
I created a Profile structure for my client's employees. He asked if I could generate an email signature for them from their Profile. I figured out a way to put all the signatures on one page using a

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

loop on a single page.

However, is there a way to give each person their own page for an email signature? /PROFILE/email-signature that pulls content from the profile. I want this to update dynamically as he adds/removes employees.

How would I create a secondary template for the profiles for an email-signature?


texts:
As per the flow diagram below I want to restrict access for users outside my network. However rather then completely stopping external access I want them to be redirected to a login page where they will be required to login via google, there email address will have to be within the organisation to be granted access.

Any help/advice much appreciated.


texts: Unable able to update Freeform Pro from 2.2 to 2.5

texts:
I continue to get this error each time I try to update Freefrom.
I don't was to alter the table structure since data exists.


texts:
Is it possible to set the postDate for a new (disabled) entry created using the GuestEntries plugin?

Otherwise when posting a GuestEntry the postDate is not set until the entry is enabled or re-saved from Craft.

Posting this with an answer as it may be useful to other people. If there are better ways to do this please add them.


texts: Show Category Title only where an entry has been included in an Entries field

texts:
I have a Category Group with an Entries field assigned so the admin can select which existing Entries should fall within a given category.  An Entry can be assigned to multiple categories.

On the Entry page I want to be able to loop through the categories and only list those where the entry has been included.

There are six categories vs 20 or 30 entries so doing it the other way (assigning a category to the entry) would be cumbersome for end user editing if a new category is added.

I hope that makes sense?


texts:
Typical scenario: users log in on the front-end and have a profile page where they can update their info, including changing their current password.

I have referenced this article from 2014 but it's not working for me; maybe it's outdated by now?

Is it possible to change a user's password in the front-end?

From that article I get:

User needs to be logged in
User needs to submit their current password (input name="password")
User needs to add a new password (input name="newPassword")

I've done all of this in my code and it does not work. For simplicity's sake, I've even copied and pasted the code from the link posted above but it does not work. I've created a fake user called "Mister Test" with a password of "purple"; if I try to change the password on the front end to something like "test123", it does not redirect to my success url and does not change the password.

I don't know what else to do. Not much coming up in google searches. My original code is below:

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="/">
    {# redirecting to homepage just for testing #}
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    {{ "Current password"|t }}
    <input type="password" name="password" id="currentPassword">

    {{ "New password"|t }}
    <input type="password" name="newPassword" id="newPassword">

    <button class="btn" type="submit">{{ "Save"|t }}</button>
</form>


texts: Is "Replace file" a potential security hole?

texts:
I am new to Craft, but have a lot of experience with other CMS systems.

I have a very specific question about Assets.  I have an intern who has been given access to a Craft site; for a particular Asset Source, the intern has "View source" and "Upload files" privileges, but he does not have "Create subfolders" and "Remove files" privileges.  But even though the intern cannot remove a file when logged in, he can still replace it with another.  This seems to be a huge security issue.

I have tried everything to get around this issue, including configuring the image field to "Restrict uploads to a single folder."  The problem here again is that I cannot restrict the intern to his folders only; he can see all the Asset folders and can replace any file -- either through malice or incompetence.

Denying the right to upload files for the intern is not going to work either because I do need him to be uploading files for the entries he is creating.

Any help would be appreciated here as this is a real show-stopper.

Cheers!


texts: Synching content and template files across environments

texts:
I'm new to CraftCMS and have a few basic questions about synching contents between local and remote development environments. This has been discussed in other posts by I'm looking for more specific answers.

Traditionally, in the old CMS we use, we do all content changes in the remote dB. And then each team member imports the remote dB and updates their local dB (similar to what is described here). However,  during the dB export, we need to update all the entries to reflect the local URLs. How does this work with Craft? do dB entries need to be updated to reflect the new URLs? And is there a widely used plugin for this step?

Reviewing a Craft migration plugin, it mentions that one has to follow a migration dependency order, and that one has to break migrations into smaller steps to prevent issues, instead of one large migration. Is this the general practice for Craft? Is there no other way to have a single large migration (contents, settings, fields, etc.) happening at once?

Thank you so much.


texts:
I have a site that requires the client to reorder their entries in each 'category' manually. Obviously structures are perfect for this but where I'm running into trouble is that the entries need to appear in multiple 'categories'.

Eg. Project One needs to appear in /projects and /selected-projects, both of which need the ability to be reordered via drag and drop functionality.

As far as I know using Craft's categories isn't an option as they can't be reordered so I'm trying to set this up with one channel that contains the entries and then using multiple structures and using the entries field so the client can add the entries they create in the channel to the structure.

Long story short, is it possible to display channels within structures?


texts:
Please refer to this thread for information leading up to this problem.

I am having problems with mass file uploads, the files will upload in my CP for craft, and be present on the assets list, however when I come to post the entry, only one image will show on my live page.

Here is my code:

{% extends "_layout/_layout" %}

{% set bodyClass = "photos" %}

{% block metaTitle %}{{ entry.title }} Photo Gallery{% endblock %}
{% block metaDescription %}{{ entry.metaDescription }}{% endblock %}

    {% block content %}

{{ entry.title }}

        {{ entry.body }}

            {% set photos = entry.photos %}
            {% if photos | length %}
            {% for photo in photos %}

                                {% set image = photo.uploadPhoto.first() %}

            {% endfor %}
            {% endif %}

        {% set prev = entry.getPrev({'section' : entry.section.handle}) %}
        {% set next = entry.getNext({'section' : entry.section.handle}) %}
        {% if prev %}&laquo; {{ prev }}{% endif %}
        {% if next %}{{ next }} &raquo;{% endif %}

        Photographer credits.

    {% endblock %}

Any help with rectifying this code would be absolutely wholeheartedly appreciated!

Thank you!


texts: Get a related entries author in a plugin

texts:
Very new to plugin stuff and taking baby steps so forgive me if this is obvious.

I have a simple notification service set up to send an email to the author of an entry (front end submitted) when it is saved.

This simply sends the email to $entry->author

The entry that gets submitted also has a related entry field and I'd like to send the author of that entry an email as well, but I'm not sure how I'd get access to them? Any pointers?


texts: Search Between 2 Dates Venti Calendar Plugin

texts:
I am using the Venti Events Calendar Plugin. I was wondering how I could go about searching for events between 2 dates.

I can display events between 2 dates below, using the .between parameter. But I have not figured out how to incorporate this into a search.

{% set events = craft.venti.events.between('2016-04-01 00:00:00','2016-05-19 00:00:00') %}


texts:
So I have been using this CSS Tricks responsive video trick for years. The problem I'm having is that this new Craft site I built imported data over from EE into a single Redactor field.

Is there any way to run s conditional check that if there is a YouTube video embedded that would wrap a div around said content?

I'm probably asking too much but Craft has been amazing for the past few years I've using it. I fear the only way to do this would be to run an elaborate MYSQL commands to wrap that content in a div (or use JS to wrap each iframe) but I would love to be proven wrong!


texts: Issues with compiled_templates - call to undefined method

texts:
We have two web servers in a load-balanced setup. Both servers are sharing a single database. The craft and public folders are rsync-ed between the two so changes on those folders in web1 propagate into web2.

We tried loading a video atom using the following twig:

{% case "video" %}
{{ atom.video(block) }}

It works on our local dev copy and on our staging server at AWS, however on our live site we get this error:

I tried copying the whole runtime folder from AWS over to the live web servers but that did not fix it.

Any ideas on how to get it to work? I would consider myself a novice to Craft so pardon me if there's something obvious that I'm missing.

Thanks in advance.

Update:

Already figured out that it was an error with the upload. Some macros were not properly copied over into live.


texts: When should I build upon existing models in my own plugins?

texts:
In the Craft Models documentation example the model extends the BaseModel class. However in the example Events plugin source code the Events_EventModel extends the BaseElementModel.

While poking around in PHPStorm I also noticed other "base model" classes such as:

BaseComponentModel
BaseElementModel
BaseEntryRevisionModel

I also wondered if it makes sense to extend non-base models such as the EntryModel (if you're modeling entry data for example).


texts:
I want to use one template on several Craft websites (different installations, not multi-sites). Is there a way in Craft I can do something like this? I want to update/overwrite the /templates/core/ directory when I implement new features/elements in the template but on the other hand, I want to have the option, to overwrite single template-files without losing the changes with the next update.

A directory structure could look like this:

templates/core/layout.twig
templates/core/home.twig
template/custom/home.twig

Thank you!

UPDATE:

One possible way would be this:

templates/core/home.twig

{% include ['custom/home.twig', 'core/base/home.twig'] %}

templates/core/base/home.twig

Welcome!

templates/custom/home.twig

Willkommen!

Problem: For this approach, I would always need to create one file, which just calls this include. As I want to split down the template in a lot of small files, to have the option to overwrite the templates on a very low level, this would cause in maybe hundred extra files.

Is there anyway to do something like this:

templates/core/home.twig

{% includeOr 'custom/home.twig' %}
   Welcome!
{% endIncludeOr%}

templates/custom/home.twig

Willkommen!


texts: 'devMode' enabled on the frontend yet its set to false

texts:
I have recently migrated a website to the live server.

In the craft/config/general.php my 'devMode' is set to false.

In the backend of the website I am not seeing the yellow and black banner to say its in dev mode but on the frontend each meta title is starting with [devmode].

Regards,

Reece


texts: Get last change timestamp in header response

texts:
I'll be polling an endpoint created with the element-api plugin which will trigger a concourse build. I need to include a timestamp the last time any entry was changed.

So I need something to go in the setHeader function:

HeaderHelper::setHeader([...])

Many thanks in advance!


texts: Craft Equivelent of EE addon CE Image Bulk Tag?

texts:
I'm preparing to migrate an old ExpressionEngine site to Craft and there are channels with images that are being resized by wrapping the rich text editor with ce image bulk tag like this:

{exp:ce_img:bulk attributes="class='img-responsive'"}
 {brand_copy}
{/exp:ce_img:bulk}

Is there an easy way to accomplish the same thing in Craft.. apply bulk transforms to images in a  rich text editor?

Need this for legacy content that will be moved in with feedme, new content will have a matrix set up using a different entry type.


texts: How I can sort my entry that belong to 3 section on date?

texts:
{% set blog = craft.entries.section('blog').all() %}
{% set news = craft.entries.section('news').all() %}
{% set caseStudies = craft.entries.section('caseStudies').all() %}
{% set allEntries = blog|merge(news)|merge(caseStudies) %}
{% for entry in allEntries %}
 <span>
       {{entry.nameSection}} | {{entry.dateNews|date("F  d, Y")}}
</span>
<h3 class="title post-title">
      {{entry.title}}
</h3>
{% endfor %}


texts:
Trying to ajax add to cart but each submit returns a

https://www.website.com/commerce/cart/updateCart 404 (Not Found)

I have this in my twig template:

{% for book in craft.products().type('books').limit(8).all() %}

    {% for image in book.productImages.limit(1).all() %}

            {% set variant = book.defaultVariant %}
            <form method="POST" class="add-to-cart">
                {{ csrfInput() }}
                <input type="hidden" name="purchasableId" value="{{ variant.id }}">
                <input type="number" name="qty" value="1">
                <button type="submit"></button>
            </form>

    {% endfor %}

{{ book.title }}

    {{ book.defaultVariant.price|currency }}

{% endfor %}

And this as my javascript:

$('.add-to-cart').on('submit', function(e) {
    console.log('add to cart clicked');
    e.preventDefault();
    var form_data = $(this).serializeArray();
    console.log(form_data);
    $.ajax({
        type: 'post',
        url: 'commerce/cart/updateCart',
        data: form_data,
        success: function(response) {
            if (response.success) {
                console.log('success');
                console.log(response.success);
                $(this).hide();
                $(this).siblings('.success').show();
                $(this).parents('.hover-cart').fadeOut();
            }
            else {
                console.log('error');
                console.log(response.success);
                alert("We're sorry, but the item couldn't be added to your cart. Please try again. If the issue persists, please send an email to webmaster@lwf.org");
            }
        }
    });
});


texts: Set site locale to display correct date format in date/time field

texts:
The date field is displaying dates in US format (mm/dd/yyyy) but I need the UK (dd/mm/yyyy) format. According to the docs:

  Dates and times are both formatted for the user’s preferred locale. They are displayed in the site’s timezone, however they get stored in UTC like all other dates in Craft.

How does one set this? The timezone is set correctly in the site config.


texts: Custom environment variable to main assets folder

texts:
I have a multilingual website which has a folder structure such as:

craft
assets
  js
  css
nl
fr

My goal is to link to the assets folder for my js en css files, but as I'm running a multilingual site I have set my config file to:

return array(
    'omitScriptNameInUrls' => true,

    'siteUrl' => array(
        'nl' => 'http://krycer.be/nl/',
        'fr' => 'http://krycer.be/fr/',
    ),
);

Which means that my {{ siteUrl }} is set to krycer.be/nl or krycer.be/fr
But my assets folder is one level higher.
I tried adding this code to the config.php:

'environmentVariables' => array(
    'baseUrl'  => 'http://krycer.be/',
),

and accessing it by using

{{ baseUrl }} or {{ craft.config.environmentVariables.baseUrl }}

But nothing seems to work. How can I create an abolute link to my assets folder?


texts:
I am having trouble setting up image volumes correctly in Hyperlane.
My best guess is that is has something to do with permissions but I have not been able to find a solution.
This is how I have set up the image volume like instructed in Hyperlane's documentation

However when I am uploading images it doesn't show in the templates, and when opening the url path I get a 404.
You can see a page where I have uploaded an image here https://dev-craft3-f59ef5d673d0.hyperlane.co/work/nausea and when I right-click and open the image in a new tab I get a 404 https://dev-craft3-f59ef5d673d0.hyperlane.co/uploads/images/work/nausea.jpg
The template to get the image looks like this
  {% set image = entry.featuredImage.one() %}
  {% if image %}
  <div class="image-box">
    <figure>
      <img
      src="{{ image.getUrl() }}"
      alt="{{ entry.title }}">
    </figure>
  </div>
  {% endif %}

…and the field is set up like this


texts:
Trying to template a matrix field that contains the use of categories. I am not a dev but trying to get this working.  This is my attempted but what I get back is something like this instead of the result.

  {{%content}}";s:12:"customFields";N;s:9:"inReverse";b:0;s:7:"asArray";b:0;s:2:"id";N;s:3:"uid";N;s:10:"fixedOrder";b:0;s:6:"status";a:1:{i:0;s:7:"enabled";}s:8:"archived";b:0;s:11:"dateCreated";N;s:11:"dateUpdate

Here is my code...

{% set entries = craft.entries.section('bizlist').limit(10) %}
  {% for entry in entries %}
{{ entry.title }}<br />
     {% for block in entry.cityList %}
{{ block.bizName }}
     {% endfor %}
  {% endfor %}


texts:
I'm trying to use a single "image" field across sections as well as categories. The intention is to keep fields to a minimum and at the same time I'm also trying to keep the assets folder neat and organised. This image field is part of a Matrix.
Ideally I would like the asset upload location to:

save with section.handle as path if section
save with services path if category
save with pages path if other

Here's what I have so far:
{% if section %}{owner.section.handle}/{owner.slug}{% elseif category is defined %}services/{owner.slug}{% else %}pages/{owner.slug}{% endif %}

Where am I going wrong?


texts:
I need to create a hierarchy that looks something to the effect of

parent 1

parent 1 child 1
parent 1 child 2
parent 1 child 3

parent 2

parent 2 child 1
parent 2 child 2
parent 2 child 3

and so on. My initial thinking was to use the matrix field type....a lot but, unfortunately, a matrix field can't have child fields of matrix field, and each child will need a matrix due to not knowing how many items each one could have as well as keeping them all together and allow for easy reordering.

The other requirement is that a "child" can't exist without a "parent", so I essentially only want to allow a user to create a "parent" at the root level and "child" types under each parent.

Is this even possible in Craft? If it is, could you point me in the direction of where it's documented as I can't seem to find anything that resembles what I'm trying to achieve.

Thank you in advance


texts:
i'm facing 404 errors for images related files in the control panel
like users photo, Login Page Logo, site Icon... etc...

for user photo for example i can edit the image, and i see it normally, but it is not visible on the my account page when craft try to reach
http://domaine.org/craft/cpresources/102e2477/thumb-100x100.jpg?v=1524146432

cpresources rights are 755

any help welcome :)


texts: How to display success message using the Contact Form plugin

texts:
Kind of feel silly having to ask this but I cannot for the life of me get a success message to display after the redirect when the Contact Form submits.

I just am not sure how to call it in the template view.

I have tried various things like this:

{% set success = craft.config.get('successFlashMessage', 'contactform') %}

{% if success %}

{{ success }}

{% endif %}

But just cannot seem to grab it.

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


texts:
I have links on a partial within my templates, but it seems to be trying to load a template when it should just be loading the outbound href of the  tag. I don't have a clue why this would be happening?

  {% if user.userWebsite %}

  {% endif %}

Will link out to mysite.com/profile/pinterest.com/username when really it should be going to pinterest.com/username

Any ideas to why?


texts:
This is my first template that im working on in craft cms3, i've managed to make the most of the homepage and other tabs of website dynamic using the CMS, but I can't figure out how do I make tags and categories dynamic on the homepage and sidebars of all the related pages.

The bottom of homepage which I want to make dynamic

The sidebar of the page that I want to make dynamic

if you want to have a look at the website im working on heres the server link http://52.65.202.173/

Will be really grateful for the help, thanks!


texts:
We have many country websites on different continents. In the CP we group the sites, where the group has the name of the continent.

Now we want to group the sites in the templates in the same way.

I have this, but it is not giving back the group.

{% set allSites = craft.app.sites.getAllSites() %}
{% set allGroups = allSites|group('allSites.group') %}

{% for group, countriesInGroup in allGroups %}
    {{ group }}

    {% for country in countriesInGroup %}
        {{country.language}}

    {% endfor %}
{% endfor %}

Hope somebody can point me in the right direction.

Thanks!


texts:
Has anyone successfully run craft on an HHVM server?  I tried it using Forge, I got a page loading, but no admin and no subpages.

According to the HHVM Frameworks page, it has 99.7 percent compatibility with yii and 100% compatible with twig? I guess that last 0.3% is a doozy.

I'd love to hear if anyone else had had more success with it?


texts: How to show if a user is logged in to control panel

texts: Is there a way to show if a user is currently logged in to the control panel? As I need a way to see if the client is working in the CMS.


texts:
/admin/utils/serverinfo and /admin/utils/phpinfo are both showing empty pages. There aren't any errors appearing in any logs.

In case it's related, the same site won't allow .jpg images to be uploaded. The progress bar reaches 100% but then it remains stuck.

Running Craft Pro 2.5.2755.

UPDATE

Running devMode true revealed the following error:
Parse error: syntax error, unexpected '[' in /nfs/c10/h03/mnt/175833/domains/example.com/craft/app/controllers/UtilsController.php on line 292


texts: Help with admin panel errors. Fresh install. Mysql version issue?

texts:
I get this on the admin panel:
CDbException

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #18 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'craftcms.structureelements.root' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by. The SQL statement executed was: SELECT elements.id, elements.type, elements.enabled, elements.archived, elements.dateCreated, elements.dateUpdated,
.....

There's a long trail in the apache error log. here's a snippet.
2017/04/27 04:46:46 [trace] [system.db.CDbConnection] Opening DB connection
in /var/www/craft/app/etc/behaviors/AppBehavior.php (871)

Env details:
Ubuntu 1.04 (fresh digital ocean vps)
php - PHP 7.0.15-0ubuntu0.16.04.4 (cli) ( NTS )
mysql - 5.7.17-0ubuntu0.16.04.2


texts: |replace filter is matching too many characters

texts:
I'm looking to format out image tags from a string using the |replace filter. The behavior I'm looking for is to give it a string like this:

some text

and get back:

some text

Unfortunately, when I use {{ snippet|replace('//', '') }} it matches the entire string, from the opening  rather than matching both  tags individually. How can I force the regex to match only through the first > it finds before continuing?


texts:
Is there any configuration hint for enabling memcache in Craft 3? I'm on 3-beta-24

I added

'cacheMethod' => 'memcache',

to config/general.php, but this did neither cause any hits on memcache nor any error.

The Craft 2 (sic!) docs say you also need config/memcache.php, which I created

returning an empty array
returning an array containing the properties I found in *app/vendor/craftcms/cms/src/config/MemCacheConfig.php:
returning a 2 dimensional array with the the first array containing the properties from 2. above

Nothing worked, but 2. & 3. throw unknown property exceptions.

This is my memcache.php (according to variant 3. above):

return [
    [        // A memcached server hostname or IP address.
        'host' => 'localhost',
        // Whether or not to use a persistent connection.
        'persistent' => true,
        // The memcached server port.
        'port' => 11211,
        // How often a failed server will be retried (in seconds).
        'retryInterval' => 15,
        // If the server should be flagged as online upon a failure.
        'status' => true,
        // The value in seconds which will be used for connecting to the server.
        'timeout' => 15,
        // Probability of using this server among all servers.
        'weight' => 1,
    ]
];

This is the exception:

Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: craft\config\MemCacheConfig::0
 in .../app/vendor/yiisoft/yii2/base/Object.php at line 161

looks like the config can't handle multiple memcache servers as array.

Here's the stacktrace: https://pastebin.ca/3855627


texts: How can I add "and" between multiple categories assigned to an entry?

texts: I have some entries that have more than one category assigned to them (under the same category group).  For example, Entry X might be assigned to Category A and Category D.   How do I get it to print "Category A **and** Category B" instead of Category A Category B"?


texts:
is there a simple way to exclude an 'include' for specific pages?

For instance I have an include {% include "_globals/_footer" %} but I don't want it to appear on my contact and 404 pages.
How would I exclude it?

Thank you!


texts: How can I write a PHP script to zip and download an Assets subfolder?

texts: I've searched everywhere but can't seem to get a straight answer.  I want to write a php script to zip and download an entire subfolder in my assets directory.  The subfolders are named based on a variable.  Where do I write this php code?  Must I write a custom plugin for something so simple?


texts: Is it Possible to Assign Permissions Within a Content Structure

texts: I'd like to be able to assign permissions to content or sections of content within a structure. For example, if I have a structure modeled around an organization and there are several departments within that organization, maybe marketing and sales, I'd like to be able to create groups that can create/edit content within a specific department. Is it possible, using a plugin or by some other means, to restrict access to a specific area within a larger structure?


texts: What's the correct syntax for recipients in Sprout Email?

texts:
I've got a form creating an entry in a Bookings channel which contains two fields, an Entries field (eventBooking) and a Users field (userBooking).

I'm trying to get Sprout Email to send an email to the user selected in userBooking. Can anyone help me with the correct syntax please?

I've tried the following which don't seem to work:

{{ userBooking.first().email }}
{{ object.userBooking.first().email }}
{{ entry.userBooking.first().email }}
{ object.userBooking.first().email }


texts: How would you template for Infinite Scroll?

texts:
I want to integrate Waypoints JS's Infinite Scroll instead of using traditional pagination.  I think the Straight Up Craft site uses this approach on its blog.

How might you template the following HTML to work with CraftCMS?  I know how to limit or not limit the number of entries, but how do you template to load each successive group of (say) 12 entries as you reach a waypoint - that is the "infinite-more-link"?

...

More


texts: How do I add custom styles/plugins to the rich text editor in Craft?

texts: I'm aware that I can customise which buttons is available in the rich text editor. But how can I add custom css styles, either as classes or as inline styles? Do I need to create a plugin for this? If so, how do I add plugins? And, can I change which options are available in the formatting drop down?


texts: Craft 3 - How do you programatically update a field type that is a Category?

texts:
I have a Category element, locations, which I am trying to update programatically through a Craft 3 plugin that reads data from a CSV.

The locations category has a Field Layout: latitude (Number), longitude (Number), nearbyLocations (Categories).

I am having trouble updating a locations' nearbyLocations field. I am inserting an array of Categories into the nearbyLocations field on the setFieldValues() call.

A TypeError gets thrown deep in the bowels of Craft:

  craft\helpers\StringHelper::toLowerCase() must be of the type string,
  array given, called in
  /home/vagrant/code/vendor/craftcms/cms/src/helpers/Db.php on line 448

Below is my code:

$new_nearby_locations is an array of Category elements.

$new_nearby_locations = [];
foreach ($nearby_locations_slugs_from_csv as $nearby_location_slug) {
  $nearby_location = Category::find()
                    ->slug($nearby_location_slug)
                    ->one();

  if (!is_null($nearby_location)) {
      array_push($new_$nearby_locations, $nearby_location);
  }
}

Update $category's field values.

$category = Category::find()->slug($slug)->one();
$category->setFieldValues([
    'latitude' => $new_latitude, // previously defined
    'longitude' => $new_longitude, // previously defined
    'nearbyLocations' => $new_nearby_locations
]);

Save the changes

 Craft::$app->elements->saveElement($category);

I am suspicious that updating nearbyLocations by inserting an array of Category elements is wrong. If so, what is the right format?

Or am I doing something else wrong.

Thanks in advance!


texts:
Could my sudden bad requests on form submissions be linked to defaultCookieDomain
and multi site use with separate add on domain?

We added defaultCookieDomain as live preview wasn't working - didnt fix it by the way - but our add on domin is obviously the same. Can we just leave it blank?


texts: Use postDate in section title format field

texts:
I'm trying to generate titles for a section's entries based off of the given post date (if it exists). Here's the configuration I've got in the Title Format field for this section's entry types:

New Arrivals for {% if postDate %}{{ postDate|date('M j, Y') }}{% else %}{{ now|date('M j, Y') }}{% endif %}

I expect that, upon saving each new entry, Craft would build a title based off of the post date. Unfortunately, it always builds off of the current date - even with a more straightforward title format configuration:

New Arrivals for {{ postDate|date('M j, Y') }}

I understand that the user doesn't have to fill out the post date fields, but it appears that Craft creates a post date for every entry (and even does so before it writes the date created field to the database).

With that in mind, why wouldn't the above title format configurations work? Am I missing something? Any and all help is appreciated.


texts:
I have just started using craft today and I have hit a bit of a bump with Images.
I created and asset for Work and set it up to point to assets/images/work/ I was able to upload the image but when I tried to preview the 'Work' page the image was going to /work/assets/images/work relative URL I am guessing.
I tried then to define and environment variable like this:

'environmentVariables' => array(
  'baseAssetUrl'  => 'http://192.168.99.100:8080/',
  'baseAssetPath' => './',
),

Updated my asset group to the following:
{baseAssetPath}assets/images/work/
{baseAssetUrl}assets/images/work/

But when I try preview the page the image is broken and the variable has not been interpreted

<img src="{baseAssetUrl}assets/images/work/_360xAUTO_crop_center-center/test.jpg" alt="Test">

And I can't upload the image I get the following error message:

Upload failed for test.jpg. The error message was: “Error uploading
the file: The file system path “{baseAssetPath}assets/images/work/”
set for this source does not exist.”

Any ideas what am I missing?


texts: Super table field in the element index table page (defineTableAttributes)

texts:
I've built a Custom Element called Contact and I've defined almost all the functions it needs including Contact::defineTableAttributes().
My question is two folds:

How can I have my plugin install itself with a ready-made custom Field Layouts and their associated Fields.
How can I display a SuperTable field, that includes multiple Email fields, in my Element's index page. Displaying the First Email field from the SuperTable is fine.

E.g.:
    protected static function defineTableAttributes(): array
    {
        return [
            'title' => ['label' => Craft::t('app', 'Title')],
            'type' => ['label' => Craft::t('app', 'Type')],
            'slug' => ['label' => Craft::t('app', 'Slug')],
            'postDate' => ['label' => Craft::t('app', 'Post Date')],
            'expiryDate' => ['label' => Craft::t('app', 'Expiry Date')],
            // SuperTableHandle.Field
            'emails.email' => ['label' => 'Email'],
        ];
    }


texts: Pagination with if statement date modify

texts:
How can I incorporate the date_modify into the craft.entries query so that the pagination takes into account this criteria? At the moment the limit is also accounting for past entries and I'm hitting errors whatever I try.

{% paginate craft.entries.section('events').limit(10).order('date asc') as entries %}

    {% for entry in entries if entry.date > now|date_modify('-1 day')  %}

        ...

    {% endfor %}

    {% include "includes/_pagination" %}


texts: Prevent change field in user profile edit

texts:
Is there a way to prevent the current user from changing fields in his profile? Currently i've attached a customfield "company" to the user object. I only want the site admin to set this field once and the only one allowed to change this. Where can I inject/override/overload the behavior of the saveUser method? Or is there a way to allow a different validation function or to disable a certain customfield during edit/save?

Thanks in advance....


texts: Update User "Field Type" for Entry in Plugin

texts:
I have a channel called "Groups", with a users field type called members for the entries. I need to be able to add/remove users to the members entry field via plugin.

What I've tried is:

// criteria
$criteria = craft()->elements->getCriteria(ElementType::Entry);

// filter
$criteria->slug     = 'groupNameHere';

// section
$criteria->section('groups');

// get entry
$entries = $criteria->find();

foreach($enries as $entry)
{
    // get current members of group
    $members = $entry['members'];

    // add new user model to $members
    $members[] = craft()->users->getUserByUsernameOrEmail("newUserEmailHere");

    // update field with new $members array
    $entry->getContent()->setAttribute('members', $members);

    // save
    craft()->entries->saveEntry($entry);
}

This simply clears the previous members value for the group, without even adding the new user. I can't find anything online about updating this type of field-type via plugin so I'm just guessing how to do this. Does anyone know the right way to do this?

Any information would hugely help! Thanks!