Symfony 2:表单实体字段在每个单选输入上添加“data-*”属性

问题描述 投票:0回答:3

我有一个带有“实体”类型字段的表单,显示单选字段:

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

我想在每个输入中添加“数据价格”:

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

我该怎么做?

html forms symfony
3个回答
7
投票

如果您使用的是 symfony >= 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)];
    },
));

0
投票

<input type= "radio" name="membership" value="1">
<input type= "radio" name="membership" value="2">
<input type= "radio" name="membership" value="3"> 


-1
投票

认为您正在寻找这个:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.