首先,您的數據庫設計錯誤。字符串屬性應始終爲字符串,日期屬性應始終爲日期,而關係屬性應始終爲關係。這不僅可以防止混淆,還可以提高性能(因爲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)
;
}