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