1

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.

2 Answers 2

3

use

{{ form_widget(child, {'id':'asterisks-rating-' ~ loop.index }) }} 
Sign up to request clarification or add additional context in comments.

Comments

1

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 }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.