Reputation: 14447
Here's what i'm trying to achieve. I'm using the SymfonyContrib\Bundle\LinkButtonBundle\LinkButtonBundle
to add a simple back/cancel link to my form right beside the submit button. Problem is that I don't know how to get to my router so that I can use the generate method to generate route url's. Anyone have an idea how to either inject the router into my form or pass the URL from my controller where the form is created with $this->createform('my_form_foo')
<?php
namespace My\Form;
use \Symfony\Component\Form\AbstractType;
use \Symfony\Component\Form\FormBuilderInterface;
class Foo extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'username',
null,
[
'label' => 'Username',
'attr' => [
'placeholder' => 'User name',
],
'required' => true
]
)
->add('actions', 'form_actions', [
'buttons' => [
'save' => [
'type' => 'submit'
],
'cancel' => [
'type' => 'button',
'options' => [
'url' => '/', // This needs to be generated from a route
'label' => 'Back'
]
],
]
]);
}
/**
* @return string
*/
public function getName()
{
return 'my_form_foo';
}
}
Upvotes: 1
Views: 745
Reputation: 39380
I suggest you to manage all the form actions in the Controller Class. As described in the doc here, you can add your button for flow-control:
$form = $this->createFormBuilder($task)
->add('name', 'text')
->add('save', 'submit')
->add('save_and_add', 'submit')
->getForm();
And manage the flow in the controller as:
if ($form->isValid()) {
// ... do something
// the save_and_add button was clicked
if ($form->get('save_and_add')->isClicked()) {
// probably redirect to the add page again
}
// redirect to the show page for the just submitted item
}
Hope this help
Upvotes: 0
Reputation: 3135
In your specific case, it's a better practice to add buttons directly in the view.
(Something like that)
{{ form_start(form) }}
{{ form_widget(form) }}
<button type="submit" value="Save" />
<a href="{{ path('name_route') }}" role="button">Back</a>
{{ form_end(form) }}
Upvotes: 1
Reputation: 707
You can inject the router into the form class if you register your form as a service in the service container.
Upvotes: 1