title: Symfony2 - SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry - SonataAdminBundle - UPDATE after INSERT
body: <p>I use SonataAdminBundle. My goal is to manage my articles and so allow administrators to create through the admin interface.</p>
  
  <p>Here's how the relationship is defined in my User class.</p>
  
  <p>So I have to use:</p>
  
  <pre><code>     /**
      * @var articles
      *
      * Here we will set the OneToMany relationship (Many: One - article : user) 
      * @ORM\OneToMany(targetEntity="Kark\RecetteBundle\Entity\Article", mappedBy="user", cascade={"persist", "remove"})
      */
      protected $articles;
  
      public function __construct()
      {
          //Une classe à pour instrctruction dans sont constructeur, le constructeur du parent
          parent::__construct();
  
          $this-&gt;articles = new \Doctrine\Common\Collections\ArrayCollection();
      }
  
     /**
      * Get articles
      *
      * @return ArrayCollection
      */
      public function getArticles()
      {
          return 
  
  $articles;
      }
  
  
     /**        
      *
      * @param $unArticle
      */
      public function addArticle(\Kark\RecetteBundle\Entity\Article $unArticle)
      {
          $this-&gt;articles[] = $unArticle;
          $unArticle-&gt;setUser($this);
      }
  </code></pre>
  
  <p>And here in my class Article:</p>
  
  <pre><code>/**
    *      @ORM\ManyToOne(targetEntity="Kark\UserBundle\Entity\User", inversedBy="articles")
    */
    private $user;
  
  /**
   * Set user
   *
   * @param User
   * @return article
   */
   public function setUser(\Kark\UserBundle\Entity\User $unUser)
   {
      $this-&gt;user = $unUser;
  
      return $this;
   }
  
   /**
   * Get user
   *
   * @return User
   */
    public function getUser()
    {
       return $this-&gt;user;
    }
  </code></pre>
  
  <p>In my SonataAdminBundle I then defined the constroller CRUD two entities User and Article:
      
  
  <pre><code>    namespace Kark\AdminBundle\Controller;
  
      use Sonata\AdminBundle\Controller\CRUDController as Controller;
  
      class ArticleAdminController extends Controller
      {
  
      }
  </code></pre>
  
  <p>Here is the CRUD User:</p>
  
  <pre><code>&lt;?php
  
  namespace Kark\AdminBundle\Controller;
  
  use Sonata\AdminBundle\Controller\CRUDController as Controller;
  
  class UserAdminController extends Controller
  {
  
  }
  </code></pre>
  
  <p>and their configurations in admin.cfg:</p>
  
  <pre><code># Kark/AdminBundle/Resources/config/admin.yml
  services:
      kark.admin.admin.article:
          class: Kark\AdminBundle\Admin\ArticleAdmin
          tags:
              - { name: sonata.admin, manager_type: orm, group: Article, label: articles }
          arguments:
              - ~
              - Kark\RecetteBundle\Entity\Article
              - KarkAdminBundle:ArticleAdmin
  </code></pre>
  
  <p>Here's the part for the User entity:</p>
  
  <pre><code>kark.admin.admin.userarticle:
      class: Kark\AdminBundle\Admin\UserAdmin
      tags:
          - { name: sonata.admin, manager_type: orm, group: user, label: users }
      arguments:
          - ~
          - Kark\UserBundle\Entity\User
          - KarkAdminBundle:UserAdmin
  </code></pre>
  
  <p>Everything is set up, and I have the following definition in my class Admin of my Article:</p>
  
  <pre><code>&lt;?php
  
  namespace Kark\AdminBundle\Admin;
  
  use Sonata\AdminBundle\Admin\Admin;
  use Sonata\AdminBundle\Form\FormMapper;
  use Sonata\AdminBundle\Datagrid\DatagridMapper;
  use Sonata\AdminBundle\Datagrid\ListMapper;
  use Sonata\AdminBundle\Show\ShowMapper;
  use Kark\RecetteBundle\Entity\Article;
  use Kark\RecetteBundle\Entity\ImageArticle;
  
  use Knp\Menu\ItemInterface as MenuItemInterface;
  
  class ArticleAdmin extends Admin
  {
       // setup the default sort column and order
      protected $datagridValues = array(
          '_sort_order' =&gt; 'ASC',
          '_sort_by' =&gt; 'name'
      );
  
  
      // L'ensemble des champs qui seront montrer lors de la création ou de la modification d'une entité
      protected function configureFormFields(FormMapper $formMapper)
      {
          $formMapper
              -&gt;with('General')
                  -&gt;add('titre', 'text')
                  -&gt;add('imageArticle', 'sonata_type_admin', array('delete' =&gt; false), array('required' =&gt; true, 'edit' =&gt; 'inline'))
                  -&gt;add('contenu','textarea');
       }
  
      /**
      *
      * Fonction qui va permettre d'afficher les différent filtres de recherche dans notre tableau
      * de notre interface.
      *
      */
      protected function configureDatagridFilters(DatagridMapper $datagridMapper)
      {
          $datagridMapper
              -&gt;add('titre')
              -&gt;add('user.username')
          ;
      }
  
      /**
      * Fonction qui redéfini celle de la classe mère Admin. Cette fonction va nous permettre de préciser les
      * champs qui seront affiché dans notre tableau lorsque l'on listera nos entités
      */
      protected function configureListFields(ListMapper $listMapper)
      {
          $listMapper
              -&gt;addIdentifier('titre')
              -&gt;add('date', null, array('route' =&gt; array('name' =&gt; 'show')))
              -&gt;add('contenu')
              -&gt;add('user.username')
              -&gt;add('_action', 'actions', array(
                  'actions' =&gt; array(
                  'show' =&gt; array(),
                  'edit' =&gt; array(),
                  'delete' =&gt; array()
                  )
              ))
          ;
      }
  
      /**
      * Fonction qui redéfinie la fonction de la classe mère qui permet d'indiquer les champs qui seront affiché
      * lorsque l'on consultera un article
      */
      protected function configureShowFields(ShowMapper $showMapper)
      {
          $showMapper
              -&gt;add('date')
              -&gt;add('titre')
              -&gt;add('contenu')
              -&gt;add('imageArticle.getWebPath()', 'string', array('template' =&gt; 'KarkAdminBundle:ArticleAdmin:list_image.html.twig'))
              -&gt;add('user.username')
          ;
      }
  
  
   /**
       * {@inheritdoc}
       */
      public function prePersist($object)
      {
  
          $user = $this-&gt;getConfigurationPool()-&gt;getContainer()-&gt;get('security.context')-&gt;getToken()-&gt;getUser();
          $user-&gt;addArticle($object);
      }
  
      /**
       * {@inheritdoc}
       */
      public function preUpdate($object)
      {
          $user = $this-&gt;getConfigurationPool()-&gt;getContainer()-&gt;get('security.context')-&gt;getToken()-&gt;getUser();
          $user-&gt;addArticle($object);
      }
  }
  </code></pre>
  
  <p>However, the article does not insert because it performs INSERT and UPDATE, and in table 'article_audit it performs the same insert twice, and so there is a primary key dupliquata ...</p>
  
  <pre><code>[3/4] UniqueConstraintViolationException: An exception occurred while executing 'INSERT INTO article_audit (rev, revtype, imageArticle_id, user_id, id, date, titre, contenu, publication, dateEdition, slugTitre) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["545", "UPD", 43, 1, 43, "2014-06-16 23:28:40", "qsmodjqskdjqslkdqjsk", "&lt;p&gt;qsldkqsmldkqslmdkqsmdlqslk lmqskdmlqskdqsmld qskdjqslkdqjsldqksd&lt;\/p&gt;", 0, "2014-06-16 23:28:40", "qsmodjqskdjqslkdqjsk"]:
  
  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '43-545' for key 'PRIMARY'
  
   PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '43-545' for key 'PRIMARY'
  </code></pre>
  
  <p>Here is the log file:</p>
  
  <pre><code>DEBUG - INSERT INTO article (date, titre, contenu, publication, dateEdition, slugTitre, imageArticle_id, user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  DEBUG - INSERT INTO article_audit (rev, revtype, imageArticle_id, user_id, id, date, titre, contenu, publication, dateEdition, slugTitre) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  DEBUG - UPDATE article SET date = ?, titre = ?, contenu = ?, publication = ?, dateEdition = ?, slugTitre = ?, imageArticle_id = ?, user_id = ? WHERE id = ?
  DEBUG - INSERT INTO article_audit (rev, revtype, imageArticle_id, user_id, id, date, titre, contenu, publication, dateEdition, slugTitre) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  DEBUG - "ROLLBACK"
  CRITICAL - Uncaught PHP Exception Sonata\AdminBundle\Exception\ModelManagerException: "Failed to create object: Kark\RecetteBundle\Entity\Article" at /var/www/recette-etudiant/vendor/sonata-project/doctrine-orm-admin-bundle/Model/ModelManager.php line 142
  </code></pre>
  
  <p>UPDATE - </p>
  
  <p>I try to insert the traditional way, that is to say with an action in my ArticleController which reads:</p>
  
  <p>public function ajouterNewsAction($_local)
           {
               // The whole creation will be through this form 
               $monArticle = new Article();</p>
  
  <pre><code>         // We create our form using an external class 
           $monFormulaire = $this-&gt;createForm(new ArticleType, $monArticle);                   
  
         // Query is recovered 
         $request = $this-&gt;get('request');
  
           // When sending a form, it is realized through transfer data from page to page via a method 
      //called POST. So we'll check when calling this function if this method is effective, if the case is 
      //data that have been transmitted via a data form. 
         if($this-&gt;get('request')-&gt;getMethod() == 'POST')
         {
           // Process the data here we will moisturize our form with what was before retrieving values 
        // my $ _POST superglobal via a rather fast function
           $monFormulaire-&gt;bind($request);
  
           // Check that the values ​​entered are correct. Validation objects is via annotation 
        // Constraints our class Validator aliased via our @ Assert. 
           if($monFormulaire-&gt;isValid())
           {
  
  
              // If the item is actually add is that everything is good then created a Tag 
             $this-&gt;get('session')-&gt;getFlashBag()-&gt;add('AjoutRealise', 'L\'article a été rajouté avec succès');
  
  
              // Get the current utilistaeur 
             $user = $this-&gt;getUser();
  
             // We persist then our body hydrated by Form 
             $entity_manager = $this-&gt;getDoctrine()-&gt;getManager();
  
             // Get the service management of user FOSUserBundle
             $userManager = $this-&gt;get('fos_user.user_manager');
  
  
             //We add a user to our article
             $user-&gt;addArticle($monArticle);
             $userManager-&gt;updateUser($user);
  
             $entity_manager-&gt;flush();
  
             //We redirect to the page display section 
             return $this-&gt;redirect($this-&gt;generateUrl('karkrecette_voir_article', array("id" =&gt; $monArticle-&gt;getId(), "slugTitre" =&gt; $monArticle-&gt;getSlugTitre() )));
         }
       }
  
       // If we're not in the presence of a méthde get is that the form is not sent, then it is blank 
  //Otherwise it is possible that the form is not valid, it displays the form hydrating value previously entered 
       return $this-&gt;render('KarkRecetteBundle:Article:ajouter.html.twig', array("form" =&gt; $monFormulaire-&gt;createView(), "langue" =&gt; $_local));
       }
  </code></pre>
  
  <p>If i delete in the admin.yml the service defined for my administration of my Article class,
  their is no problem because the SonataAdmin is not fired. But i really NEED to administrate my Article object.</p>
  
  <p>Thanks.</p>