7

I have a form as below:

class AdminEmployerForm extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('firstName', 'text')
            ->add('user', new AdminUserForm());
    }
}


class AdminUserForm extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('username', 'text')
            ->add('email', 'text');
    }
}

I am calling AdminEmployerForm in controller and I want to remove email field of AdminUserForm from AdminEmployerForm:

$form = $this->createForm(new AdminEmployerForm, $employer);
//i want to do something like $form->remove('email')

how can i do use $form->remove() to remove field in embedded form? Is it possible to remove a field of embedded form from controller?

sonam
  • 3,720
  • 12
  • 45
  • 66

1 Answers1

17

You'll have to get the embedded form type to remove a field from it.

$form = $this->createForm(new AdminEmployerForm, $employer);

// Get the embedded form...
$adminUserForm = $form->get('user');

// ... remove its email field.
$adminUserForm->remove('email');

Not sure of your exact use-case, but you may consider leveraging form events as it may be more ideal than handling this in the controller.

  • 1
    Minor thing that I'm sure you would figure out quickly, but you have to remove the field before `$form->handleRequest($request)`. – bassplayer7 Apr 25 '15 at 15:53