Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate absolute URL in custom form type?

Tags:

php

symfony

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.

like image 294
user3783550 Avatar asked Jun 27 '14 14:06

user3783550


Video Answer


2 Answers

There are two ways to do it:

  • Register your form type as service and inject the router in it: doc
  • 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.

like image 181
egeloen Avatar answered Nov 07 '22 01:11

egeloen


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

like image 24
Divi Avatar answered Nov 07 '22 00:11

Divi