Symfony 2 basic GET form generated URL Symfony 2 basic GET form generated URL symfony symfony

Symfony 2 basic GET form generated URL


To create your desired URL, you will have to set the form name by using createNamedBuilder which you'll just leave blank ''.To remove _token you need to set csrf_protection to false. Please look into csrf protection to make sure you know what could happen if it is turned off.

Changing your code to the following should give you the results you want.

$form = $this->get('form.factory')->createNamedBuilder('', 'form', $search, array(            'csrf_protection' => false,         ))->setMethod('GET')           ->add('q', 'text')           ->add('search', 'submit')           ->getForm();

This should produce a URL like:

search?q=red+apple&search=

Edit:

If you want to get rid of &search=, one way would be to change search from submit to button.

->add('search', 'button')

This will require javascript to submit your form.Here is simple example in jquery:

//This assumes one form and one button$(document).ready(function(){    $('button').click(function(){        $('form').submit();    });});

This will produce a URL like:

search?q=red+apple

To access GET vars you put something like this in your controller:

public function yourSearchAction(Request $request){    // your code ...    $form->handleRequest($request);    if ($form->isValid()) {        $getVars = $form->getData();        $q = $getVars['q'];        $page = $getVars['page'];        $billing = $em        //Do something    }    return //your code}

Just to clarify if you are adding page to your URL you will need to add it to your form:

->add('page', 'text') 


Old question but, for people who want to know, this does the job too (Symfony 2.8) :

<?php// src/AppBundle/Form/SearchType.phpnamespace AppBundle\Form;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\Form\Extension\Core\Type\TextType;use Symfony\Component\Form\Extension\Core\Type\SubmitType;use Symfony\Component\OptionsResolver\OptionsResolver;class SearchType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->setMethod('GET')            ->add('q', TextType::class)            ->add('submit', SubmitType::class))        ;    }    public function getBlockPrefix(){        return '';    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults([            'csrf_protection' => false,        ]);    }}

In your controller :

<?php//...use AppBundle\Form\SearchType;//...public function yourSearchAction(Request $request){    $form = $this->createForm(SearchType::class);    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $q = $form->get('q')->getData();        // ...    }    // ...}