【问题标题】:Symfony 3.3 FORM, validate a JSON (in an API) through $form->submit($data)Symfony 3.3 FORM,通过 $form->submit($data) 验证 JSON(在 API 中)
【发布时间】:2018-02-15 10:27:48
【问题描述】:

我正在 Symfony 3.3

中测试一些“API开发”方法

我刚刚浏览了一个教程,它告诉我可以使用 Symfony Forms 来

  1. 自动验证 JSON

  2. 使用 JSON 数据自动填充新实体

所以我创建了一个方法“POST”,我用它来创建一个资源,比如 USER。

  1. 我使用以下 rawbody 发布到该方法: {"name": "foo", "surname": "bar", "userType": 1}

  2. 教程说我可以通过编写以下代码行来用表单完成这两个“自动操作”:

    $data = json_decode($request->getContent(), true);
    
    $user = new User();
    
    $form = $this->createForm(UserType::class, $user );
    
    $form->submit($data);
    
    $em = $this->getDoctrine()->getManager();
    
    $em->persist($user);
    
    $em->flush();
    

表单类“UserType”有以下几行代码:

namespace FooBundle\Form;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)
            ->add('surname', TextType::class)
            ->add('userType', ChoiceType::class, array(
                    'choices' => array(
                        1 => 'one',
                        2 => 'two',
                        3 => 'three',
                        4 => 'four',
                        5 => 'five',
                        6 => 'six',
                    )
                )
            )
        ;
    }


    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                "data_class" => "FooBundle\Entity\User"
            )
        );

    }

}

但是,当我发布到该端点时,出现以下错误:

执行'INSERT INTO user(name, surname, user_type) VALUES (?, ?, ?)' with params ["foo", "bar", null]:

SQLSTATE[23000]:违反完整性约束:1048 列 'user_type' 不能为空

为什么表单不会自动填写“用户类型”字段

我在表单的“ChoiceType”字段中做错了吗?

谢谢:)

【问题讨论】:

    标签: php forms symfony validation


    【解决方案1】:

    ChoiceType 字段的选项是相反的。您的 choices 选项数组应该按照in the documentation 的解释结束:

    choices 选项是一个数组,其中数组键是项的标签,数组值是项的值

    事实上,当您的表单处理请求数据时,它偶然发现了一个不属于userType 预期值的整数。这种情况是通过简单地忽略给定值来处理的,这就是您最终得到null 值的原因。

    长话短说,在你的情况下,你必须像这样写你的 choices 数组:

    'choices' => ['one' => 1, 'two' => 2, ...]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2016-12-14
      • 2021-06-23
      相关资源
      最近更新 更多