ElPiter
ElPiter

Reputation: 4324

Symfony2 and Doctrine - Generate code on insertion

Using Symfon2.0 and Doctrine, I am trying to do the following:

  1. Insert a new row in the database
  2. in the moment of inserting, automatically generate a code and also insert it.
  3. That code is related to the ID of the table. Something like <something>/row_id

How can I easily do this?

I've been trying Doctrine Livecycle callbacks. But:

Any clue overthere?

Any other way to do it properly?

Upvotes: 2

Views: 190

Answers (1)

Lighthart
Lighthart

Reputation: 3656

In your create controller:

if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        $entity->setCode($code);
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('entity_show'
           ,array('id' => $entity->getId())));
    }

The second block ($entity->setCode...) is what you need to add and will need to be customized to suit your purposes

Alternatively, you can use Listeners:

<?php

namespace ormed\ormedBundle\Listener;

use Doctrine\ORM\Event\OnFlushEventArgs; use
Symfony\Component\DependencyInjection\Container;

class LastModifiedListener {

  private $container;

  public function __construct(Container $container){$this->container = $container;}

  public function onFlush(OnFlushEventArgs $eventArgs)
  {
      $entityManager = $eventArgs->getEntityManager();
      $unitOfWork = $entityManager->getUnitOfWork();

      foreach ($unitOfWork->getScheduledEntityInsertions() AS $entity) {
          $entity->setCode( $code );

          $entityManager->persist($entity);
          $classMetadata = $entityManager->getClassMetadata(get_class($entity));
          $unitOfWork->recomputeSingleEntityChangeSet($classMetadata, $entity);
} } }

Upvotes: 1

Related Questions