如何在树枝

时间:2015-07-29 15:07:35

标签: symfony doctrine-orm twig

我是symfony2的新手,6周经验,我遇到了问题。 我必须在用户和事件之间使用ManyToMany关系以及其他属性,因此它们已成为2个关系(与中间实体的两个OneToMany关系)并且编码部分是正确的。 我有一个事件页面,显示事件详细信息(标题,日期等)按钮。这就是我的问题所在:

我想检查当前用户是否已订阅该活动并根据其显示两个不同的按钮:订阅/取消订阅

到目前为止,我能想到的最好的是这个树枝代码:

{% for user_event in event.user_event%}
        {% if  app.user.id == user_event.user.id %}
            Already subscribed! <button> Unsubscribe </button>
            {% else %}
                You are not subscribed! What are you waiting for!?
                <button> Subscribe </button>
            {% endif %}
{% endfor %}

上面的代码遍历中间表所在的行 特定事件,然后测试订阅该事件的所有用户,问题是除了当前用户之外,else条件将为真,这种方法将输出如下内容:

你没有订阅!你在等什么!? 已经订阅! 你没有订阅!你在等什么!? 你没有订阅!你在等什么!? 你没有订阅!你在等什么!? 你没有订阅!你在等什么!?

是不是有办法做这样的事情:(这可能不是正确的编码,但它澄清了我想做的事情)

{% if  event.user_event.user(app.user.id) %}
        Already subscribed! <button> Unsubscribe </button>
        {% else %}
            You are not subscribed! What are you waiting for!?
             <button> subscribe </button>
        {% endif %}

我尝试过:

{%if app.user.id == event.user_event.user.id %}

但它不起作用并给我这个错误:

方法&#34;用户&#34; for object&#34; Doctrine \ ORM \ PersistentCollection&#34;在OCUserBundle中不存在:事件:第35行的view_event.html.twig。

我错过了什么吗?帮助将不胜感激,如果你想检查我的实体告诉我。谢谢。

2 个答案:

答案 0 :(得分:0)

根据结果进行检查然后输出:

{% set subscribed = false %}
{% for user_event in event.user_event%}
    {% if  app.user.id == user_event.user.id %}
        {% set subscribed = true %}
    {% endif %}
{% endfor %}
{% if subscribed %}
    Already subscribed! <button> Unsubscribe </button>
{% else %}
    You are not subscribed! What are you waiting for!?
    <button> Subscribe </button>
{% endif %}

我认为更好的方法是生成查询以获取用户订阅的事件列表。为每个事件抓住每个用户似乎效率低下。

答案 1 :(得分:0)

解决。我最终得到了一个twig扩展函数,它返回true或false,如下所示:

<?php
namespace OC\UserBundle\Services\Twig\Extension;

class AzouzExtension extends \Twig_Extension
{
 protected $em;

 public function __construct($em)
 {
    $this->em = $em;
 }

 public function getFunctions()
 {
    return array(
        new \Twig_SimpleFunction('test_inscription', array($this, 'aa'))
    );
 }

 public function getName()
 {
    return 'test_inscription';
 }   

 public function aa($uid,$eid)
 {
    $qb=$this->em->createQueryBuilder();
    $qb->select('ue')
       ->from('OCUserBundle:InscritEvent', 'ue')
       ->where('ue.apprenant = :x and ue.evenement = :y' )
       ->setParameter('x', $uid)
       ->setParameter('y', $eid)
            ;
    $query=$qb->getQuery();

    if($query->getResult())
    {return true;}
    else {return false;}
  }
 }

并在树枝页面中:

{% if test_inscription(app.user.id,evenement.id)%}
you are already subscribed :)
{% else %}
</button><a href="#">Subscribe</a> </button>
{% endif %}

可能不是最好的方法,但它有效。