Symfony2从API数据填充选择列表 [英] Symfony2 populate choice list from api data

查看:160
本文介绍了Symfony2从API数据填充选择列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从一个Api调用中填充选择列表。我尝试了几种方法,但没有成功。

我认为最好的方法是通过实现ChoiceListInterface。

有人已经完成了吗?



谢谢 /github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/ChoiceList/LazyChoiceList.php#L25\">LazyChoiceList 并实现loadChoiceList 方法,例如

  // ApiChoiceList.php 
名称空间Your \Namespace;
使用Symfony \Component\Form\Extension\Core\ChoiceList\LazyChoiceList;
使用Symfony \Component\Form\Extension\Core\ChoiceList\ChoiceList;
$ b $ class ApiChoiceList extends LazyChoiceList
{
protected function loadChoiceList()
{
//获取并处理api数据

返回新的ChoiceList($ options,$ labels);


$ b b

$ b然后在你的<$ c
$ b

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


I have to populate a choice list from an Api call. I have try several approach without success.

I think the best way is by implementing ChoiceListInterface.

Does someone has already done it ?

Thanks

解决方案

Extend LazyChoiceList and implement loadChoiceList method, e.g

//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);

    }
}

And then in your buildForm method of your form,

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

这篇关于Symfony2从API数据填充选择列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆