我正在为我的应用程序使用 Sonata admin bundle,一切正常,在我的应用程序中,我有用户和管理员,当我尝试更新用户时,管理员可以添加/编辑/删除用户密码数据有问题从用户表中覆盖。我已经覆盖了管理 Controller 的 preUpdate
方法,我得到了 $object
,它有一个用户实体管理器的实例,所以如果用户离开去更新密码并保存数据,密码就会丢失.
public function preUpdate($object)
{
$Password = $object->getUserPassword();
if (!empty($Password)) { /* i check here if user has enter password then update it goes well*/
$salt = md5(time());
$encoderservice = $this->getConfigurationPool()->getContainer()->get('security.encoder_factory');
$User = new User();
$encoder = $encoderservice->getEncoder($User);
$encoded_pass = $encoder->encodePassword($Password, $salt);
$object->setUserSalt($salt)->setUserPassword($encoded_pass);
} else { /* here i try to set the old password if user not enters the new password but fails */
$object->setUserPassword($object->getUserPassword());
}
}
当我尝试设置 $object->setUserPassword($object->getUserPassword());
它得到 null 并将密码更新为 null 它没有得到我试图得到的编辑数据再次访问存储库(如下)以获取密码,但运气不佳
$DM = $this->getConfigurationPool()->getContainer()->get('Doctrine')->getManager()->getRepository("...")->find(id here);
有没有办法在实体管理器中访问当前实体的原始数据
最佳答案
您可以通过获取 doctrine 的 Unit of Work 来访问原始数据。As from docs
You can get direct access to the Unit of Work by calling EntityManager#getUnitOfWork(). This will return the UnitOfWork instance the EntityManager is currently using.An array containing the original data of entity
从 Unit of Work 获取密码并在你的 setter 方法中使用
public function preUpdate($object)
{
$DM = $this->getConfigurationPool()->getContainer()->get('Doctrine')->getManager();
$uow = $DM->getUnitOfWork();
$OriginalEntityData = $uow->getOriginalEntityData( $object );
$Password = $object->getUserPassword();
if (!empty($Password)) { /* i check here if user has enter password then update it goes well*/
$salt = md5(time());
$encoderservice = $this->getConfigurationPool()->getContainer()->get('security.encoder_factory');
$User = new User();
$encoder = $encoderservice->getEncoder($User);
$encoded_pass = $encoder->encodePassword($Password, $salt);
$object->setUserSalt($salt)->setUserPassword($encoded_pass);
} else { /* here i try to set the old password if user not enters the new password but fails */
$object->setUserPassword($OriginalEntityData['Password']);/* your property name for password field */
}
}
希望一切顺利
关于php - Symfony 2 从实体管理器获取实体的原始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20251781/