2014-06-24 38 views
0

我有一個表單類型,並希望知道在我的情況下在setDefaultOptionsdata_class提出什麼要求。我知道我們通常會放置實體的路徑,但在這種情況下,我嵌入了兩個實體,所以我現在該做什麼?在表單類型中爲data_class賦值

我知道我們可以忽略它,但我不想因爲它建議不由SensioLabs(...So, while not always necessary, it's generally a good idea to explicitly specify the data_class option...)。

$resolver->setDefaults(array('data_class' => '?????????????????????')); 

表格類型:

namespace Car\BrandBundle\Form\Type; 

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

class BothType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->setMethod('POST') 
      ->setAction($options['action']) 
      ->add('brands', new BrandsType()) 
      ->add('cars', new CarsType()) 
      ->add('button', 'submit', array('label' => 'Add')) 
      ; 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array('data_class' => '?????????????????????')); 
    } 

    public function getName() 
    { 
     return 'both'; 
    } 
} 

控制器:

namespace Car\BrandBundle\Controller; 

use Car\BrandBundle\Entity\Brands; 
use Car\BrandBundle\Entity\Cars; 
use Car\BrandBundle\Form\Type\BothType; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class BothController extends Controller 
{ 
    public function indexAction() 
    { 
     $entity = array(new Brands(), new Cars()); 

     $form = $this->createForm(new BothType(), $entity, 
       array('action' => $this->generateUrl('bothCreate'))); 

     return $this->render('CarBrandBundle:Default:both.html.twig', 
      array('page' => 'Both', 'form' => $form->createView())); 
    } 
} 

當我回聲提交的數據我得到這個複製的數據:

Array 
(
    [0] => Car\BrandBundle\Entity\Brands Object 
     (
      [id:protected] => 
      [name:protected] => 
      [origin:protected] => 
     ) 

    [1] => Car\BrandBundle\Entity\Cars Object 
     (
      [id:protected] => 
      [model:protected] => 
      [price:protected] => 
     ) 

    [brands] => Car\BrandBundle\Entity\Brands Object 
     (
      [id:protected] => 
      [name:protected] => Mercedes 
      [origin:protected] => Germany 
     ) 

    [cars] => Car\BrandBundle\Entity\Cars Object 
     (
      [id:protected] => 
      [model:protected] => SL500 
      [price:protected] => 25,000 
     ) 

) 
+0

在你的情況下,你沒有一個實體類來映射它。所以除非你創建一個,否則你應該把它留空。 – Chausser

回答

1

我認爲這裏最好的方法實際上是忽略它,因爲沒有特定的實體將它鏈接到它。該文檔應該被理解爲「如果你的表單綁定到一個實體,那麼它更好」。

+0

是的,我忽略了在控制器中傳遞數組,並將'null'分配給'data_class',結果正常。 – BentCoder

相關問題