2014-01-09 18 views
3

如何將Symfony表單的默認表單值嵌入另一個與實體關聯的表單中?如何設置嵌入在另一個表單中的Symfony表單的默認值?

如果我嘗試在以下示例中將我的PropertyLocation實體中的街道屬性設置爲默認值,則在窗體呈現時,此默認值不會顯示。我知道我可以使用每個表單域的數據選項,但我寧願不這樣做,因爲它覆蓋了實體中設置的內容。我怎樣才能讓表單顯示存儲在實體中的默認值。

class PropertyType 
{ 

    /** 
    * @param FormBuilderInterface $builder 
    * @param array $options 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder->add('propertyLocation', new PropertyLocationType()); 
    } 

    /** 
    * @param OptionsResolverInterface $resolver 
    */ 
    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(
      array('data_class' => 'UR\AppBundle\Entity\Property' 
     )); 
    } 

    /** 
    * @return string 
    */ 
    public function getName() 
    { 
     return 'property'; 
    } 
} 

物業位置類型的樣子:

class PropertyLocationType extends AbstractType 
{ 

    /** 
    * @param FormBuilderInterface $builder 
    * @param array $options 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder->add('street', 'text'); 
    } 

    /** 
    * @param OptionsResolverInterface $resolver 
    */ 
    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
     'data_class' => 'UR\AppBundle\Entity\PropertyLocation' 
     )); 
    } 

    /** 
    * @return string 
    */ 
    public function getName() 
    { 
     return 'propertyLocation'; 
    } 
} 

回答

0

默認值可能會在newAction控制器內設置:

假設你有一個PropertyController.php作爲控制器爲您的財產實體

您的newAction將如下所示:

public function newAction() 
{ 
    $defaultPropertyLocation = new PropertyLocation(); 
    $defaultPropertyLocation->setStreet('default value '); 
    $property = new Property(); 
    $property->setPropertyLocation($defaultPropertyLocation); 
    // now you could pass your property entity to get rendred 
    $form = $this->createCreateForm($property); 

    return $this->render('YourBundle:Property:new.html.twig', array(
     'entity' => $property, 
     'form' => $form->createView(), 
    )); 
} 

編輯第二個選項: 使用data

->add('myfield', 'text', array(
    'label' => 'Field', 
    'data' => 'Default value' 
)) 

AFAIK有沒有第三種選擇。

+0

謝謝您的回覆。我希望有一種方法可以不必在ne​​wAction中顯式創建一個新的PropertyLocation。這可能嗎? – user3009816

+0

這是我知道的唯一方法,畢竟如果你沒有創建'PropertyLocation'實體框架將創建它 – zizoujab

+0

但是,如果我將PropertyLocation實體類中的街道屬性設置爲值,爲什麼Symfony不會使用該屬性值?畢竟,我的data_class指向那個實體。 – user3009816

相關問題