10 php symfony doctrine-orm sonata-admin sonata
我正在使用Sonata管理包为我的应用程序一切正常,在我的应用程序中我有用户和管理员,管理员可以添加/编辑/删除用户当我尝试更新用户时出现问题密码数据被用户覆盖表.我已经覆盖了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());
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试设置$object->setUserPassword($object->getUserPassword());
它获取null并将密码更新为null它没有得到编辑数据我试图再次获取存储库(下面)获取密码但没有运气它得到相同
$DM = $this->getConfigurationPool()->getContainer()->get('Doctrine')->getManager()->getRepository("...")->find(id here);
Run Code Online (Sandbox Code Playgroud)
有没有办法可以访问实体管理器中当前实体的原始数据
M K*_*aid 26
您可以通过获取学说的工作单元来访问原始数据.来自文档
您可以通过调用EntityManager#getUnitOfWork()直接访问工作单元.这将返回EntityManager当前正在使用的UnitOfWork实例.包含实体原始数据的数组
从工作单元中获取密码并在您的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 */
}
}
Run Code Online (Sandbox Code Playgroud)
希望它工作正常