Symfony2 populate choice list from api data

前端 未结 1 628
一个人的身影
一个人的身影 2021-01-07 03:29

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.

<
相关标签:
1条回答
  • 2021-01-07 03:58

    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(),
        //....
    ));
    
    0 讨论(0)
提交回复
热议问题