Symfony2和Doctrine - 在插入时生成代码

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:

  • PrePersist still doesn't have the ID.
  • PostPersist have the ID, but somehow the insertion has already been done and, although I can set any property from the Entity, I don't know how to make it to be persisted "again" to the database.

Any clue overthere?

Any other way to do it properly?

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);
} } }