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