I ran into a trouble of understanding how exactly data is processed in DataTransformers of Symfony.
I have a just a password form. Just one field. This field belongs to the User entity which has to constraints defined in .yml
file.
Software\Bundle\Entity\User:
password:
- NotBlank: ~
- Length:
min: 6
max: 155
The validation works fine, as supposed to. The problem arise when password must be encoded automatically from the field. So,
$builder->add('password', 'password', [
'label' => 'word.password'
]);
$builder->get('password')
->addModelTransformer(new EncodePasswordTransformer());
And the transformer itself:
class EncodePasswordTransformer implements DataTransformerInterface
{
public function transform($value)
{
return $value;
}
public function reverseTransform($value)
{
// encode password
return PasswordHash::createHash($value);
}
}
So here's what's happening:
The form should contain 6 to 155 characters but $form->isValid()
is always true, because the PasswordHash::createHash($value)
encodes the password to 32 characters. What I was expecting is:
Form validates raw password, if more than 6 chars then go to $form->isValid()
true and then encode the password after it's validated.
I know I can just encode the password manually while the form is valid without using DataTransformer
but I was hoping for a bit more elegant way.
Am I wrong?