Symfony2重写bundle HTML表单输入约束

时间:2015-07-10 10:28:16

标签: forms validation symfony fosuserbundle

我试图覆盖FOSUserBundle的最大用户名长度。看起来很简单,但我无法做到。

validation.yml

AppBundle\Entity\User:
    properties:
        username:
            - Length: { max: 5, groups: [CustomRegistration] }

config.yml

fos_user:
    [...]
    user_class: AppBundle\Entity\User
    registration:
        form:
            validation_groups: [CustomRegistration]

验证本身运行正常。如果用户提供超过5个字符的用户名,Symfony会显示一个不应超过5个字符的错误。问题是HTML表单输入仍然使用默认的FOSUserBundle值(255)。表单构建器似乎完全忽略验证组。有什么方法可以让表单构建器使用我的约束吗?

我想提一下,当我使用XML格式时HTML验证有效,但我需要使用YAML,它只能巧合,所以我不想依赖这样的怪癖。

我也尝试提供自定义类型,希望它会改变任何东西,但事实并非如此。用户名输入仍然使用maxlength值255.供参考:

getDefaultOptions @ AppBundle / Form / RegistrationFormType.php

public function getDefaultOptions(array $options)
{
    return [
        'data_class'        => 'AppBundle\Entity\User',
        'validation_groups' => ['Default', 'CustomRegistration']
    ];
}

config.yml

fos_user:
    [...]
    user_class: AppBundle\Entity\User
    registration:
        form:
            type: appbundle_registration

services.yml

services:
    appbundle.registration.form.type:
        class: AppBundle\Form\RegistrationFormType
        tags:
            - { name: form.type, alias: appbundle_registration }

1 个答案:

答案 0 :(得分:0)

您应该手动将max-length HTML属性添加到字段中。 验证对HTML属性没有影响。

buildForm @ AppBundle \ Form \ RegistrationFormType

$builder->add("username", "text", array("attr" => array("maxlength" => "5")));

请参阅:http://symfony.com/doc/current/reference/forms/types/text.html#max-length

如果它没有解决问题,请查看您的模板。它也可以在那里设置..