zm455 zm455 - 3 months ago 19
Twig Question

Twig: remove div around each checkbox fields of a form

Edit: see the solution I've found at the end of my question ;-)

I'm looking since hours for a solution but I do not really find what I'like. I'm sure it is easy to do.

I'm building a form with Symfony 3.1. My form does not send anything in a database. Everything seems okay. But when rendering my twig template all my checkbox are surrounded by a

<div>
html tag.

I just would like twig renders me a form without that
<div>
tag.
edit: this is what Twig render me: this is ok for me but I would like to remove div tags

<form name="form" method="post">
<div id="form"><div><label for="form_1">1</label><input type="checkbox" id="form_1" name="form[1]" class="ballsCheckBox" value="1" /></div>
</form>


Here is my twig template:

{% extends "::base.html.twig" %}

{% block title %}SimulotoBundle:Lotto:lotto{% endblock %}

{% block body %}
<h1>Welcome to the Lotto:result page</h1>
{{form(form)}}

{% endblock %}


I build the form directly in a controller. See it:
public function LottoSimulationFormAction()

{
$lt = new LottoSimulation();

$data = [];

$formBuilder = $this->createFormBuilder($data);

/** building Lotto grid with checkboxes * */
for ($i = 1; $i <= $lt->getMaxNb(); $i++)
{
$formBuilder->add($i, CheckboxType::class, [
'label' => $i,
'required' => false,
'attr' => [
'class' => 'ballsCheckBox'
]
]);
}

/** adding submit button **/
$formBuilder->add('Envoyer', SubmitType::class, [
'attr' => [
'class' => 'save'
]
]);

$form = $formBuilder->getForm();

return $this->render("SimulotoBundle:Lotto:lotto.html.twig", [
"form" => $form->createview()
]);
}
}

Answer

Here is the soluton to solve this problem.

I need to Customize the form rendering as it is explained in the Synfony cookBook on this page http://symfony.com/doc/current/form/form_customization.html

Go to vendor\Symfony\Bridge\Twig\Ressources\views\Form\form_div_layout.html and modify the block:

{%- block form_row -%}
    <div>
        {{- form_label(form) -}}
        {{- form_errors(form) -}}
        {{- form_widget(form) -}}
    </div>
{%- endblock form_row -%}

You can remove it but a better way is to copy/past that block to your teplate and overide it. Like this:

{% extends "::base.html.twig" %}

{% form_theme form _self %} //don't forget this line of code

{%- block form_row -%}
        {{- form_label(form) -}}
        {{- form_errors(form) -}}
        {{- form_widget(form) -}}
{%- endblock form_row -%}
Comments