简体   繁体   中英

Set id attribute in Symfony Form to twig variable

I want to add a twig variable to my table row id in a form.

{% for child in form %}               
    {{ form_widget(child, {'id':'asterisks-rating-loop.index' }) }} 
{% endfor %}

Currently it is not being parsed as a twig variable. Is there any way to set the id to 'asterisks-rating-'loop.index using this setup without the use of Javascript or jQuery?

I tried 'escaping' it with:

{{ form_widget(child, {'id':'asterisks-rating-{{loop.index}}' }) }}
{{ form_widget(child, {'id':'asterisks-rating-'{{loop.index}}'' }) }} 

But obviously none of these solutions work.

采用

{{ form_widget(child, {'id':'asterisks-rating-' ~ loop.index }) }} 

The best practice should be:

  • to add a form collection instead of several forms if you can (eg. if your forms are not processed individually).

  • to add your dynamic id in the type's getName() method if your forms are processed individually, example:

BobType.php

<?php

namespace Fuz\AppBundle\Form;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class BobType extends AbstractType
{

    protected $suffix;

    public function __construct($suffix)
    {
        $this->suffix = $suffix;
    }


    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
           ->add('whatever', 'text')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array (
                'data_class' => 'Fuz\AppBundle\Entity\BobData',
        ));
    }

    public function getName()
    {
        return 'BobType-' . $suffix;
    }

}

BobController.php

$formA = new BobType("hello"); // {{ formA.whatever.vars.id == BobType-hello-whatever }}
$formB = new BobType("world"); // {{ formB.whatever.vars.id == BobType-world-whatever }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM