Testing if a Doctrine entity has been modified

Published on 2020-12-18 • Modified on 2020-12-18

In this snippet, we will see how to test if a Doctrine entity has been modified from its initial state in the database. We must use the isEntityScheduled() function of the UnitOfWork Doctrine object. If you want to test if an entity is already persisted in the database, check out this snippet.
PS: If you hit the run button will see at the bottom left that the author is "webby" not "COil" as it should be as we just modified this field at runtime.


<?php

declare(strict_types=1);

// src/Controller/Snippet/Snippet124Trait.php

namespace App\Controller\Snippet;

use App\Repository\ArticleRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\UnitOfWork;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor..
 *
 * @property ArticleRepository $articleRepo
 */
trait Snippet124Trait
{
    public function snippet124(): void
    {
        $manager = $this->getDoctrine()->getManager();
        if (!$manager instanceof EntityManager) {
            throw new \RuntimeException('Houston, We Have a Problem. 💥');
        }

        $uow = $manager->getUnitOfWork();
        if (!$uow instanceof UnitOfWork) {
            throw new \RuntimeException('Houston, We Have a Problem. 💥');
        }

        $article = $this->articleRepo->findById(124); // this snippet
        var_dump($uow->isEntityScheduled($article));

        // Now modify the article with dummy data
        $article->setAuthor('Webby');
        $uow->computeChangeSets();
        var_dump($uow->isEntityScheduled($article)); // should return true now

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow  Random snippet