我试图在我的表单中使用查询字符串给出的一些数据。我在网上搜索并找到了一个很好的解释(http://bicknoyle.com/2014/04/passing-query-string-params-form-symfony/):
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('refer', 'user_refer_type');
$builder->addEventListener(FormEvents::POST_SET_DATA, function(FormEvent $event) use ($options) {
if (isset($options['request'])) {
$form = $event->getForm();
$form->get('source')->setData($options['request']->query->get('source'));
}
});
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setOptional(array(
'request'
));
$resolver->setAllowedTypes(array(
'request' => 'SymfonyComponentHttpFoundationRequest'
));
}
我找到了使用请求作用域的另一种方法:
class RegistrationFormType extends BaseType
{
private $request = null;
public function __construct(Request $request)
{
$this->request = $request;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('refer', 'user_refer_type');
$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event)
{
$form = $event->getForm();
$form->get('refer')->setData($this->request->query->get('refer'));
});
}
我有一些关于代码的问题:
- 什么是"更好"的方式来实现这样的事情?
总的来说,我可以总结,第一种方法需要访问控制器来传递请求对象,第二种方法需要请求范围。 - 我错过了另一个好方法吗?
我建议使用第二种方法,但不是注入Request对象,而是根据这篇文章注入RequestStack服务。
下面是一些我通常怎么做的例子:
class CustomType extends AbstractType
{
/**
* @var RequestStack
*/
private $requestStack;
/**
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$currentRequest = $this->requestStack->getCurrentRequest();
...
$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) use ($currentRequest)
{
$form = $event->getForm();
$form->get('refer')->setData($currentRequest->query->get('refer'));
});
}
...
}