Sonata User Bundle Avatar using Sonata Media Bundle, in custom form while update image updates old one, and also creating a new one
<p>I'm working in Sonata User Bundle <strong>avatar</strong> using Sonata Media Bundle. Every thing works as expected in Sonata Admin(Backend). i.e while updating form admin, only the old file is replaced.(works good).</p>

<p><strong>Problem:</strong> While trying to edit user profile by custom form in frontend. The image uploads correctly and replacing the old one, <em>but it additonally creating a new image in file folder, also a new entry in media. Only the new image id is added to the user entry(avatar), instead of old one</em>. Normally only the old one will be used. </p>

<p><strong>What I need</strong> is to edit/update old image and not to add new image&amp;entry.</p>

<p><strong>HINT :</strong> Folder permission is good - because it edit old file.</p>

<p><strong>EXPECTED SOLUTION TO THE PROBLEM :</strong> How the new entry? instead of edit/update.!</p>

<p>User.php</p>

<pre><code>namespace Application\Sonata\UserBundle\Entity;
// all use ... i deleted to reduce lines
/**
* @ORM\Table(name="fos__user_user")
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
* @Assert\Callback(methods={ "isMediaSizeValid" })
*/
class User extends BaseUser {

/**
 * @var string
 *
 * @ORM\OneToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media",cascade={"persist"} )
 * @ORM\JoinColumns( { @ORM\JoinColumn( referencedColumnName="id", onDelete="CASCADE" ) } )
 * @Assert\NotNull()
 */
private $profilePicture;

// generated getter and setter
  public function setProfilePicture(\Application\Sonata\MediaBundle\Entity\Media $profilePicture = null) {
    $this-&gt;profilePicture = $profilePicture;
    return $this;
  }
  public function getProfilePicture() {
    return $this-&gt;profilePicture;
  }

  public function isMediaSizeValid(ExecutionContextInterface $context) {
    $this-&gt;fzValidateImage($context, $this-&gt;getProfilePicture());
  }

  private function fzValidateImage($context, $f) {
    if ($f == NULL) {
        // IMAGE can be null . If null it uses the default image             
    } else if ($f-&gt;getSize() &gt; (self::FILE_SIZE * 1024)) {
        $context-&gt;buildViolation('The file is too large ( %a% kb). Allowed maximum size is %b% kb.')-&gt;atPath(self::FILE_PATH)-&gt;setParameters(['%a%' =&gt; intval($f-&gt;getSize() / 1024), '%b%' =&gt; self::FILE_SIZE])-&gt;addViolation();
    } else if ($f-&gt;getWidth() &lt; self::FILE_MIN_WIDTH) {
        $context-&gt;buildViolation('The image width is too small ( %a% px). Minimum width expected is  %b% px.')-&gt;atPath(self::FILE_PATH)-&gt;setParameters(['%a%' =&gt; $f-&gt;getWidth(), '%b%' =&gt; self::FILE_MIN_WIDTH])-&gt;addViolation();
    } else if ($f-&gt;getWidth() &gt; self::FILE_MAX_WIDTH) {
        $context-&gt;buildViolation('The image width is too big ( %a% px). Allowed maximum width is  %b% px.')-&gt;atPath(self::FILE_PATH)-&gt;setParameters(['%a%' =&gt; $f-&gt;getWidth(), '%b%' =&gt; self::FILE_MAX_WIDTH])-&gt;addViolation();
    } else if ($f-&gt;getHeight() &lt; self::FILE_MIN_HEIGHT) {
        $context-&gt;buildViolation('The image height is too small ( %a% px). Minimum height expected is  %b% px.')-&gt;atPath(self::FILE_PATH)-&gt;setParameters(['%a%' =&gt; $f-&gt;getHeight(), '%b%' =&gt; self::FILE_MIN_HEIGHT])-&gt;addViolation();
    } else if ($f-&gt;getHeight() &gt; self::FILE_MAX_HEIGHT) {
        $context-&gt;buildViolation('The image height is too big ( %a% px). Allowed maximum height is  %b% px.')-&gt;atPath(self::FILE_PATH)-&gt;setParameters(['%a%' =&gt; $f-&gt;getHeight(), '%b%' =&gt; self::FILE_MAX_HEIGHT])-&gt;addViolation();
    }
  }
}
</code></pre>

<p><strong>UserController.php</strong> type 1</p>

<pre><code>    /**
     * @Route("/profile/edit", name="fz_user_profile_edit")
     */
    public function editProfileAction(Request $request) {
        $form = $this-&gt;get('sonata.user.profile.form');
        $form-&gt;add('profilePicture', 'sonata_media_type', array(
            'provider' =&gt; 'sonata.media.provider.image',
            'context' =&gt; 'profile'
        ));
        $form-&gt;get('profilePicture')-&gt;add('binaryContent', 'file', ['label' =&gt; 'Profile Picture']);
        $form-&gt;get('profilePicture')-&gt;remove('unlink');
        $formHandler = $this-&gt;get('sonata.user.profile.form.handler');

        $process = $formHandler-&gt;process($user);
        if ($process) {
            $this-&gt;setFlash('notice', 'Profile updated!');
            return $this-&gt;redirectToRoute('fz_user');
        }
        $x = ['cmf' =&gt; '', 'pTitle' =&gt; 'Profile'];
        return $this-&gt;render('user/layout.html.twig', ['x' =&gt; $x, 'form' =&gt; $form-&gt;createView()]);
</code></pre>

<p><strong>UserController.php</strong> type 2</p>

<pre><code>/**
 * @Route("/profile/edit", name="fz_user_profile_edit")
 */
public function editProfileAction(Request $request) {
    $user = $this-&gt;getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw $this-&gt;createAccessDeniedException('This user does not have access to this section.');
    }
    $builder = $this-&gt;createFormBuilder($user);
    $builder-&gt;add('profilePicture', 'sonata_media_type', array(
        'provider' =&gt; 'sonata.media.provider.image',
        'context' =&gt; 'profile'
    ));
    $form = $builder-&gt;getForm();
    $form-&gt;handleRequest($request);
    if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
        $em = $this-&gt;getDoctrine()-&gt;getManager();
        $em-&gt;persist($user);
        $em-&gt;flush();
        $this-&gt;setFlash('notice', 'Profile updated!');
    }

    $x = ['cmf' =&gt; '', 'pTitle' =&gt; 'Profile'];
    return $this-&gt;render('user/layout.html.twig', ['x' =&gt; $x, 'form' =&gt; $form-&gt;createView()]);
}
</code></pre>

<p>UserController.php type 1 - code is using FOSUserBundle. and UserController.php type 2 my custom code for symfony doc..</p>