I have example custom form type:
namespace Acme\SimpleBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ExampleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->setAction(****-----GENERATE-ROUTE-ABSOLUTE-URL-HERE-----****)
->add('email', 'text')
->add('send', 'submit');
}
public function getName()
{
return 'example';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'error_bubbling' => true
));
}
}
How can I generate absolute URL (like http://example.com/admin/check_form) to my route?
$this->generateUrl()
doesn't work, becuse it's not a controller, and $this->get('router')->generate()
also doesn't work, I don't know why.
There are two ways to do it:
Pass your action as option when you create your form in your controller:
$form = $this->createForm(new FormType(), null, array('action' => $this->generateUrl('your_route', array(/* your route parameters */), true));
Note that you must pass true
as last argument in order to force the router to generate an absolute url (as you asked for for Symfony < 2.8). If you're using Symfony3, use UrlGeneratorInterface::ABSOLUTE_URL
instead of true as suggested by Emilie in the comments.
You have to declare your FormType as a service, and with the service container add the router (service id: router), then in your FormType :
$this->router->generate('your_route_name', [] /* params */, true /* absolute */);
Here the doc : http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With