Emaus Emaus - 9 days ago 6
Twig Question

Render custom formType option in twig template

I have this problem in Symfony 2.8: I can't render a custom variable with my query passed to form option.

See the below code what i have tried :

This is my controller:

$form = $this->createForm('AppBundle\Form\FooAdminType', $res, array('attr' => array('fooOnes' => $Choices)));
//when $choices is my dql query


This is my formType:

public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('bar', EntityType::class, array(
'class' => 'AppBundle:Foo',
'choices' => $options['attr']['FooOnes'],
'required' => true,
'property' => 'name',
'attr' => array(
'class' => 'col-lg-2 control-label text-center'
)
))


finally, my twig template

{% for foo in form.bar %}
{{ form_widget(foo) }}
{% endfor %}


...Without the
for
block, the form is rendered. With the
for
block, I have this error:


An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string") in form_div_layout.html.twig at line 277.


PS: I have defined the
public function __toString()
in the entity

Answer

Without testing your code, the way you have set it up right now, you will be rendering a select element. Therefore, it doesn't make any sense for you to be looping through it.

You will need to set the attribute expanded to true in order for you to be able to use the for loop. This way, you will be rendering either radio buttons or checkboxes, depending on the multiple value.

For checkboxes:

public function buildForm(FormBuilderInterface $builder, array $options) {      
$builder
            ->add('bar', EntityType::class, array(
                'class' => 'AppBundle:Foo',
                'choices' => $options['attr']['FooOnes'],
                'required' => true,
                'expanded' => true,
                'multiple' => true,
                'property' => 'name',
                'attr' => array(
                    'class' => 'col-lg-2 control-label text-center'
                )
            ))