使用文件上载编辑表单后,文件“”不存在

时间:2018-02-08 20:08:13

标签: php symfony file-upload symfony-3.3

我正在尝试为我的Task实体上传文件。我使用两个来源: http://symfony.com/doc/3.4/controller/upload_file.htmlSymfony2 file upload step by step但我无法弄清楚如何在编辑过程中保留上传的文件。

我不确定我是否实施了正确的部分: enter image description here

当我尝试编辑任何任务时,我的表单抱怨:

  

表单的视图数据应该是类的实例   Symfony \ Component \ HttpFoundation \ File \ File,但是是一个(n)字符串。您   可以通过将“data_class”选项设置为null或by来避免此错误   添加一个视图转换器,将(n)字符串转换为实例   Symfony \ Component \ HttpFoundation \ File \ File。

所以我修改了我要扩展PDF文件的Task实体中的getter getBrochure()。请看下面我的getBrochure方法这是我的实体的代码:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Task
 *
 * @ORM\Table(name="task")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TaskRepository")
 */
class Task
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="datetime", type="datetime")
     */
    private $datetime;

    /**
     * @ORM\ManyToMany(targetEntity="Category", inversedBy="tasks")
     * @ORM\JoinTable(name="categories_tasks")
     */
    private $categories;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * @ORM\Column(type="string")
     *
     * @Assert\File(mimeTypes={ "application/pdf" })
     */
     private $brochure;


    public function __construct() {
        $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Task
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set datetime
     *
     * @param \DateTime $datetime
     *
     * @return Task
     */
    public function setDatetime($datetime)
    {
        $this->datetime = $datetime;

        return $this;
    }

    /**
     * Get datetime
     *
     * @return \DateTime
     */
    public function getDatetime()
    {
        return $this->datetime;
    }

    public function getCategories()
    {
        return $this->categories;
    }

    public function setCategories(Category $categories)
    {
        $this->categories = $categories;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function setDescription($description)
    {
        $this->description = $description;
    }

    public function getBrochure()
    {
        //return $this->brochure;
        return new File($this->brochure);
    }

    public function setBrochure($brochure)
    {
        $this->brochure = $brochure;

        return $this;
    }

    public function __toString() {
        return $this->name;
    }
}

?>

结果是我可以加载编辑页面,但文件上传字段为空,没有我上传任何文件的信息。我不确定是否应该有任何信息,但我在数据库中看到文件名在那里,并且在web文件夹中还有上传的文件。当我在任务中更改任何内容并清除文件保存时,当我尝试启动编辑页面时,我看到:

  

文件“”不存在

对我来说很清楚,因为此任务的文件列已被清除。那么,当我不想上传新文件时,如何在编辑期间保留文件?

这是我的TaskType

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Ivory\CKEditorBundle\Form\Type\CKEditorType;
use Symfony\Component\Form\Extension\Core\Type\FileType;

class TaskType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name')->add('datetime')->add('categories')
            ->add('description', 'Ivory\CKEditorBundle\Form\Type\CKEditorType', array())
            ->add('brochure', FileType::class, array('label' => 'Broszurka (PDF)', 'required' => false));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Task'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_task';
    }


}

这是我的TaskController(仅限编辑操作)

/**
 * Displays a form to edit an existing task entity.
 *
 * @Route("/{id}/edit", name="task_edit")
 * @Method({"GET", "POST"})
 */
public function editAction(Request $request, Task $task)
{
    $deleteForm = $this->createDeleteForm($task);
    $editForm = $this->createForm('AppBundle\Form\TaskType', $task);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('task_edit', array('id' => $task->getId()));
    }

    return $this->render('task/edit.html.twig', array(
        'task' => $task,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

任务实体:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Task
 *
 * @ORM\Table(name="task")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TaskRepository")
 */
class Task
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="datetime", type="datetime")
     */
    private $datetime;

    /**
     * @ORM\ManyToMany(targetEntity="Category", inversedBy="tasks")
     * @ORM\JoinTable(name="categories_tasks")
     */
    private $categories;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * @ORM\Column(type="string")
     *
     * @Assert\File(mimeTypes={ "application/pdf" })
     */
     private $brochure;


    public function __construct() {
        $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Task
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set datetime
     *
     * @param \DateTime $datetime
     *
     * @return Task
     */
    public function setDatetime($datetime)
    {
        $this->datetime = $datetime;

        return $this;
    }

    /**
     * Get datetime
     *
     * @return \DateTime
     */
    public function getDatetime()
    {
        return $this->datetime;
    }

    public function getCategories()
    {
        return $this->categories;
    }

    public function setCategories(Category $categories)
    {
        $this->categories = $categories;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function setDescription($description)
    {
        $this->description = $description;
    }

    public function getBrochure()
    {
        //return $this->brochure;
        return new File($this->brochure);
    }

    public function setBrochure($brochure)
    {
        $this->brochure = $brochure;

        return $this;
    }

    public function __toString() {
        return $this->name;
    }
}

?>

2 个答案:

答案 0 :(得分:0)

您应该检查文件然后,如果用户没有选择文件,请从数据库中选择文件名

 if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $form->handleRequest($request);
            $TaskRepo=$em->getRepository('AppBundle:Task');
            $Taskdata = $TaskRepo->find($id);///id task
            $Taskdata->setName($form->get('name')->getData());
            $Taskdata->setDescription($form->get('description(')->getData());
            $Taskdata->setDatetime(new \DateTime('now'));
    if($form->get('brochure')->getData() != ""){////Check the file selection status

             $file2 = $form->get('brochure')->getData();
             $fileName2 = md5(uniqid()).'.'.$file2->guessExtension();
             $file2->move(
             $this->getParameter('brochures_directory'), $fileName2);
             $Taskdata->setBrochure($fileName2);
        }
         $em->flush();
     } 

答案 1 :(得分:0)

好的,我在撰写评论并添加了任务实体代码几秒钟后发现了问题。在getBrochure方法中,我尝试为每个Task实例创建File对象,即使它没有任何小册子,所以解决方案是使用:

public function getBrochure()
{
    return $this->brochure;
    //return new File($this->brochure);
}