我有一个简单的表格:
...
$builder
->add('email', EmailType::class, array(
'constraints' => [
new Length(array('min' => 3)),
new NotBlank(),
],
))
->add('username', TextType::class)
...
我希望将该表单作为JSON响应返回,而不是在Twig
模板中呈现它,如下所示:
{
fields: {
email: {
type: 'email',
constraints: {
'notBlank',
lenght: {
'min': 3
}
}
},
username: {
type: 'text'
}
}
}
如果不使用array
之类的第三方套装,是否可以返回FOSRestBundle
这种类型的内容?
答案 0 :(得分:0)
经过两个小时的搜索,我发现没什么兴趣,但基于一个answer我写了这个:
$user = new User();
$form = $this->createForm(UserType::class, $user);
foreach ($form->all() as $field) {
$name = $field->getName();
$options = $field->getConfig()->getOptions();
$fields[$name]['type'] = $field->getConfig()->getType()->getBlockPrefix();
$fields[$name]['disabled'] = $options['disabled'];
foreach ($options['constraints'] as $constraint) {
$rules = [];
// Get lowercase constraint name from class.
$class = strtolower((new \ReflectionClass($constraint))->getShortName());
switch ($class) {
case 'length':
$rules['min'] = $constraint->min;
$rules['max'] = $constraint->max;
break;
// More constraints here.
}
$fields[$name]['constraints'][$class] = empty($rules) ? true : $rules;
}
}
return new JsonResponse(['fields' => $fields]);
给了我以下结果,我很满意:
"fields": {
"email": {
"type": "email",
"disabled": false,
"constraints": {
"length": {
"min": 3,
"max": null
},
"notblank": true
}
},
"username": {
"type": "text",
"disabled": false
},
"plainPassword": {
"type": "repeated",
"disabled": false,
"constraints": {
...