2012-03-22 72 views
1

所以,我要做到以下幾點:學說的DBAL在Symfony2中與形式

我在/Form/Type/UserType.php

創建的窗體類我有一個表的狀態列表(表名爲「狀態」)。

我想在下拉菜單中顯示所有這些狀態。

我應該在類UserType中使用哪些代碼來顯示所有狀態?

我想:

$request = new Request; 
    $conn = $request->get('database_connection'); 
    $states = $conn->fetchAll('SELECT state_code, state_name FROM states'); 

    $builder->add('state', 'choice', array(
     'choices' => $states, 
     'required' => false, 
    )); 

但給我一個錯誤。基本上,我想查詢表狀態中的所有狀態,並從所有這些狀態創建一個下拉菜單。

回答

0

您可以創建State實體,將其映射到states表並與User實體建立OneToMany關係。然後在您的UserType表格$builder->add('state')應自動創建下拉字段。您還必須將data_class選項設置爲您的User實體getDefaultOptions方法的UserType表單。

0

@ m2mdas給了你正確的基於對象的答案。但是,如果你真正想要做的就是存儲state_code,那麼你所擁有的將幾乎工作。你只需要獲得正確的連接。

class MyType extends extends AbstractType 
{ 
    public function __construct($em) { $this->em = $em; } 

    public function buildForm(FormBuilder $builder, array $options) 
    { 
     $conn = $this->em->getConnection(); 
     $statesx = $conn->fetchAll('SELECT state_code, state_name FROM states'); 

     // Need to index for the choice 
     $states = array(); 
     foreach($statesx as $state) 
     { 
      $states[$state['state_code']] = $state['state_name']; 
     } 

     $builder->add('state', 'choice', array(
      'choices' => $states, 
      'required' => false, 
     )); 

... 
// In your controller 
$form = new MyType($this->getDoctrine()->getEntityManager());