2015-11-28 75 views
1

什麼是設置鍵/值對(從MySQL獲得)的集合作爲控制器內的選擇字段「選擇」的最佳方式? 我想類似的東西:如何在Symfony2中設置選擇字段值?

$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); 

其中AddNews()形式如下:

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

回答

0

也許類似如下(假設Symfony的> = 2.7)。現場選項見docs

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 
      )); 
    } 
0

你可以從你的formType文件讓您的「新聞」直接使用你的資料庫,這樣的:

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() 
      )); 
    } 
相關問題