2

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

2
  • 1
    Can you show what you actually tried? Commented Nov 9, 2012 at 18:35
  • I've just answered similar question here: stackoverflow.com/questions/13285281/… See the "UPDATE" section of the answer... Commented Nov 9, 2012 at 21:09

1 Answer 1

13

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(),
    //....
));
Sign up to request clarification or add additional context in comments.

3 Comments

+1 @m2mdas, this is great. Just a quick question. The ApiChoiceList will contain all the choices that will be used in the form. Is there anything to do in the entity to make sure the data suits the ApiChoiceList?
Might want to add the extra awesome choice list as service to your answer. :)
how to use this choice list in the twig view to display the value in the showAction?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.