Reputation: 670
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?
Upvotes: 0
Views: 780
Reputation: 1391
You can't, according to the documents.
Symfony's form library uses the validator service internally to validate the underlying object after values have been submitted.
So you're not actually validating form, but the object underneath which has no "notion" of the plain password.
A not so elegant solution would be to include a plain password field on your user and not persist it. However you probably won't be able to validate your existing user objects (e.g: in an update form), since their plain password fields will be null
. To get around that you could create a custom validator that checks the validity of the $plainPassword
field only if the user is not new. You could check that by using doctrine's UnitOfWork
or by checking if the id
of the user is null
.
I suggest you also take a look at FOSUserBundle
it has (or had) a similar approach to the plain password field and might have what you're looking for.
Upvotes: 2