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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用