-->

How to use ChoiceList in Symfony 2.1?

2020-06-21 10:23发布

问题:

I have a file containing a list of the US states.
Alabama
Alaska
etc ..

In symfony 2.0 I used ChoiceListInterface.php to use it in my form. I simply wrote this :

<?php

namespace MyBundle\Form;

use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface;

class StateChoiceList implements ChoiceListInterface
{
    public function getChoices()
    {
        $lines = file('listes/us_states.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        // fill the array
        $arr = array();
        foreach ($lines as $line) {
            $arr[$line] = $line;
        }
        return $arr;

    }
}

But now there is 7 other functions to implement in ChoiceListInterface :

public function getValues();
public function getPreferredViews();
public function getRemainingViews();
public function getValuesForChoices(array $choices);
public function getIndicesForChoices(array $choices);
public function getIndicesForValues(array $values);

I have read the documentation http://api.symfony.com/2.1/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.html but in my case I find it unclear and I really don't understand how to implement them.

Someone could help ? Thanks a lot

回答1:

You can extend LazyChoiceList and implement loadChoiceList() method where you can return an new ChoiceList object filled with the values read from the file.