繁体   English   中英

Symfony和主义:订购表格类型(按选择标签)

[英]Symfony & Doctrine: Order Form Type By Choice Label

我在Symfony 2.8中有一个使用choice_label选项的表单类型。 此值是对参数应用某种格式的函数,目的是返回带有任何前导“ The”字符串的字段name (因此,“ 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;
    }
}
...

感谢您的帮助或指示。

在存储库中实现排序功能

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更改为options

// \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
));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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