返回表单数组而不渲染

时间:2018-01-31 19:37:12

标签: symfony symfony-forms symfony4

我有一个简单的表格:

...
$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这种类型的内容?

1 个答案:

答案 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": {
...