symfony - 使用 FPNTagBundle 在查询中加载标记

标签 symfony tags symfony-2.1

Bundle 文档解释了如何加载简单对象的标记:

$this->tagManager->loadTagging($article);

但是我需要加载可标记资源及其标签的列表(来自学说查询的 ArrayCollection)。然后迭代 twig 中的集合并打印: 对象:tag1、tag2、tag..n

最佳答案

旧帖子,但希望这个答案会对某人有所帮助,因为我在尝试实现标记包时遇到了同样的问题。问题是您的实体将具有标签的私有(private)或 protected 属性,但从文档在包上读取的方式来看,该属性没有关联映射,并且它不是实际的字段(列)。因此,尝试访问 Tags 属性或在实体上使用 getTags 方法将不起作用,无论是在 Controller 还是在 Twig 中。我觉得 bundle 上的文档可能缺少标签属性上的一些映射注释,但我无法准确缩小它应该是什么。

我最终采用了其他人推荐的方法,即循环遍历 Controller 中的实体,并使用每个实体的标签管理器加载标签。我还做了一个很有帮助的事情,那就是向接受 ArrayCollection 的实体添加一个 setTags 方法,这样当循环遍历 Controller 中的实体时,您可以在每个实体上设置标签,然后在 twig 中访问它们,例如你想做的事。例如:

将此 setTags 方法添加到您的实体:

/**
 * @param ArrayCollection $tags
 * @return $this
 */
public function setTags(ArrayCollection $tags)
{
    $this->tags = $tags;

    return $this;
}

这将允许您从 Controller 设置标签属性。

然后在你的 Controller 中:

/**
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function indexAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $posts = $em->getRepository('ContentBundle:Post')->findAll();

    // here's the goods... loop thru each entity and set the tags
    foreach ($posts as $post) {
        $post->setTags($this->getTags($post));
    }

    // replace this example code with whatever you need
    return $this->render('AppBundle::index.html.twig',array(
        'posts' => $posts
    ));
}

/**
 * @param Post $post
 * @return \Doctrine\Common\Collections\ArrayCollection
 */
public function getTags(Post $post) {
    $tagManager = $this->get('fpn_tag.tag_manager');
    $tagManager->loadTagging($post);

    return $post->getTags();
}

此 Controller 中的 getTags 方法仅获取您的实体并使用标签管理器查找并返回其标签。您将在索引方法中看到将标签添加到每个实体的循环。

然后在 Twig 中,您可以访问循环中每个帖子上的标签:

{% for post in posts %}
  <h2>{{ post.title }}</h2>
  {% for tag in post.tags %}
    <a href="{{ url('tag_detail',{'slug':tag.slug}) }}">{{ tag.name }}</a> 
  {% endfor %}
{% endfor %}

关于symfony - 使用 FPNTagBundle 在查询中加载标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13030473/

相关文章:

html - 将元描述和开放图谱协议(protocol)描述合并到一个标签中

php - 在 Symfony2 中反序列化或解析 XML 响应

Symfony2 - 在具有不同关系的 Bundle 之间共享实体

forms - 带有抽象基类的 Doctrine 继承映射

symfony - 在 Symfony 2.1 抽象类型中访问当前用户

authentication - 如何修改当前用户的属性并在整个 session 中持久化它们

symfony-forms - 在 Symfony2.1 中手动更改或捕获无效 CSRF token 的消息

php - Symfony2 - 在事件之间传递数据

javascript - 正则表达式去除所有 html 标签,不包括 <br> & <a class ='user' ></a>

mercurial - Mercurial:分支与标签冲突