你有两种可能:
- 通过构造函数注入参数(构造函数注入)
- 通过表单的选项注入参数
这个很棒的线程向您展示了一种有趣的方法(来自@khepin)。但是,正如@Bernhard 所建议的(见第一条评论),在这种情况下有一种更简单的方法。
方法 1- 构造函数注入:如果您不想创建订阅者等...您可以直接将安全上下文注入表单构造函数:
物品种类:
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');