babzich
babzich

Reputation: 163

Symfony2 populate choice list from api data

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

Upvotes: 2

Views: 3993

Answers (1)

Mun Mun Das
Mun Mun Das

Reputation: 15002

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(),
    //....
));

Upvotes: 13

Related Questions