我有两个密码字段。额外的用于确认。当两者都为空或密码不匹配时,不会出现错误消息。
如何启用或调试我认为应该开箱即用的验证(http://symfony.com/doc/current/reference/forms/types/repeated.html#validation)?
class MyType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'My\\Bundle\\Entity\\User',
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
...
$builder->add('password', 'repeated', array(
'invalid_message' => 'Passwords must match.',
'type' => 'password',
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password')
));
form.html.twig
...
<form action="" method="post" novalidate>
...
<tr>
<td>{{ form_label(regForm.password.first) }}</td>
<td>{{ form_widget(regForm.password.first, { 'attr': {'pattern': '.{6,}','title': 'Minimum 6 characters long'} } ) }}</td>
</tr>
<tr>
<td>{{ form_label(regForm.password.second) }}</td>
<td>{{ form_widget(regForm.password.second, { 'attr': {'pattern': '.{6,}', 'title': 'Minimum 6 characters long', 'data-equals': '#register_password_first'} } ) }}</td>
</tr>
在validation.yml 中声明的验证器似乎对这个问题没有影响。
My\Bundle\Entity\User:
properties:
...
password:
# this one does not work because of "repeated" type in buildForm()???
- NotBlank:
message: "Password is required."
- MinLength:
limit: 6
message: "Password must have at least {{ limit }} characters."
Controller.php(原版)
...
if (!$form->isValid()) {
$formFields = $form->all();
foreach ($formFields as $key => $field) {
if ($field->getErrorsAsString()) {
$errors = $field->getErrors();
foreach ($errors as $error) {
$messages[$key][] = $error->getMessage();
}
}
}
var_dump($messages);
编辑:现在错误检索看起来像这样(感谢 alex.dominte):
public static function getFormErrorMessages(\Symfony\Component\Form\Form $form)
{
$messages = array();
foreach ($form->getErrors() as $i => $error) {
$messages[$i] = $error->getMessage();
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$messages[$child->getName()] = self::getFormErrorMessages($child);
}
}
return $messages;
}
Pedro Cordeiro 建议的修改可以删除递归,但也可以使字段名称不可用。