2013-06-23 25 views
0

我有一個字符串實體屬性的Symfony2應用程序。根據其他屬性的值,此字符串可以表示另一個實體的ID,日期或任何隨機字符串。Symfony2表單不正確表示存儲的屬性值

我的問題是屬性代表另一個實體的ID的情況。由於我的關聯表單(假定)假定獲取實體而不是字符串,因此表單字段(在這種情況下是可用實體的下拉列表)不能正確反映存儲在數據庫中的值,這意味着它始終默認爲第一個項目在列表中。

我該如何讓表格理解屬性的值是一個實體ID(在它是​​什麼情況下)?

回答

0

首先,您的數據庫設計錯誤。字符串屬性應始終爲字符串,日期屬性應始終爲日期,而關係屬性應始終爲關係。這不僅可以防止混淆,還可以提高性能(因爲symfony會生成高性能連接查詢,並且如果將適當的屬性定義爲實體,則使用代理類)。

在你的情況,有一個解決方案。您可以將任何選項傳遞給您的表單類並動態構建不同的字段集。

SomeController.php:

public function someAction() 
{ 

    $propertyType = array(); 

    // put here your conditions to determine property type 
    if (property is string) 
    { 
     $propertyType['type'] = 'string'; 
    } 
    else if (property is datetime) 
    { 
     $propertyType['type'] = 'datetime'; 
    } 
    else if (property is entity) 
    { 
     $propertyType['type'] = 'entity'; 
     $propertyType['class'] = '\Acme\DemoBundle\Entity\Something'; 
    } 

    $form = $this->createForm(new SomeFormType(), $someData, array('propertyType' => $propertyType)); 
} 

SomeFormType.php:

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setRequired(array(
     'propertyType', 
    )); 
} 

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $array = array('required' => true, 'label' => 'Your label'); 
    if ($options['propertyType']['type'] == 'entity' 
     $array['class'] = $options['propertyType']['class'] 

    $builder 
     ->add('title', $options['propertyType']['type'], $array) 
    ; 
}