1

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I thought about that but how should i create child objects if their parent is a service but they are not ?
I think you can pass all data what you want to form constructor in a options parameter :)
Maybe, but i have to pass it from form to form until i reached the form in which i need the session
So forget about a parent one. Just create the embeded form as a service and do it in that way :)
0

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()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.