简体   繁体   中英

How to set choice field values in Symfony2?

Whats the best way to set a collection of key/values pairs (obtained from MySQL) as a choice field 'choices' inside a controller? I think about something similar to :

 $form = $this->createForm(new AddNews(), $news);
 $newsList = $this->getDoctrine()
             ->getRepository('BakaMainBundle:News')->getAllNews();

 $titlesList = ...($newsList); // some fuction that extract title=>id 
                               // array from news object collection

 $form->get('newsList')->setData($titlesList);

where the AddNews() form looks like :

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(...)
            ->add(...)
            ->add('accept' , 'submit')
            ->add('newsList', 'choice', array
            (
                'mapped' => false,
                'required' => true
            ));
    }

Perhaps something like below (assuming Symfony >= 2.7). See docs for field options:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(...)
            ->add(...)
            ->add('accept' , 'submit')
            ->add('newsList', 'entity', array
            (
                'class' => ''BakaMainBundle:News'',
                'choice_label' => 'title',
                'mapped' => false,
                'required' => true
            ));
    }

You could get your "news" directly from your formType file, using your repository, like that:

    private function getNews(){    
    $newsList = $this->getDoctrine()
                 ->getRepository('BakaMainBundle:News')->getAllNews();

     $titlesList = ...($newsList); // some fuction that extract title=>id 
                                   // array from news object collection
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(...)
            ->add(...)
            ->add('accept' , 'submit')
            ->add('newsList', 'choice', array
            (
                'mapped' => false,
                'required' => true,
                'choices' => $this->getNews()
            ));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM