Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 createFormBuilder field name prefix without entity

Tags:

symfony

A form has been created in Symfony2 using createFormBuilder, it does not need an entity and is only used for searching. The name of the form and the input name need to be changed.

    $form = $this->createFormBuilder(null, array(
                'action' => $this->generateUrl('route'),
                'method' => 'GET',
        'csrf_protection' => false,
        'attr' => array('name' => 'search'),
            ))
            ->add('query', 'text', array(
                'required' => false,
            ))
            ->getForm();

The rendered HTML is as follows:

<form class="" method="GET" action="route" name="form">
<div class="errors"></div>
<div id="form" name="search">
<div>
<label for="form_query">Query</label>
<input id="form_query" type="text" value="king" name="form[query]">
</div>
</div>
<p>
</form>

How can the form name be changed? Currently it is form, which means the div id is also form, could it be changed to search?

Secondly the input should have a name as query not form[query]?

I have had a look at the docs about working with a form without an entity but I can not see how to change these properties.

The end result should be:

<form class="" method="GET" action="route" name="search">
<div class="errors"></div>
<div id="search">
<div>
<label for="search_query">Query</label>
<input id="search_query" type="text" value="king" name="query">
</div>
</div>
<p>
</form>
like image 674
lookbadgers Avatar asked Mar 18 '23 17:03

lookbadgers


1 Answers

You should call createNamedBuilder. It allows you to set custom form name in the first argument.

Example:

    // public function createNamedBuilder($name, $type = 'form', $data = null, array $options = array())
    $form = $this->get('form.factory')->createNamedBuilder('', 'form', array(), array(
        'action' => $this->generateUrl('route'),
        'method' => 'GET',
        'csrf_protection' => false,
        'attr' => array('name' => 'search'),
    ))->add('query', 'text', array(
        'required' => false,
    ))->getForm();

For more useful methods, please see: \Symfony\Component\Form\FormFactory

like image 143
Dmitrii Korotovskii Avatar answered Mar 24 '23 17:03

Dmitrii Korotovskii