Live preview does not seem to work when I "Eager load" a matrix field.
{% set blocks = entry.grid.with([
['image:image', {
withTransforms: ['background']
}]
]).all() %}
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.assetsFieldgets overwritten with an array of the eager-loaded assets. Soone(),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.
Most helpful comment
Workaround !