我正在尝试使用表单中查询字符串给出的一些数据。我在互联网上搜索了一个很好的解释(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' => 'Symfony\Component\HttpFoundation\Request'
));
}
我找到了使用请求范围的另一种方式:
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'));
});
}
我对代码有一些疑问:
答案 0 :(得分:1)
我建议使用第二种方法,但不是注入Request对象,而应根据this post注入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'));
});
}
...
}