2

I have a twig template in my Symfony2 project. In the twig template, I have an entity object. This entity object is linked to another entity with oneToMany relation.

Example:

{{ submission }} -> Submission entity
{{ submission.histories }} -> Histories entity -> I have here an array collection of histories

The entity histories has a field "state_to"

My goal is to get only the histories object where the state_to is 4

I tryed like that:

{{ submission.histories('status_to', 4)[0] }}

But this is not working.

I know that I can use:

{% for history in submission.histories %}
    {% if history.statusTo == 4 %}
        {{ history.statusDate|date("d F Y") }}
    {% endif %}
{% endfor %}

But I am allmost sure that there is a nicer way.

2
  • 6
    Well instead of fetching all your entites from the database and trying to filter them in your template ... you should create a repository method to fetch ONLY the ones having history.statusTo = 4 and pass these to the template. Logic like this should not be included in a template. Commented Oct 29, 2013 at 13:39
  • Good idea @nifr, +1 for you. Commented Oct 29, 2013 at 13:42

2 Answers 2

6

Add a method getHistoryByStatus($status) in your entity to filter your histories based on the status_to field, then in your template:

{% set filtered_history = submission.historyByStatus(4)|default(false) %}
{% if filtered_history %}
    {{ filtered_history.statusDate|date("d F Y") }}
{% endif %}
Sign up to request clarification or add additional context in comments.

2 Comments

A method in the entity will still fetch all related histories ( as you will need to access $this->getHistories() inside this method which triggers doctrine to load the whole collection instead of only the related histories needed even with lazy loading enabled). Not a clean solution in this case. This belongs into a repository method to have the unneeded relations filtered out before getting the relations from database.
@nifr - that's no longer true. You can now use criteria to filter. Doing so will perform the filtering on the SQL level if the collection hasn't already been loaded.
2

you could just find the histories object where the state_to is 4 within a method called in your controller. then pass it to the view. This method can be inside your controller, but is better to have it in your history repository maybe? or a manager..

try avoiding complexity in the views.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.