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

时间:2018-10-01 05:09:07

标签: php symfony twig

我想编辑现有图像,但无法更新。任何人都可以帮助我。

我以这种方式使用了表单类型

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

我有以下实体

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

我以这种方式使用了表单处理

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

现在,当我在树枝{{ form_widget(form.picture) }}中使用此表单时,在输入字段<input type= "file" name= "picture">中缺少值,我没有在上传按钮上获得现有图像的值。

编辑动作的控制器

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()

    ]);
}

请帮助我如何更新现有图像。

谢谢

2 个答案:

答案 0 :(得分:0)

由于您在“图片”输入中指定了data_class => null,因此不会将其映射到您的实体,因此将其删除即可。

如果您不想将其映射到实体上,那么pedram的注释是正确的。

https://symfony.com/doc/3.4/forms.html#creating-form-classes->设置data_class上查看data_class的文档

答案 1 :(得分:0)

这是为给定实体更新文件的示例: 在您的示例中,请尝试以下操作:

在您的实体中:

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

在这里,我们在使用文件上传服务(例如,允许您管理特定目录中的文件上传服务)时将文件名作为字符串存储在数据库中。

您的实体类型:

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

我将第二个参数设置为null,因为已经指定我将在实体注释中输入文件。

  

我们假设您上传的文件位于/ web / uploads

您的控制器应该看起来像:

/**  
     *
     * @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();

    }

希望对您有所帮助。如果仍有问题,请发表评论