我试图覆盖FOSUserBundle的最大用户名长度。这似乎很简单,但我做不到。
validation.yml
AppBundleEntityUser:
properties:
username:
- Length: { max: 5, groups: [CustomRegistration] }
config.yml
fos_user:
[...]
user_class: AppBundleEntityUser
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' => 'AppBundleEntityUser',
'validation_groups' => ['Default', 'CustomRegistration']
];
}
config.yml
fos_user:
[...]
user_class: AppBundleEntityUser
registration:
form:
type: appbundle_registration
services.yml
services:
appbundle.registration.form.type:
class: AppBundleFormRegistrationFormType
tags:
- { name: form.type, alias: appbundle_registration }
您应该手动为字段添加max-length HTML属性。验证对HTML属性没有影响。
buildForm @ AppBundleFormRegistrationFormType
$builder->add("username", "text", array("attr" => array("maxlength" => "5")));
见:http://symfony.com/doc/current/reference/forms/types/text.html最大长度
如果它不能解决问题,看看你的模板。