【问题标题】:Symfony & Doctrine: Order Form Type By Choice LabelSymfony & Doctrine:按选择标签的订单类型
【发布时间】:2016-05-31 13:48:14
【问题描述】:

我在 Symfony 2.8 中有一个表单类型,它使用 choice_label 选项。这个值是一个函数,它对参数应用一些格式,目的是返回字段name,任何前导“The”字符串移到末尾(因此“The Company Inc”变成“Company Inc, The”。

choice_label 不是实体字段时,如何按FormType 排序?

// \Form\Type\AdvertiserType.php
...
->add(
    'advertiser',
    'entity',
    array(
        'class' => 'MyBundle:Advertiser',
        'label' => 'Advertiser Account',
        'choice_label' => 'formattedName',
        'query_builder' => function(EntityRepository $repo) {
            return $repo->createQueryBuilder('a')
                ->orderBy('a.name', 'ASC')
            ;
        }
    )
)
...

我不能在查询生成器中使用orderBy('a.formattedName', 'ASC'),因为这是一个函数名而不是实体字段。

广告商实体具有此附加功能:

// Entity\Advertiser.php
...
public function getFormattedName() {
    if (substr($this->name, 0, 4) == 'The ') {
        return substr($this->name, 4) . ', The';
    } else {
        return $this->name;
    }
}
...

感谢您的帮助或指点。

【问题讨论】:

    标签: php symfony doctrine-orm


    【解决方案1】:

    在仓库中实现排序功能

    public function getSortedList()
    {
        $entities = $this->findAll();
    
        usort($entities, function($a, $b) {
            return strcmp($a->getFormattedName(), $b->getFormattedName());
        });
    
        return $entities;
    }
    

    将其传递给控制器​​中的 FormType

    $form = $this->createForm(AdvertiserType::class, $advertiser, array('repository' => $this->getDoctrine()->getRepository('AppBundle:Advertiser')));
    

    然后将 query_builder 更改为选择

    // \Form\Type\AdvertiserType.php
    // before $builder->add
    $repo = $options['repository'];
    ...
    ->add(
        'advertiser',
        'entity',
        array(
            ...
            'choices' => $repo->getSortedList(),
            }
        )
    )
    ...
    
    // and in configureOptions(OptionsResolver $resolver) method
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Advertiser',
        'validation_groups' => array(),
        'repository' => null
    ));
    

    【讨论】:

    • 太好了。开箱即用,谢谢!!我只需要将 strcmp() 更改为 strnatcasecmp(str_replace("[", "0000000000", $a->getQueueName()), str_replace("[", "0000000000", $b->getQueueName())) 以确保首先排序数字,并且像 é 这样的 UTF8 字符在 e 中排序(而不是在末尾添加)。
    猜你喜欢
    • 2012-08-14
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    相关资源
    最近更新 更多