Question

How to access the data of a parent form in the subform?

For example there are products and categories. Product and Categories are many to many. If I want to edit all Products of a Category. The editable Data of each Product depends on the Category.

Is it possible to achieve this by using Symfony Forms?

Right now I can't see any possibility as the Product has no information about the current Category (since the relation is many to many).

Was it helpful?

Solution

I believe there is not a way to access the parent form data in any "clean" way.

However, it IS possible.

You will have to pass it as an option to the subform from the mainform.

Example:

Main form, how you will include subform:

$builder->add('sub',   new SubType(),   array('parent_data' => $builder->getData());

If your subtype is collection, it is a little bit different:

$builder->add('subs',   'collection',   array('type' => new SubType(),
                                          'options' => array('parent_data' => $builder->getData()))
    );

Add this to subform:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver
        ->setRequired(array('parent_data'));
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $parentData = $options['parent_data'];

    ... build subform

}

Please tell me if it works, I wrote it without testing, so we can fix any possible typos.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top