symfony2的新手,我有一个包含2个字段的简单表。
由于alert
字段是布尔值,我声明了这样的形式:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('message', 'text', array('label' => "Message"))
->add('alert', 'choice', array(
'choices' => array(1 => 'Yes', 0 => 'No'),
'expanded' => true,
'multiple' => false,
'label' => "Are you agree?",
'attr' => array('class' => 'well')
));
}
当我创建新条目时它正在工作,但当我尝试编辑条目时,警告'存储在数据库中的选择未在表单中设置(单选按钮)。
如何在表单中设置字段的数据库状态?
答案 0 :(得分:3)
这里有2个选项。
尝试在formbuilder中使用data属性。
$builder
->add('message', 'text', array('label' => "Message"))
->add('alert', 'choice', array(
'choices' => array(1 => 'Yes', 0 => 'No'),
'expanded' => true,
'multiple' => false,
'label' => "Are you agree?",
'data' => $entity->getAlert(),
'attr' => array('class' => 'well')
));
或者: 在symfony中创建表单时,通常会将数据实体传递给该表单。此自动填充所有值。
$this->createForm(new FormType(), $entity);
答案 1 :(得分:1)
要完成Rico Humme的回答,请按以下步骤操作。
public function myFunc() {
....
$entity = $this->getDoctrine()
->getRepository('AcmeFooBundle:Entity')
->find($id);
if ($entity) {
$form = $this->createForm(new EntityType(), $entity);
...
}
}
修改强>:
要完成我的回答, EntityType 的内容如下:
class EntityType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
//This is just soe
$builder->add('alert', 'choice', array(
'choices' => array(1 => 'Yes', 0 => 'No'),
'expanded' => true,
'multiple' => false,
'label' => "Are you agree?",
'attr' => array('class' => 'well')
));
}
public function getName()
{
return 'entity';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\FooBundle\Entity\Entity',
));
}
}