Symfony2从api数据填充选择列表

bab*_*ich 2 php forms symfony

我必须从Api调用填充选择列表.我尝试了几种没有成功的方法.

我认为最好的方法是实现ChoiceListInterface.

有人已经做过吗?

谢谢

Mun*_*Das 13

扩展LazyChoiceList并实现loadChoiceList方法,例如

//ApiChoiceList.php
namespace Your\Namespace;
use Symfony\Component\Form\Extension\Core\ChoiceList\LazyChoiceList;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;

class ApiChoiceList extends LazyChoiceList 
{
    protected function loadChoiceList()
    {
        //fetch and process api data

        return new ChoiceList($choices, $labels);

    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你buildForm的表单方法中,

$builder->add('fieldname', 'choice', array(
    'choice_list' => new Your\Namespace\ApiChoiceList(),
    //....
));
Run Code Online (Sandbox Code Playgroud)