php 强制不需要字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11868497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:18:52  来源:igfitidea点击:

Force a field to not be required

phpsymfonyfosuserbundle

提问by ElPiter

I am using Symfony2 and FOSUserBundle.

我正在使用 Symfony2 和 FOSUserBundle。

Just as detailed in the documentation, I have overridden and created a "name" property in the User entity.

正如文档中所详述的那样,我在用户实体中覆盖并创建了一个“名称”属性。

I do all necessary and finally get that field to be shown in the form view.

我做了所有必要的事情,最后让该字段显示在表单视图中。

The thing is: when I go form_widget(form.name)and the input html tag is generated, a required="required" property is generated within it. And that causes the engine to red the input when the field is not filled in.

问题是:当我去form_widget(form.name)并生成输入 html 标签时,会在其中生成一个 required="required" 属性。这会导致引擎在未填写该字段时将输入变为红色。

How do I do to tell the Symfony2 not to make that field mandatory? I guess that it has to be here:

我该如何告诉 Symfony2 不要将该字段设为必填项?我想它必须在这里:

        parent::buildForm($builder, $options);

    // add your custom field
    $builder->add('name', 'text', array('label' => 'form.name'));
    $builder->remove('username');

or here:

或在这里:

    /**
 * @ORM\Column(type="string", length="255")
 *
 * @Assert\MinLength(limit="0", message="The name is too short.", groups={"Registration", "Profile"})
 * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"})
 */
private $name;

回答by Carlos Granados

$builder->add('name', 'text', array('label' => 'form.name','required' => false));

回答by Shadi Akil

Try to use:

尝试使用:

use Symfony\Component\Validator\Constraints\NotNull;


$builder->add('name', 'text', array('label' => 'form.name',
'constraints' => new NotNull()));