Symfony 2:表单实体字段添加"数据 - *"每个无线电输入的属性

时间:2016-03-30 15:42:21

标签: html forms symfony

我有一个带有" entity"类型字段的表单。显示无线电字段:

->add(
            'membership',
            'entity',
              array(
                'class' => 'Comiti\UserBundle\Entity\Membership',
                'expanded' => true,
                'multiple' => false,
                'label' => false,
                'empty_value' => 'Aucune adhésion',
                'query_builder' => function (MembershipRepository $er) {
                    return $er->createQueryBuilder('membership')
                        ->where('membership.club = :club')
                        ->setParameter('club', $this->authentication_service->getCurrentClub())
                        ->orderBy('membership.name', 'ASC')
                    ;
                }, 
            )
        )

我在我的视图中添加了无线电字段:

{{ form_row(form.membership) }}

在html中渲染类似的东西:



<input type= "radio" name="membership" value="1">
<input type= "radio" name="membership" value="2">
<input type= "radio" name="membership" value="3"> 
&#13;
&#13;
&#13;

我想添加&#34;数据价格&#34;每个输入:

&#13;
&#13;
<input type= "radio" name="membership" data-price="20" value="1">
<input type= "radio" name="membership" data-price="10" value="2">
<input type= "radio" name="membership" data-price="15" value="3"> 
&#13;
&#13;
&#13;

我该怎么做?

2 个答案:

答案 0 :(得分:4)

如果您使用的是symfony&gt; = 2.7,则可以使用“choice_attr”

http://symfony.com/doc/current/reference/forms/types/entity.html#choice-attr

$builder->add('attending', 'choice', array(
    'choices' => array(
        'Yes' => true,
        'No' => false,
        'Maybe' => null,
    ),
    'choices_as_values' => true,
    'choice_attr' => function($val, $key, $index) {
        // adds a class like attending_yes, attending_no, etc
        return ['class' => 'attending_'.strtolower($key)];
    },
));

答案 1 :(得分:-1)

认为你正在寻找这个:

form = $this->createFormBuilder($someObj)
        ->add('myInput', 'text', array(
             'attr' => array('myAttr' => 'myValue')
        )
        ->getForm();

docs在这里: http://symfony.com/doc/2.0/reference/forms/types/field.html