简体   繁体   中英

Customize 'choice_label' of EntityType Field for Twig

I have the following form:

$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()));

I have 2 Problems with that:

  1. I can not customize the 'choice_label' like:

     'choice_label' => function ($user) { return ($user->getId() + " " + $user->getUsername()); } 
  2. There is not Linebreak after each choice (or after each Radio button), which gets pretty ugly with the alot of users.

How can I customize the 'choice_label' s ?

How can I get a Linebreak after each Radio button ?

You can customise this to string method however you want and then remove the 'choice_label' attribute in form builder

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

To customise labels you, I would use style sheets. You can add a class using attr or choice_attr for individual radio inputs based on their values .. For example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM