我将Symfony Form Component用于我们的RESTish JSON API(灵感来自 http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/(。
现在我有一些多维的 POST-请求,总是具有相同的根键(name
和 actions
(,但不同的子元素。
{
"name": "Name",
"actions": [{
"type": "type_of_action",
"config": {
"name": "name",
"assigned_to": "23cb1a6b-5a99-4b91-ae72-b52882b45f47",
"information": "Lorem Impsum"
}
},{
"type": "type_of_other_action",
"config": {
"name": "name",
"dueDate": "2016-12-01"
"active": "true"
}
}]
}
如您所见,每个actions
元素上的config
都可能不同。我需要这样的东西:
->add('config', [TaskActionType::class, OtherActionType::class])
我知道,不可能呈现这样的形式,但我只需要它来验证请求并将其传输到可靠的数组 ($data = $form->get('actions')->getData()
(。
尝试将选项参数发送到窗体中,然后呈现该子窗体类型。
控制器:
$form = $this->createForm(MainForm::class, null, [
'method' => Request::METHOD_POST,
'param' => $param
]);
主窗体:
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$param = $options['param'];
if (param == "type1") {
$builder
->add('config', FormType1::class))
} elseif (param == "type2") {
$builder
->add('config', FormType2::class))
}
}
我希望这就是你需要的。