N
N
nepster-web2014-10-28 17:45:59
symfony
nepster-web, 2014-10-28 17:45:59

What is the correct way to work with doctrine collections in symfony2?

I am implementing tags on the site and now I came across a problem (more precisely a question) that I would like to clarify.
There is a Post entity in which there is such a thing:

public function getTags()
    {
        return $this->tags ?: $this->tags = new ArrayCollection();
    }

That is, all the tags for the post fall into the collection.
Now I have a task to show tags on the site, for example like this:

Tags: Vasya, Friends, Family

Actually, you can get a collection, for example, in a controller like this:
foreach ($entity->getTags()->getValues() as $tag) {
            print_r($tag->getName());
        }

in the form of the same code will look like this:
<div class="news-tags">   
                {% if entity.tags.values %}
                    <span class="font-bold" >{{ 'news.post.tags'|trans({}, 'NewsBundle') }}:</span> 
                {% else %}
                    {{ 'news.post.no_tags'|trans({}, 'NewsBundle') }}
                {% endif %}
                <ul class="tags-list">
                    {% if entity.tags.values %}
                        {% for tag in entity.tags.values %}
                            <li><a href="{{ url('news_tag', {'tag':tag.name} )}}">{{ tag.name }}</a></li>
                        {% endfor %}
                    {% endif %}
                </ul>
            </div>

Now actually the main essence of my question, how and where to carry out any manipulations, well, in this case, with collections?
Well, for example, freeze or delete some tag and give all the rest. Or, as in the example, place commas everywhere except for the last element. That is, in yii, I would create 1 more method in the model that would put the data in order and return a regular array, which I would pass to the view through the controller. How to act here (in the symphony)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
neolink, 2014-10-28
@nepster-web

first of all it's better

public function __construct()
{
    $this->tags = new ArrayCollection();
}

Secondly
{% if entity.tags|length %}
   Теги есть!
{% endif %}

{% for tag in entity.tags %}
    {% if not loop.first %}, {%endif %}         
    {% tag.name %}
{% endfor %}

A
Alex, 2014-10-28
@shoomyst

It can be in the controller (bad), in the service (slightly better), in the entity (like in yii), in the twig (good)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question