如何以symfony格式禁用必填字段?

时间:2018-08-31 05:59:02

标签: php symfony-3.2

我的地址表格类型需要邮政编码。这是代码

class AddressType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('poBox', TextType::class, ['required' => false])
            ->add('roomNumber', TextType::class, ['required' => false])
            ->add('building', TextType::class, ['required' => false])
            ->add('street', TextType::class, ['required' => false])
            ->add('street2', TextType::class, ['required' => false])
            ->add('country', null, [
                "invalid_message" => "Country is required."
            ])
            ->add('state', null, [
                "invalid_message" => "State is required."
            ])
            ->add('city', null, [
                "invalid_message" => "City is required."
            ])
            ->add('zipCode', TextType::class, [
                "invalid_message" => "Postal Code given is not a valid value.",
                "required" => true,
                "constraints" => [
                    new NotBlank(["message" => "Postal Code is required"]),
                    new Length(["min" => 5, "max" => 5, "exactMessage" => "Postal Code must be a 5-digit code" ]),
                    new Regex(["pattern" => "/^[0-9]+$/", "message" => "Postal code must be numbers only"])
                ]
            ]);
    }

您只能看到我需要的邮政编码。我有另一种表单类型,我称其为Person类型。这种表格类型,我继承了AddressType类。但是如您所见,我禁用了必填字段(false)。

class PersonType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('firstName')
                ->add('lastName')
                ->add('address', AddressType::class, ['required' => false]);

           $builder->get('address')->setRequired(false);                            
        }
    }

每次我提交表单时,总是会收到表单错误postal code is required。我已经以个人类型形式为AddressType禁用了必填字段。我无法将邮政编码的必填字段更改为false,因为其他需要邮政编码的表单类型(例如CompanyType)。有人在如何将必填字段更改为false时遇到这种问题吗?

1 个答案:

答案 0 :(得分:0)

您只需要添加此代码

$builder->get('address')->setRequired(false);