Mr. B. Mr. B. - 2 months ago 13
PHP Question

Symfony: how to get a parameter from the route within a FormType?

I'm trying to access the parameter

page
from the current route within a
FormType
. It works in a
Controller
, but not in a
FormType
. I'd like to avoid passing the parameter like
/?page=1
and prefer
/page/1
.

routing.yml

my_route:
path: /data/page/{page}
defaults:
_controller: MyBundle:MyController:myAction


src/myBundle/Form/Type/MyFormType.php

class MyFormType extends AbstractType {
// ...
public function buildForm(FormBuilderInterface $builder, array $options) {
$request = Request::createFromGlobals();
$page = $request->query->get('page');
echo "page: $page"; // empty

// ...
}
}


I'd like to avoid to pass the parameter through the Controller to the FormType and prefer to access it directly within the FormType.

Any ideas?

Thanks in advance!

Answer

You need to inject the request stack service into form type to do that:

class MyFormType extends AbstractType 
{
    private $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    } 

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $request = $this->requestStack->getCurrentRequest();

        //do something: for example hide/show fields from request parameters  
    }
}

Register the form type and their dependencies:

services:
    app.form.type.myform:
        class: AppBundle\Form\Type\MyFormType
        arguments: ['@request_stack']
        tags:
           - { name: form.type }