自定义' choice_label' Twig的EntityType字段

时间:2016-08-26 17:05:25

标签: php symfony twig symfony-forms

我有以下表格:

$form = $this->createFormBuilder()
->setMethod('POST')
->add('users', EntityType::class, array(
    'class' => 'AppBundle:User',
    'choices' => $users,
    'expanded' => true,
    'multiple' => false,
    'choice_label' => function ($user) {
            return $user->getUsername();
    }
))
->add('selected', SubmitType::class, array('label' => 'select'))
->getForm();

return $this->render('default/showUsers.html.twig', array('form' => $form->createView()));

我有两个问题:

  1. 我无法自定义'choice_label'

    'choice_label' => function ($user) {
            return ($user->getId() + " " + $user->getUsername());
    }
    
  2. 每次选择后(或每个单选按钮之后)都没有Linebreak,这会让很多用户感到非常难看。

  3. 如何自定义'choice_label'

    如何在每个单选按钮后获取Linebreak?

1 个答案:

答案 0 :(得分:1)

您可以根据需要自定义此字符串方法,然后删除表单构建器中的“choice_label”属性

//in user entity
public function __toString()
{
    $string =$this->getId(). ' ' . $this->getUsername();
    return $string;
}

要自定义标签,我会使用样式表。您可以使用attr或choice_attr为基于其值的单个无线电输入添加类。例如

->add('users', EntityType::class, array(
    'class' => 'AppBundle:User',
    'choices' => $users,
    'attr' => array('class' =>'type_label'),
    'choice_attr' => array(
        '0' => array('class' => 'class_one'),
        '1' => array('class' => 'class_two'),
    ),
    'expanded' => true,
    'multiple' => false,
))

See symfony reference for more information