Leto
Leto

Reputation: 2674

Access session from formType in Symfony2

I'm trying to get session data into my forms but i don't know how to do.

I could pass it to the constructor of my FormType but the FormType that actually use the session is nested 3 levels deeper in the main form. So i think that it is dirty to pass the session object in each constructor of each form type like this :

->add('name', new NestedFormType($this->session))

I also thought about using formsType as service. So i would have a parent for each of my formsType that should be injected with session.

But how can i do that without defininf all my forms as services ?

Futhermore, i can't access to the DIC inside of my FormTypes. So, it's ok for the creation of the first formType object (which is created in the controller which can access to DIC) but the nested FormTypes cannot be instianciated from their parent.

Is there a clean solution?

Upvotes: 1

Views: 3376

Answers (2)

dylan oliver
dylan oliver

Reputation: 1284

You don't need to define services for your higher level form types as long as you refer to the inner, injected form type by its alias:

NestedFormType service definition:

nested.form.type:
    class: Type\NestedFormType
    tags:
        - { name: form.type, alias: nested_form }
    arguments: [ @security.context ]

NestedFormType:

class NestedFormType extends AbstractType
{
    private $security_context;

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // do something with $this->security_context
    }

    public function getName()
    {
        return 'nested_form';
    }
}

ParentFormType:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('name', 'nested_form'); 
    // 'nested_form' matches service definition and NestedFormType::getName()
}

Upvotes: 0

Max Małecki
Max Małecki

Reputation: 1702

You need to define this parent form as a service and pass the session as the argument.

look at this question: Create a form as a service in Symfony2

Upvotes: 1

Related Questions