2016-04-21 40 views
0

我一直在使用Symfony,我試圖找出創建表單的方法。 我需要使用基於MVC的解決方案。Symfony2 - 創建使用不同實體的表單

我的表單需要詢問不同實體的幾個信息,然後我需要處理在數據庫中提取它的信息。 數據庫不會成爲問題。

我只是想清楚如何使用不同類型的實體做一個窗體?

而我該如何製作一個實體的數據庫中包含的數據的滾動菜單?

+2

http://symfony.com/doc/current/reference/forms/types/entity.html您可以映射關聯作爲表單的一個領域,增加選擇,你會得到一個選擇素t元素包含相關實體的屬性(您選擇的)作爲值的選項。 – chalasr

回答

0

如果@chalasr的評論不適用,即實體不相關,則可以在控制器中執行類似下面的操作。只需創建爲每個實體{X}輸入形式在$表單變量:

$formA = $this->createForm(AppBundle\Entity\EntityAType($entityA)); 
$formB = $this->createForm(AppBundle\Entity\EntityBType($entityB)); 
... 

return array(
    'formA' => $formA->createView(), 
    'formB' => $formB->createView(), 
    ... 
); 
0

你可以簡單地同時保持每個單獨像這樣

namespace AppBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolver; 

class ReallyBigFormType extends AbstractType 
{ 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('foo', FooType::class, [ 
       // label, required, ... as well as options of FooType 
      ]) 
      ->add('bar', BarType::class, [ 
       // label, required, ... as well as options of BarType 
      ]) 
     ; 

    } 

    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults([]); 
    } 

} 

,並定義FooTypeBarType像結合形式規則形式

namespace AppBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolver; 
use Symfony\Component\Form\Extension\Core\Type\TextType 

class FooType extends AbstractType 
{ 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('name', TextType::class, [ 
       'label' => 'foo.name', 
      ]) 
     ; 
    } 

    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults([ 
      'data_class' => 'AppBundle\Entity\Foo', 
     ]); 
    } 

}