我是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 %}上面的代码遍历中间表where特定事件的行,然后测试订阅该事件的所有用户,问题是除了当前用户外,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 %}但它不起作用,并给出了这个错误:
在OCUserBundle:Event:view_event.html.twig的第35行,对象"Doctrine\ORM\PersistentCollection“的方法"user”不存在。
我是不是遗漏了什么?感谢你的帮助,如果你想检查我的实体,请告诉我。谢谢。
发布于 2015-07-29 23:58:17
执行检查,然后根据结果进行输出:
{% 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 %}我认为更好的方法是生成一个查询来获取用户订阅的事件列表。抓住每个事件的每个用户似乎有点低效。
发布于 2015-07-30 17:43:11
解决了。我最终得到了一个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;}
}
}在twig page中:
{% if test_inscription(app.user.id,evenement.id)%}
you are already subscribed :)
{% else %}
</button><a href="#">Subscribe</a> </button>
{% endif %}这可能不是最好的方法,但它是有效的。
https://stackoverflow.com/questions/31704326
复制相似问题