dongying3744 2017-03-14 17:47
浏览 38
已采纳

Symfony自定义表单选择值

I am using Symfony3 and I want to be able to display custom select values by combining two fields together such as name and city. So, in essence in the select box it would show this:

 ------------------------------------
 John Smith - Denver
 ------------------------------------
 Abe Lincoln - Washington D.C
 ------------------------------------
 George Washington - Washington D.C
 ------------------------------------
 etc...
 ------------------------------------

Here's my form...

$builder->add('person', EntityType::class, array(
            'required'=>false,
            'class'=>'AppBundle:Person',
            'choice_label'=>'name',
            'label'=>'Choose the person',
            'empty_data'=>null,
            'placeholder'=>"None",
            'query_builder' => function(EntityRepository $repository) {
                return $repository->createQueryBuilder('p');
            }
        ));
  • 写回答

1条回答 默认 最新

  • douna2014 2017-03-14 21:08
    关注

    As Symfony Doc says choice_label can be also a callable which gives you two options.

    1. Create a getter for composed value that should represent entity like:

      class Person {
          // ...
      
          public function getComposedName() {
              return $this->name . ' - ' . $this->city;
          }
      
      }
      

    And then in the form set choice_label to 'composedName'. Please note that it's composedName, and not getComposedName, because Symfony will use PropertyAccesor here, it will try also getting value with a getter getComposedName.

    This may be useful if you'll need this value in other places

    1. If you need this only in this particular form, then you can pass an anonymous function directly to the form:

      'choice_label'=> function($person) {
          return $person->getName(). ' - ' . $person->getCity();
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题