防止Symfony的CheckboxType铸造字符串到Bool

发布于 2025-02-11 01:06:20 字数 988 浏览 0 评论 0原文

我正在使用Symfony 5.4 REST API工作,并使用FormTypes验证了用户的输入。我有一个必需的布尔字段,如果我收到该字段的任何非树树输入,则希望抛出一个异常。但是,Symfony的CheckBoxType会自动将任何非树树输入设置为true当我提交表单时,因此我无法检查我的输入是否是合法的布尔值。

我的代码看起来像这样:

        $inputModel= new InputModel();
        $this->form->setData($inputModel);
        if ($this->request->isMethod('PUT')) {
            // Here the vaue of $this->request->request->all()['myBooleanField'] is "asdf"
            $this->form->submit($this->request->request->all());
            // Here the value of inputModel->getMyBooleanField() is true
            //...
        }

我的FormType buildform方法看起来像这样:

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        //...
        ->add('myBooleanField', typeForm\CheckboxType::class, [ 'required' => true ])
        //...
        ;
}

任何帮助都将受到赞赏!

I am working on a Symfony 5.4 REST API and validating a user's input using FormTypes. I have a required boolean field and would like to throw a form exception if I receive any non-boolean input for that field. However, Symfony's CheckboxType automatically sets any non-boolean input to true when I submit the form, so I can not check if my input was a legit boolean.

My code looks like this:

        $inputModel= new InputModel();
        $this->form->setData($inputModel);
        if ($this->request->isMethod('PUT')) {
            // Here the vaue of $this->request->request->all()['myBooleanField'] is "asdf"
            $this->form->submit($this->request->request->all());
            // Here the value of inputModel->getMyBooleanField() is true
            //...
        }

My FormType buildForm method looks like this:

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        //...
        ->add('myBooleanField', typeForm\CheckboxType::class, [ 'required' => true ])
        //...
        ;
}

Any help is appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文