Symfony2的填充来自API的数据选择列表(Symfony2 populate choice l

2019-07-03 16:56发布

我必须从API调用填充选项列表。 我已经尝试没有成功的几个方法。

我认为最好的办法是通过实施ChoiceListInterface。

是否有人已经做了吗?

谢谢

Answer 1:

扩展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);

    }
}

然后在您的buildForm窗体的方法,

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


文章来源: Symfony2 populate choice list from api data