坚持非持久性字段变更的实体 [英] Persist entity on non persisted field change

查看:49
本文介绍了坚持非持久性字段变更的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有plainPassword和password属性的实体.在形式上,我映射到plainPassword上.之后,当用户验证表单时,我在plainPassword上进行密码验证.

I've an entity with a plainPassword and a password attribute. In form, I map on the plainPassword. After, when the user valid the form, I do password validation on the plainPassword.

要编码密码,我使用EventSubscriber侦听prePersist和preUpdate.它适用于注册表,因为它是一个新实体,用户填写了一些保留的属性,然后根据学说对其进行了保留并刷新.

To encode the password, I use an EventSubscriber that listen on prePersist and preUpdate. It works well for the register form, because it's a new entity, the user fill some persisted attributes, then doctrine persist it and flush.

但是,当我只想编辑密码时,它不起作用,我认为这是因为用户只是编辑了一个非持久属性.然后,Doctrine不会尝试坚持下去.但是我需要它,才能输入订户.

But, when I just want to edit the password, it doesn't work, I think it's because the user just edit a non persisted attribute. Then Doctrine doesn't try to persist it. But I need it, to enter in the Subscriber.

有人知道该怎么做吗?(我在另一个实体中也有类似的问题)目前,我在控制器中执行操作...

Someone know how to do it ? (I've a similar problem in an other entity) For the moment, I do the operation in the controller...

非常感谢.

我的UserSubscriber

My UserSubscriber

  class UserSubscriber implements EventSubscriber
  {
      private $passwordEncoder;
      private $tokenGenerator;

      public function __construct(UserPasswordEncoder $passwordEncoder, TokenGenerator $tokenGenerator)
      {
          $this->passwordEncoder = $passwordEncoder;
          $this->tokenGenerator = $tokenGenerator;
      }

      public function getSubscribedEvents()
      {
          return array(
              'prePersist',
              'preUpdate',
          );
      }

      public function prePersist(LifecycleEventArgs $args)
      {
          $object = $args->getObject();
          if ($object instanceof User) {
              $this->createActivationToken($object);
              $this->encodePassword($object);
          }
      }

      public function preUpdate(LifecycleEventArgs $args)
      {
          $object = $args->getObject();
          if ($object instanceof User) {
              $this->encodePassword($object);
          }
      }

      private function createActivationToken(User $user)
      {
          // If it's not a new object, return
          if (null !== $user->getId()) {
              return;
          }

          $token = $this->tokenGenerator->generateToken();
          $user->setConfirmationToken($token);
      }

      private function encodePassword(User $user)
      {
          if (null === $user->getPlainPassword()) {
              return;
          }

          $encodedPassword = $this->passwordEncoder->encodePassword($user, $user->getPlainPassword());
          $user->setPassword($encodedPassword);
      }

我的用户实体:

class User implements AdvancedUserInterface, \Serializable
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(name="email", type="string", length=255, unique=true)
 * @Assert\NotBlank()
 * @Assert\Email()
 */
private $email;

/**
 * @Assert\Length(max=4096)
 */
private $plainPassword;

/**
 * @ORM\Column(name="password", type="string", length=64)
 */

private $password;

ProfileController:

ProfileController:

class ProfileController extends Controller 
{
/**
 * @Route("/my-profile/password/edit", name="user_password_edit")
 * @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
 */
public function editPasswordAction(Request $request)
{
    $user = $this->getUser();
    $form = $this->createForm(ChangePasswordType::class, $user);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        // Encode the password
        // If I decomment it, it's work, but I want to do it autmaticlally, but in the form I just change the plainPassword, that is not persisted in database
        //$password = $this->get('security.password_encoder')->encodePassword($user, $user->getPlainPassword());
        //$user->setPassword($password);
        $em = $this->getDoctrine()->getManager();
        $em->flush();
        $this->addFlash('success', 'Your password have been successfully changed.');
        return $this->redirectToRoute('user_profile');
    }
    return $this->render('user/password/edit.html.twig', [
        'form' => $form->createView(),
    ]);
}

}

推荐答案

您可以通过直接操作UnitOfWork来强制Doctrine将对象标记为脏对象.

You can force Doctrine to mark an object as dirty by manipulating the UnitOfWork directly.

$em->getUnitOfWork()->scheduleForUpdate($entity)

但是,我强烈反对这种方法,因为它违反了精心设计的抽象层.

However, I do strongly discourage this approach as it violates carefully crafted abstraction layers.

这篇关于坚持非持久性字段变更的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆