title: Symfony2: do not update a form field if not provided
body: <p>I have a form for my "Team" entity. This entity has an "image" field. This field is required on creation process, but not required on edit process. But right now, during edit process, if I don't provide any image in the file input, the empty input is still persisted, and so my database field is emptied during the process. 
  How can I do to avoid persistence of this field, if nothing is provided in the form file input? So the entity keeps its old value for this field. Of course, if a file is provided, I want him to erase the old one.</p>
  
  <p>My controller looks like this:</p>
  
  <pre><code>if ($request-&gt;getMethod() == 'POST') {
  
      $form-&gt;bind($request);
  
      if ($form-&gt;isValid()) {
  
          $em-&gt;persist($team);
          $em-&gt;flush();
          ...
      }
  }
  </code></pre>
  
  <p>and part of my entity, dealing with image (I'm pretty sure I have to do something in here, but don't know what exactly):</p>
  
  <pre><code>/**
   * @ORM\PrePersist()
   * @ORM\PreUpdate()
   */
  public function uploadImage() {
      // the file property can be empty if the field is not required
      if (null === $this-&gt;image) {
          return;
      }
      if(!$this-&gt;id){
          $this-&gt;image-&gt;move($this-&gt;getTmpUploadRootDir(), $this-&gt;image-&gt;getClientOriginalName());
      }else{
          $this-&gt;image-&gt;move($this-&gt;getUploadRootDir(), $this-&gt;image-&gt;getClientOriginalName());
      }
      $this-&gt;setImage($this-&gt;image-&gt;getClientOriginalName());
  }
  </code></pre>
  
  <hr>
  
  <p><strong>EDIT</strong></p>
  
  <p>Ok, I did some changes to <a href="https://stackoverflow.com/a/22558473/4257747">this answer's code</a> code, because apparently the event listener asks for a <code>FormEvent</code> instance in his callback, not a <code>FormInterface</code> instance.</p>
  
  <pre><code>$builder-&gt;addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
  // Retrieve submitted data
  $form = $event-&gt;getForm();
  $item = $event-&gt;getData();
  
  // Test if upload image is null (maybe adapt it to work with your code)
  if (null !== $form-&gt;get('image')-&gt;getData()) {
      var_dump($form-&gt;get('image')-&gt;getData());
      die('image provided');
      $item-&gt;setImage($form-&gt;get('image')-&gt;getData());
  }
  </code></pre>
  
  <p>});</p>
  
  <p>When I provide an image, the script goes into the test, and <code>die()</code>, as expected. When I do not provide any file, the script doesn't go into the test <code>if()</code>, but my field in the database is still erased with an empty value. Any idea?</p>
  
  <p>And as asked below, here is the Form </p>
  
  <pre><code>// src/Van/TeamsBundle/Form/TeamEditType.php
  
  namespace Van\TeamsBundle\Form;
  
  use Symfony\Component\Form\FormBuilderInterface;
  use Symfony\Component\OptionsResolver\OptionsResolverInterface;
  use Symfony\Component\Form\FormEvent;
  use Symfony\Component\Form\FormEvents;
  
  class TeamEditType extends TeamType // Ici, on hÃ©rite de ArticleType
  {
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          // On fait appel Ã  la mÃ©thode buildForm du parent, qui va ajouter tous les champs Ã  $builder
          parent::buildForm($builder, $options);
          // On supprime celui qu'on ne veut pas dans le formulaire de modification
          $builder-&gt;remove('image')
          -&gt;add('image', 'file', array(
              'data_class' =&gt; null,
              'required' =&gt; false
          ))
          ;
  
  
          $builder-&gt;addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
              // Retrieve submitted data
              $form = $event-&gt;getForm();
              $item = $event-&gt;getData();
  
              // Test if upload image is null (maybe adapt it to work with your code)
              if (null !== $form-&gt;get('image')-&gt;getData()) {
                  var_dump($form-&gt;get('image')-&gt;getData());
                  die('image provided');
                  $item-&gt;setImage($form-&gt;get('image')-&gt;getData());
              }
          });
  
  
      }
  
      // On modifie cette mÃ©thode car les deux formulaires doivent avoir un nom diffÃ©rent
      public function getName()
      {
          return 'van_teamsbundle_teamedittype';
      }
  }
  </code></pre>
  
  <p>and the whole Team entity:</p>
  
  <pre><code>&lt;?php
  
  namespace Van\TeamsBundle\Entity;
  
  use Doctrine\ORM\Mapping as ORM;
  use Symfony\Component\Validator\Constraints as Assert;
  
  /**
   * Team
   *
   * @ORM\Table()
   * @ORM\HasLifecycleCallbacks
   * @ORM\Entity
   * @ORM\Entity(repositoryClass="Van\TeamsBundle\Entity\TeamRepository") @ORM\Table(name="van_teams")
   */
  class Team
  {
      /**
       * @var integer
       *
       * @ORM\Column(name="id", type="integer")
       * @ORM\Id
       * @ORM\GeneratedValue(strategy="AUTO")
       */
      private $id;
  
      /**
       * @var string
       *
       * @ORM\Column(name="name", type="string", length=100)
       */
      private $name;
  
      /**
       * @var string
       *
       * @ORM\Column(name="countryCode", type="string", length=2)
       */
      private $countryCode;
  
      /**
       * @ORM\ManyToOne(targetEntity="Van\TeamsBundle\Entity\Game")
       * @ORM\JoinColumn(nullable=false)
       */
      private $game;
  
      /**
       * @ORM\ManyToOne(targetEntity="Van\TeamsBundle\Entity\Statut")
       * @ORM\JoinColumn(nullable=false)
       */
      private $statut;
  
      /**
       * @var string $image
       * @Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
       * @ORM\Column(name="image", type="string", length=255)
       */
      private $image;
  
  
  
      /**
       * Get id
       *
       * @return integer 
       */
      public function getId()
      {
          return $this-&gt;id;
      }
  
      /**
       * Set name
       *
       * @param string $name
       * @return Team
       */
      public function setName($name)
      {
          $this-&gt;name = $name;
  
          return $this;
      }
  
      /**
       * Get name
       *
       * @return string 
       */
      public function getName()
      {
          return $this-&gt;name;
      }
  
      /**
       * Set countryCode
       *
       * @param string $countryCode
       * @return Team
       */
      public function setCountryCode($countryCode)
      {
          $this-&gt;countryCode = $countryCode;
  
          return $this;
      }
  
      /**
       * Get countryCode
       *
       * @return string 
       */
      public function getCountryCode()
      {
          return $this-&gt;countryCode;
      }
  
      /**
       * Set image
       *
       * @param string $image
       * @return Team
       */
      public function setImage($image)
      {
          $this-&gt;image = $image;
  
          return $this;
      }
  
      /**
       * Get image
       *
       * @return string 
       */
      public function getImage()
      {
          return $this-&gt;image;
      }
  
      /**
       * Set game
       *
       * @param \Van\TeamsBundle\Entity\Game $game
       * @return Team
       */
      public function setGame(\Van\TeamsBundle\Entity\Game $game)
      {
          $this-&gt;game = $game;
  
          return $this;
      }
  
      /**
       * Get game
       *
       * @return \Van\TeamsBundle\Entity\Game 
       */
      public function getGame()
      {
          return $this-&gt;game;
      }
  
      /**
       * Set statut
       *
       * @param \Van\TeamsBundle\Entity\Statut $statut
       * @return Team
       */
      public function setStatut(\Van\TeamsBundle\Entity\Statut $statut)
      {
          $this-&gt;statut = $statut;
  
          return $this;
      }
  
      /**
       * Get statut
       *
       * @return \Van\TeamsBundle\Entity\Statut 
       */
      public function getStatut()
      {
          return $this-&gt;statut;
      }
  
  
  
  
  
  
      public function getFullImagePath() {
          return null === $this-&gt;image ? null : $this-&gt;getUploadRootDir(). $this-&gt;image;
      }
  
      protected function getUploadRootDir() {
          // the absolute directory path where uploaded documents should be saved
          // return $this-&gt;getTmpUploadRootDir();
          return __DIR__ . '/../../../../web/uploads/';
      }
  
      protected function getTmpUploadRootDir() {
          // the absolute directory path where uploaded documents should be saved
          return __DIR__ . '/../../../../web/uploads_tmp/';
      }
  
      /**
       * @ORM\PrePersist()
       * @ORM\PreUpdate()
       */
      public function uploadImage() {
          // the file property can be empty if the field is not required
          if (null === $this-&gt;image) {
              return;
          }
          if(!$this-&gt;id){
              $this-&gt;image-&gt;move($this-&gt;getTmpUploadRootDir(), $this-&gt;image-&gt;getClientOriginalName());
          }else{
              $this-&gt;image-&gt;move($this-&gt;getUploadRootDir(), $this-&gt;image-&gt;getClientOriginalName());
          }
          $this-&gt;setImage($this-&gt;image-&gt;getClientOriginalName());
      }
  
      /**
       * @ORM\PostPersist()
       */
      public function moveImage()
      {
          if (null === $this-&gt;image) {
              return;
          }
          if(!is_dir($this-&gt;getUploadRootDir())){
              mkdir($this-&gt;getUploadRootDir());
          }
          copy($this-&gt;getTmpUploadRootDir().$this-&gt;image, $this-&gt;getFullImagePath());
          unlink($this-&gt;getTmpUploadRootDir().$this-&gt;image);
      }
  
      /**
       * @ORM\PreRemove()
       */
      public function removeImage()
      {
          unlink($this-&gt;getFullImagePath());
          rmdir($this-&gt;getUploadRootDir());
      }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>I did that. When I provide an image, it is saved in the image field in the database and redirection to my index page occurs. When I don't provide any image, redirection doesn't occur, and the following message appears above my file input in my form: "The file could not be found." In my <code>TeamEditType</code> class, I did the following, so the image should not be required.     </p>
  
  <pre><code>$builder-&gt;remove('image')
  -&gt;add('image', 'file', array(
      'data_class' =&gt; null,
      'required' =&gt; false
  ))
  ;
  </code></pre>