Can I change a Form Class action on build?

10,274

You get access to the same form builder in the buildForm method, so just calling the setAction on it will work:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->setAction($path);
}

The question is how you pass the $path to your form type. One of the ways would be to pass it as an option when creating the form. But if you're passing the $path anyway, why not just set the action itself?

$form = $this->createForm(new MyType(), $object, array(
    'action' => $this->generateUrl('my_action'),
));

Another way would be to inject the router to the form type and use it to generate the URL, but I don't think it's a good idea to make that kind of decisions in a form type.

Share:
10,274

Related videos on Youtube

Nelson Teixeira
Author by

Nelson Teixeira

Senior developer and technology enthusiast contact: [email protected]

Updated on June 04, 2022

Comments

  • Nelson Teixeira
    Nelson Teixeira almost 2 years

    On a form classe's buildForm method (AbstractType derived) can I set the action of that form? What I want to do is similar to the setAction method that I can use when building an embedded form:

    $form = $this->createFormBuilder()
      ->setAction($this->generateUrl('my_action'))
      ->add('field', 'text')
      ->add('button', 'submit');
    

    I mean, is the setAction an equivalent to form classes?

  • Nelson Teixeira
    Nelson Teixeira over 10 years
    I can't upvote yet, as my reputation still doesn't allow it. when it allows, I'll do it ok ?
  • Elnur Abdurrakhimov
    Elnur Abdurrakhimov over 10 years
    Sure, not a problem. It's not a requirement. Just a way to thank an answerer doubly. :)