如果我使用对象选项,如何将选项元素标记为选中?

时间:2017-06-20 14:21:53

标签: php symfony

我正在使用Symfony 3框架。

下一个代码来自我的src / AppBundle / Form / ArticleType.php文件:

class ArticleType extends AbstractType
{    
    public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('title')
                ->add('publishAt', ChoiceType::class, array(
                'choices' => array(
                    'now' => new \DateTime('now'),
                    'tomorrow' => new \DateTime('+1 day'),
                    '1 week' => new \DateTime('+1 week'),
                    '1 month' => new \DateTime('+1 month')
                ),
                'data' => 2,
                ));
        }
...
}

代码生成一个带有下一个select元素的表单:

<select ...>
  <option value="0">now</option>
  <option value="1">tomorrow</option>
  <option value="2">1 week</option>
  <option value="3">1 month</option>
</select>

我希望选择值为“2”的选项。

这有效:

->add('publishAt', ChoiceType::class, array(
    'choices' => array(
       'now' => 0,
       'tomorrow' => 1,
       '1 week' => 2,
       '1 month' => 3,
     ),
     'data' => 2,
    )
);

但我有对象而不是数字。我该如何解决?

1 个答案:

答案 0 :(得分:0)

通常,所选值取决于您在表单上操作的数据,但您可以指定值为空时的值。

->add('publishAt', ChoiceType::class, array(
    'choices' => array(
       'now' => 0,
       'tomorrow' => 1,
       '1 week' => 2,
       '1 month' => 3,
     ),
     'empty_data' => '1 week',
    )
);

空数据:http://symfony.com/doc/current/reference/forms/types/choice.html#empty-data

虽然在构建表单时设置了将覆盖empty_data选项的数据。

    $task = new Task();
    $task->setTask('Write a blog post');
    $task->setDueDate(new \DateTime('tomorrow'));

    $form = $this->createFormBuilder($task)
        ->add('task', TextType::class)
        ->add('dueDate', DateType::class)
        ->add('save', SubmitType::class, array('label' => 'Create Post'))
        ->getForm();

    return $this->render('default/new.html.twig', array(
        'form' => $form->createView(),
    ));

完整记录的示例:http://symfony.com/doc/current/forms.html#building-the-form