donglu1472
2018-10-01 05:09
浏览 57
已采纳

如何在symfony中编辑上传的图像

I want to edit existing image but I could not update .Please can anyone help me.

I have used my form type in this way

$builder->add('picture', FileType::class,['label'=> 'Picture', 'required'=> false, 'data_class'=> null]);
    $builder->add('submit',SubmitType::class, ['label' => 'Submit', 'attr' => ['class'=>'contact100-form-btn']]);

I have following entity

 /**
 * @var string
 *
 * @ORM\Column(name="picture", type="string", length=255, nullable=true)
 *
 */
private $picture;

I have used my form handling in this way

$form = $this->createForm(userType::class, $userEntity, ['action'=>$actionUrl]);
    $form->handleRequest($request);
    if ($form->isSubmitted()) {
        dump($form->getData());die;}

Now when I am using this form in twig {{ form_widget(form.picture) }} the value is missing in input field <input type= "file" name= "picture"> I am not getting value of existing image on upload button.

controller for edit action

public function editUserData(Request $request, $id) {

    $userEntity = $this->get('app.manage.user_data')->getUserById($id);
    $actionUrl = $this->generateUrl('edit_user_data', ['id' => $id]);
    $form = $this->createForm(userType::class, $userEntity, ['action' => $actionUrl]);
    $form->handleRequest($request);
    if ($form->isSubmitted()) {
        dump($form->getData());die;
        $this->addOrEditUserData($userEntity, $form, $id);
        $this->addFlash("success", "Your have successfully changes data of id=" . $id);

        return $this->redirect($this->generateUrl('display_user_data'));
    }

    return $this->render('@LillyDoo/Narayan/_edit.userData.html.twig', [
        'form' => $form->createView()

    ]);
}

Please can any help me how I can update existing image.

Thanks

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doushizhou4477 2018-10-01 13:10
    已采纳

    here is an example for updating a file for a given entity : in your example , try this :

    In your entity :

    /**
     * @ORM\Column(type="string")
     * @Assert\File(mimeTypes={ "image/jpeg" , "image/png" , "image/tiff" , "image/svg+xml"})
     */
    private $picture;
    

    Here we are storing the name of the file as string in the database while the file is upload using for example a service that allow you to manage uploading files in a specific directory.

    your entity type :

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('picture', null , array("attr"=> array(), 'required' => false));
    }
    

    i set the second param to null because i have been specified that it will a file input in the entity annotation .

    we suppose that the files you upload are on the /web/uploads

    your controller should be seem somethign like :

    /**  
         *
         * @Route("/{id}/edit", name="your_route_name")
         * @Method({"GET", "POST"})
         */
        public function editAction(Request $request,$id)
        {
          $userEntity = $this->get('app.manage.user_data')->getUserById($id);
          $userEntity = $this->get('app.manage.user_data')->getUserById($id);
          $actionUrl = $this->generateUrl('edit_user_data', ['id' => $id]);
          $editForm= $this->createForm(userType::class, $userEntity, ['action' => 
        $actionUrl]);
    
    
          // we must transform the image string from Db  to File to respect the form types
           $oldFileName = $userEntity->getPicture();
           $oldFileNamePath = $this->get('kernel')->getRootDir().'/../web/uploads/'.$userEntity->getPicture();
           $pictureFile = new File($oldFileNamePath);
           $userEntity->setPicture($pictureFile );
    
           $editForm->handleRequest($request);
    
            if ($editForm->isSubmitted() && $editForm->isValid()) {
                /*
               *  it means that the user has been set a new picture
               *  else :
               *  we let the old picture
               */
                if($userEntity->getPicture()!=null){
                    $newLogoFile = $userEntity->getPicture();
                   $fileName = md5(uniqid()).'.'.$newLogoFile ->guessExtension();
    
                 $newLogoFile ->move($this->get('kernel')->getRootDir().'/../web/uploads/', $fileName);
                    $newFileName = $fileUploader->upload($newLogoFile);
                    $userEntity->setPicture($newFileName);
                    $fileUploader->deleteFile($oldFileNamePath);
                }
                /**
                 * setting the picturefile because the file is not set . we modify it using the old file name .
                 */
                else{
                    $userEntity->setPicture($oldFileName);
                }
                $this->getDoctrine()->getManager()->flush();
    
        }
    

    I hope that help you . if you still have problems , just comment

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongli7870 2018-10-01 06:38

    Because you specify data_class => null on "picture" input it will not map it to your entity, so remove it and it will work.

    If you do not want to have it mapped on the entity then pedram's comment is correct.

    See the docs for data_class at https://symfony.com/doc/3.4/forms.html#creating-form-classes -> Setting the data_class

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题