将查询字符串数据传递给表单

时间:2014-08-14 22:21:59

标签: symfony symfony-forms symfony-2.5

我正在尝试使用表单中查询字符串给出的一些数据。我在互联网上搜索了一个很好的解释(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'));
        });
    }

我对代码有一些疑问:

  1. 实施此类事情的“更好”方式是什么? 总的来说,我可以总结一下,第一种方法需要访问控制器来传递请求对象,第二种方法需要请求范围。
  2. 我是否想念另一个好方法?

1 个答案:

答案 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'));
        });
    }

    ...
}