Tuesday, 23 April 2013

Getting "Must be a StateFieldPathExpression" Symfony2/Doctrine exception


I'm getting a weird error when making a DQL query in my Symfony2 project. The error contains the phrase "Must be a StateFieldPathExpression". This seems to happen with queries that try to select an identity field (or something with a foreign key.)


This may be a bit of a work around, but you can try using the IDENTITY() function in the DQL query to get the id. For instance, imagine that you wanted to select an external ID (un-creatively named 'extern_id'), among other (more un-creatively named) fields:

$dql = "
SELECT IDENTITY(s.extern_id) AS eid, 
  s.some_col AS sc,
  s.another  AS ac
FROM something s WHERE 1";


// ... etc ...


This was tested to work using up to Symfony 2.1.4-DEV.

This workaround seems to work for now. If there's anyone out there with more knowledge of Doctrine and DQL, here's a question for you: is using IDENTITY() the right way to go on a permanent basis?

Find the length of an array in Twig


How do I find the length of an array using Twig?


Use the length filter, for instance:

{% if my_array|length < 1 %}
  {# ... do default thing ... #}
{% else %}
  {# ... do something ... #}
{% endif %}

Or if you'd like to use a variable instead ...

{% set arr_size = my_array|length %}