Cms: Eager loading and Live Preview

Created on 23 Jan 2018  路  9Comments  路  Source: craftcms/cms

Description

Live preview does not seem to work when I "Eager load" a matrix field.

{% set blocks = entry.grid.with([
    ['image:image', {
        withTransforms: ['background']
    }]
]).all() %}

Additional info

  • Craft version: Craft Personal 3.0.0-RC6
  • PHP version: 7.1.6
  • Database driver & version: MySQL 5.6.35
  • Plugins & versions:

Most helpful comment

Workaround !

{% set preview = craft.app.request.isLivePreview %}

{% if preview %}
    {% set blocks = entry.grid.all() %}
{% else %}
    {% set blocks = entry.grid.with([
        ['image:image', {
            withTransforms: ['background']
        }]
    ]).all() %}
{% endif %}

All 9 comments

Workaround !

{% set preview = craft.app.request.isLivePreview %}

{% if preview %}
    {% set blocks = entry.grid.all() %}
{% else %}
    {% set blocks = entry.grid.with([
        ['image:image', {
            withTransforms: ['background']
        }]
    ]).all() %}
{% endif %}

@brandonkelly This wasn't fixed, was it?

It is expected behavior, per the Eager-Loading docs:

However when the assets _are_ eager-loaded, entry.assetsField gets overwritten with an array of the eager-loaded assets. So one(), all(), and other element query methods are not available. Instead you must stick to the standard array syntaxes.

(Example uses assets, but the behavior applies to all element types.)

I know about the [0] vs .one() difference, but why does eager loading break live preview?

Sorry, was on a different train of thought I guess 馃檭

Live Preview will preload each of your field values based on the POST data, but eager-loading will override those values with the eager-loaded values. So as @H-i-red鈥檚 workaround demonstrates, if it鈥檚 a Live Preview request you should just avoid eager-loading anything.

Wow. Is there any way to generally disable eager-loading during Live Preview, or should there be??

Problem is, if the template is telling Craft to eager-load elements, then the template should also have adjusted following code to treat those field values like arrays (as they will be if they've been eager-loaded. So we can't just disable eager-loading for LP requests, as that will likely cause other errors further down the template.

Ok, and I had thought of @H-i-red 's solution before seeing it, which will do what you know I'm interested in, and will have to be standard practice anyway.

Thanks, @brandonkelly

There should be a warning in the Eager Loading docs with instruction how to best write the conditional to avoid code duplication.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

leigeber picture leigeber  路  3Comments

angrybrad picture angrybrad  路  3Comments

angrybrad picture angrybrad  路  3Comments

davist11 picture davist11  路  3Comments

rynpsc picture rynpsc  路  3Comments