我有一张表格如下:
items
-id (pk) AI
-user_id (fk) references users
-title
-description
我有一个需要经过身份验证的用户的表单页面。我想用属于用户的项填充选择框(例如select * from user_id = loggedinUserId)
我查看了文档,发现了这个:
$builder->add('items', 'entity', array(
'class' => 'AcmeHelloBundle:Items',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('i')
->orderBy('i.title', 'ASC');
},
));
我的问题是如何在symfony 2.1表单中将经过身份验证的用户ID传递给此查询?
答案 0 :(得分:4)
@Patt提供的解决方案似乎是理想的,但在我的情况下,此表单仅使用一次或仅在一页中使用。所以我更喜欢这样做:
class ItemType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$user=$options['user'];
$builder->add('itemOffered', 'entity', array(
'class' => 'TestBundle:Items',
'query_builder' => function(EntityRepository $er) use ($user) {
return $er->createQueryBuilder('i')
->where('i.user =:user')
->setParameter('user', $user);
}
));
}
}
在控制器中:
$form = $this->createForm(new ItemType(), new Item(),array('user' => $this->getUser()));
答案 1 :(得分:1)
您有两种可能性:
这个awesome thread向您展示了一种有趣的方式(来自@khepin)。但是,正如@Bernhard所建议的那样(见第一条评论),在这种情况下有一种更简单的方法。
方法1-构造函数注入:如果你不能打扰创建一个suscriber等...你可以直接将安全上下文注入到表单构造函数中:
的ItemType:
namespace Acme\HelloBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\User\UserInterface;
classItemType extends AbstractType
{
/**
* @var string
*/
private $class;
/**
* @var UserInterface
*/
private $user;
/**
* @param string $class
*/
public function __construct($class, SecurityContextInterface $securityContext)
{
$this->class = $class;
$this->user = $securityContext->getRequest->getUser();
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$username = $this->user->getUsername();
$builder->add('items', 'entity', array(
'class' => $this->class,
'multiple' => true,
'expanded' => true,
'query_builder' => function(EntityRepository $er) use ($username) {
$query = $er->createQueryBuilder('i')
->select(array('i'))
->leftJoin('i.users', 'u')
->andWhere('u.username = :username')
->setParameter('username', $usename)
->orderBy('i.title', 'ASC');
return $query;
},
)
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => $this->class,
));
}
public function getName()
{
return 'acme_hello_item';
}
}
将其声明为服务:
<parameters>
<parameter key="acme_hello.item.class">Acme\HelloBundle\Entity\Item</parameter>
</parameters>
<services>
<service id="merk_notification.filter.form.type" class="Acme\HelloBundle\Form\Type\ItemType">
<tag name="form.type" alias="acme_hello_item" />
<argument>%acme_hello.item.class%</argument>
<argument type="service" id="security.context" />
</service>
</services>
要构建表单,您现在可以:
$formBuilder = $this->container->get('form.factory');
$form = $formBuilder->createNamed('acme_hello_item', 'acme_hello_item');