我有以下实体:
//实体
class propertiesGeneral{
/**
* @var abc\NikBundle\Entity\propertiesFinancial $finances
* @ORM\OneToOne(targetEntity="propertiesFinancial", mappedBy="property", cascade= {"persist", "remove", "merge"}))
*/
protected $finances;
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
protected $generalfield1;
protected $generalfield2;
}
class propertiesFinancial{
/**
* @ORM\OneToOne(targetEntity="propertiesGeneral", inversedBy="finances")
* @ORM\JoinColumn(name="property_id", referencedColumnName="id")
* @ORM\Id
*/
protected $property;
protected $financialfield1;
protected $financialfield2;
}
所以我有以下表格来保存一个新的propertiesGeneral和propertiesFinancial对象:
$builder = $this->createFormBuilder();
$form = $builder
->add('general',new GeneralType, array(
'label' => false
))
->add('finances',new FinancesType,array(
'label' => false
))
->add('price_rent','text',array(
'mapped' => false,
))
->add('price_buy','text',array(
'mapped' => false,
))
->getForm();
而GeneralType表单是:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('generalfield1',null)
->add('generalfield2',null)
}
而财务表格是:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('financialfield1',null)
->add('financialfield2',null)
}
此代码可以在数据库中保留propertiesGeneral和propertiesFinancial对象。但我的问题是如何编辑现有记录。所以我希望使用与字段的默认值相同的表单作为从数据库中检索的对象的相应值。是否有可能使用相同的形式?
答案 0 :(得分:-1)
在表单类(Type)中,您可以定义setDefaultOptions
方法:
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FQCN of your entity like Acme/Entity/propertiesGeneral',
));
}
工作原理:
$form = $this->createForm(new GeneralType(), new propertiesGeneral());
或
$form = $this->createForm(new GeneralType(), $propertiesGeneralObject);
另外,请阅读:http://symfony.com/doc/current/book/forms.html#creating-form-classes和http://symfony.com/doc/current/cookbook/form/form_collections.html了解详情。