Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 change field options of an embedded form

Tags:

My question basically is, is it possible to change an option of a field of an embedded for from the parent form?

To illustrate the problem consider this; I have a parent form type class like this:

class FruitFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text')
            ->add('apple', new AppleFormType())
        ;
    }

and a child form type class that is in a separate bundle and I would prefer not to edit, like this:

class AppleFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text')
            ->add('qty', 'integer', array('label' => 'rubbish label')
        ;
    }

and I want to change the label of qty to something else, but I want to do this only in the FruitForm, not everywhere where the AppleForm is used. I had hoped to be able to do something like:

class FruitFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text')
            ->add('apple', new AppleFormType(), array('qty' => array('label' => 'better label')))
        ;
    }

or:

class FruitFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text')
            ->add('apple', new AppleFormType())
        ;

        $builder->get('apple')->get('qty')->setOption('label', 'better label');
    }

but neither of these (and a number of other attempts) have all failed me. There does not exist a setOption method that I can see.

Does anyone know of a way of doing this?

Thanks

like image 701
lopsided Avatar asked Jul 23 '12 16:07

lopsided


1 Answers

I also wanted to change options, the obvious "change the label" case for an existing field from the FOSUserBundle. I know I could do this in Twig or with translations.

@redbirdo pointed me in the right direction with "it appears that adding a field with the same name will replace it". Here's the solution:

$field = $builder->get('username');         // get the field
$options = $field->getOptions();            // get the options
$type = $field->getType()->getName();       // get the name of the type
$options['label'] = "Login Name";           // change the label
$builder->add('username', $type, $options); // replace the field
like image 199
Peter Wooster Avatar answered Oct 12 '22 23:10

Peter Wooster