2011-08-23 56 views
9

我如何創建一個選擇列表與Symfony 2中的數據庫表中的值?Symfony 2表單與選擇列表

我有2個實體:學生課堂有多對一的關係,我需要創建與如下因素字段的表單:年齡教室(選擇列表從可用的類)。

在我學生表格我有

$builder 
     ->add('name') 
     ->add('surname') 
     ->add('age') 
     ->add('classroom', new ClassroomType()) 
    ; 

在我課堂形式我有這樣的:

$classrooms =$this->getDoctrine()->getRepository('UdoCatalogBundle:Classroom')->findAll(); 
    $builder 
     ->add('clasa','choice',array('choices' => array($classrooms->getId() => $classrooms->getName()))); 

我得到這個以下錯誤:

Fatal error: Call to undefined method Udo\CatalogBundle\Form\ClassroomType::getDoctrine() in /var/www/html/pos/src/Udo/CatalogBundle/Form/ClassroomType.php on line 13   

類問候, Cearnau Dan

+0

這裏的解釋:http://groups.google.com/group/symfony2/browse_thread/thread/ da8f72b33f9f93ba – tttony

回答

24

不知道你是否找到了答案,但我只需要做一些挖掘工作,找出我自己的項目。

表單類沒有設置爲使用Doctrine就像控制器一樣,因此您無法以同樣的方式引用實體。你想要做的是使用entity Field Type這是一個特殊的選擇字段類型,允許你加載一個Doctrine實體的選項,就像你正在做的那樣。

好吧這麼長的故事短。而不是做你在做什麼,以創建選擇字段,這樣做:

->add('category', 'entity', array(
    'class' => 'VendorWhateverBundle:Category', 
    'query_builder' => function($repository) { return $repository->createQueryBuilder('p')->orderBy('p.id', 'ASC'); }, 
    'property' => 'name', 
)) 

我不知道,如果你能放置query_builder功能到存儲庫還是什麼,我有種瘋狂地擺動,因爲我走。到目前爲止,我所鏈接的文檔在做什麼時都很清楚。我想下一步是在Doctrine's QueryBuilder上閱讀。

當你在裏面我想你想砸你在哪裏嵌入課堂形式的位,

->add('classroom', new ClassroomType()) 

你可能不希望人們創建自己的教室。除非你這樣做,那麼是的。

+0

是的,實體字段類型是我所需要的。 – ziiweb

+0

你剛剛爲我節省了很多時間,+1 –

0

如果實體映射,這是Symfony的2.8+一個乾淨的解決方案或3+

<?php 

namespace My\AppBundle\Form\Type; 

use My\AppBundle\Entity\Student; 
use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolver; 

class StudentType extends AbstractType 
{ 
    /** 
    * {@inheritdoc} 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('name') 
      ->add('surname') 
      ->add('age') 
      /* 
      * It will be resolved to EntityType, which acts depending on your doctrine configuration 
      */ 
      ->add('classroom'); 
    } 

    /** 
    * {@inheritdoc} 
    */ 
    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults(['data_class' => Student::class]); 
    } 
}