簡體   English   中英

將Symfony Form中的id屬性設置為twig變量

[英]Set id attribute in Symfony Form to twig variable

我想在表單中的表行id中添加一個twig變量。

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

目前它沒有被解析為樹枝變量。 有沒有辦法在不使用Javascript或jQuery的情況下使用此設置將id設置為'asterisks-rating-'loop.index?

我嘗試'逃避'它:

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

但顯然這些解決方案都不起作用。

采用

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

最佳做法應該是:

  • 如果可以的話,添加表單集合而不是多個表單(例如,如果您的表單未單獨處理)。

  • 如果您的表單是單獨處理的,請在類型的getName()方法中添加動態ID,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM