Bring back (deprecated) support for using the |length
filter on element queries
#11625
-
Since the 4.0 release, I'm seeing a lot of people getting tripped up by the fact that the Specifically, this has become a big gotcha because a) There is no exception thrown for it in Craft 4. In fact it appears to still work, as the filter now returns the character count for the query's b) There is no deprecation warning logged for it in Craft 3 Essentially, this silently breaks a lot of templates that are doing something similar to this: {% if entry.images|length %}
...
{% endif %} I get that I propose that either a) Support for using b) Support is not restored for Craft 4, but a deprecation warning is added for Craft 3. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 12 replies
-
There might be neater ways to do it, but one idea that seems to me like a pretty straight-forward solve is to add a custom public function lengthFilter(TwigEnvironment $env, $thing): int
{
if ($thing instanceof QueryInterface) {
Craft::$app->getDeprecator()->log('length-queries', 'Using the `|length` filter on queries has been deprecated. Use the query\'s `count()` method to fetch the number of results instead.');
return $thing->count();
}
return twig_length_filter($env, $thing);
} |
Beta Was this translation helpful? Give feedback.
-
Same idea occurred to me this morning as well 😄 Implemented for Craft 4.2, which we’ll release ASAP! f2ccc77 Also realized dropping element queries’ (And these are being brought back indefinitely, not as temporary deprecations.) |
Beta Was this translation helpful? Give feedback.
-
Ref: #11625 (comment) Following this discussion, it looks like Craft is going to un-deprecate using the |length filter on element queries. While that's good (I think?) it has thrown up a lot of discussion on Discord about "well you shouldn't have been doing that anyway as it's a heavy query". So while it's good that our sites won't break with the reversed change, it is making me wonder what the better way is to code these instances? I've been using |length fairly heavy-handidly on all sorts of things, and as there are no deprecation errors, and I'm not a PHP programmer, it's not clear when you should or shouldn't be using this. Is there anything in the docs that talks about this? |
Beta Was this translation helpful? Give feedback.
-
Craft 4.2.0 is out now with support for treating element queries as arrays 🎉 Craft 3.7.50 has also been released, dropping related deprecation warnings. |
Beta Was this translation helpful? Give feedback.
Craft 4.2.0 is out now with support for treating element queries as arrays 🎉
Craft 3.7.50 has also been released, dropping related deprecation warnings.