我有以下形式:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, array(
'expanded' => true,
'multiple' => false,
'choices' => array(
'Friend' => 'friend',
'Guide' => 'guide'
)
));
}
如何在呈现表单时默认选中"朋友"复选框?
我认为您应该尝试使用data
选项,但这只是在您甚至没有在对象中保存数据的情况下,因为它会覆盖它。
重要提示:它适用于创建操作,但不适用于编辑操作。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, array(
'expanded' => true,
'multiple' => false,
'choices' => array(
'Friend' => 'friend',
'Guide' => 'guide'
),
'data' => 'friend'
));
}
官方链接
摘录 :
创建表单时,每个字段最初显示 表单域对象的对应属性(如果对象是 绑定到表单)。如果要覆盖 表单或只是一个单独的字段,您可以在数据选项中进行设置
更新 如果您需要空值:
作为下面的答案,如果您在任何情况下都需要更新默认值,请将data
替换为empty_data
使用"empty_data
表单域"选项。(不是data
因为它将覆盖任何已发布的数据,除非您动态设置它)。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, array(
'expanded' => true,
'multiple' => false,
'choices' => array(
'Friend' => 'friend',
'Guide' => 'guide'
),
'empty_data' => 'friend'
));
}
复杂案例的另一个选项是使用 SF 动态表单事件。
如果您不想覆盖版本的值,可以这样做:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
$form->add(
'type',
ChoiceType::class,
[
'expanded' => true,
'multiple' => false,
'choices' => [
'Friend' => 'friend',
'Guide' => 'guide'
],
'data' => $event->getData() ?: 'friend'
]);
});
}
我认为最好
在实体构造函数中设置初始值:
public function __construct()
{
$this->exercises = new ArrayCollection();
$this->setTitle("WOCHE#") ;
$this->setYear(date('Y'));
$this->setWeekInCalendar(Week::getCurrentWeekInCalendar());
}
另一种
解决方案是将占位符设置为 false.
这会将第一个值设置为默认值><,并最大限度地减少设置工作量。如果该字段需要为空,您可以再添加一个选择,即 'empty' => null
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, array(
'expanded' => true,
'multiple' => false,
'choices' => array(
'Friend' => 'friend',
'Guide' => 'guide'
),
'placeholder' => false
));
}