Symfony2: sort / arrange form field of translated object?

I am trying to arrange the entity form field translated.

I am using the symfony translation tool, so I cannot order values ​​using an SQL statement. Is there a way to sort the values ​​after loading and translating?

Perhaps a form event is being used?

$builder
    ->add('country', 'entity', 
            array(
                'class' => 'MyBundle:Country',
                'translation_domain' => 'countries',
                'property' => 'name',
                'empty_value' => '---',
            )
        )
+3
source share
3 answers

EDIT

I found a solution to sort the values ​​of my field in my form type.

We must use the finishView () method, which is called when creating the form view:

<?php

namespace My\Namespace\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Bundle\FrameworkBundle\Translation\Translator;

class MyFormType extends AbstractType
{
    protected $translator;

    public function __construct(Translator $translator)
    {
        $this->translator = $translator;
    }

    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        // Order translated countries
        $collator = new \Collator($this->translator->getLocale());
        usort(
            $view->children['country']->vars['choices'], 
            function ($a, $b) use ($collator) {
                return $collator->compare(
                    $this->translator->trans($a->label, array(), 'countries'), 
                    $this->translator->trans($b->label, array(), 'countries')
                );
            }
        );
    }

    // ...

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('country', 'entity', 
                    array(
                        'class' => 'MyBundle:Country',
                        'translation_domain' => 'countries',
                        'property' => 'name',
                        'empty_value' => '---',
                    )
                )
        ;
    }

}

OLD ANSWER

I found a solution for my problem, I can sort them in my controller after creating the view:

$fview = $form->createView();
usort(
    $fview->children['country']->vars['choices'], 
    function($a, $b) use ($translator){
        return strcoll($translator->trans($a->label, array(), 'countries'), $translator->trans($b->label, array(), 'countries'));
    }
);

, ? , .

+9

, . PHP, Symfony Form Type, JavaScript .

0

, sort() SORT_STRING. , . : http://php.net/manual/fr/function.sort.php

0

All Articles