FunkeMT
FunkeMT

Reputation: 1

Symfony2 Doctrine 'preUpdate' event to encode password

Based on question and this answer, i confuesd what the event preUpdate() in combination with symfony and doctrine really does.

To be exact, i mean this line in the answer above:

$event->setNewValue('password', $user->getPassword());

Why i need the extra step of manually setting the new value?
I thought that doctrine handles the event and update the entity by itself without a call of e.g. flush?

Supportive of the thrown exception
Field "password" is not a valid field of the entity "...\UserBundle\Entity\User" in PreUpdateEventArgs.
when i use this, i don't understand why i need to modify the entity manually.

Extended info about the exception: it's only thrown when users logged in. Not when users are registered or edited.

Upvotes: 0

Views: 1016

Answers (1)

Reece45
Reece45

Reputation: 2779

The setNewValue() method can be used to change the value of fields that have been marked as updated. It doesn't work if, for whatever reason, the field you want to update isn't already changed.

Usually, setting the password to null is enough to add it to the changeset. In the event that it isn't, you can request the unit of work recompute the changes.

For example:

<?php

if ($event->hasChangedField('password')) {
    $event->setNewValue('password', $newPassword);
}
else {
    $em = $event->getEntityManager();
    $uow = $em->getUnitOfWork();
    $uow->recomputeSingleEntityChangeSet(
        $em->getClassMetadata(User::class),
        $entity
    );
}

Upvotes: 2

Related Questions