Загрузка файла Sonata Admin из документации не работает - PullRequest
1 голос
/ 25 сентября 2019

Я пытаюсь загрузить файл с помощью SonataAdminBundle.

Я не знаю, что я делаю неправильно, поскольку я следовал инструкциям из официальной документации https://sonata -project.org / bundles / admin /3-x / doc / cookbook / recipe_file_uploads.html

Функция upload () не запускается, и даже когда я вызываю метод в DocumentAdmin, она не помещает файлы в указанный мной каталог.Кажется, что файл yaml даже не читается, но как мне его настроить?prePersist () и preUpdate () запускаются даже без него.

Код:

final class DocumentAdmin extends AbstractAdmin
{
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('title', null, [
                'label' => 'Name'
            ])
            ->add('documentCategory', null, [
                'label' => 'Typ'
            ])
            ->add('priority', null, [
                'label' => 'Order'
            ])
            ;
    }
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('file', FileType::class, [
                'required' => true,
            ])
            ->add('title', null, [
                'label' => 'Name'
            ])
            ->add('priority', null, [
                'label' => 'Priority'
            ])
            ->add('documentCategory', null, [
                'label' => 'Typ'
            ])
        ;
    }

    public function prePersist($document)
    {

        $this->manageFileUpload($document);
    }

    public function preUpdate($document)
    {

        $this->manageFileUpload($document);
    }

    private function manageFileUpload($document)
    {
        if ($document->getFile()) {
            $document->refreshUpdated();
        }
    }


    public function toString($object)
    {
        return $object instanceof Document
            ? $object->getTitle()
            : 'File'; // shown in the breadcrumb on the create view
    }

}

Сущность документа

class Document
{
    const SERVER_PATH_TO_DOCUMENTS_FOLDER = '%kernel.project_dir%/public/uploads';

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * Unmapped property to handle file uploads
     */
    private $file;

    /**
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
    }

    /**
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * Manages the copying of the file to the relevant place on the server
     */
    public function upload()
    {
        // the file property can be empty if the field is not required
        if (null === $this->getFile()) {
            return;
        }

        // we use the original file name here but you should
        // sanitize it at least to avoid any security issues

        // move takes the target directory and target filename as params
        $file = $this->getFile();
        $directory = self::SERVER_PATH_TO_DOCUMENTS_FOLDER;
        $originaName = $this->getFile()->getClientOriginalName();

//        dump($file);
//        dump($directory);
//        dump($originaName);
//        die();

        $file->move($directory, $originaName);

        // set the path property to the filename where you've saved the file

        // clean up the file property as you won't need it anymore
        $this->setFile(null);
    }

    /**
     * Lifecycle callback to upload the file to the server.
     */
    public function lifecycleFileUpload()
    {
        $this->upload();
    }

    /**
     * Updates the hash value to force the preUpdate and postUpdate events to fire.
     */
    public function refreshUpdated()
    {
        $this->setDateOfUpload(new \DateTime());
    }

    /**
     * @ORM\Column
     * @Gedmo\UploadableFileName
     */
    private $title;

    /**
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(type="datetime")
     */
    private $dateOfUpload;

    /**
     * @ORM\Column(type="smallint")
     */
    private $priority;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\DocumentCategory", inversedBy="documents")
     * @ORM\JoinColumn(nullable=false)
     */
    private $documentCategory;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getDateOfUpload()
    {
        return $this->dateOfUpload;
    }

    public function setDateOfUpload(\DateTimeInterface $dateOfUpload): self
    {
        $this->dateOfUpload = new \DateTime();

        return $this;
    }

    public function getPriority(): ?int
    {
        return $this->priority;
    }

    public function setPriority(int $priority): self
    {
        $this->priority = $priority;

        return $this;
    }

    public function getDocumentCategory(): ?DocumentCategory
    {
        return $this->documentCategory;
    }

    public function setDocumentCategory(?DocumentCategory $documentCategory): self
    {
        $this->documentCategory = $documentCategory;

        return $this;
    }

//    public function myCallbackMethod(array $info)
//    {
//    }

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

}

РЕДАКТИРОВАТЬ: Iизменил путь к каталогу файлов:
const SERVER_PATH_TO_DOCUMENTS_FOLDER = 'uploads/documents';, а также вызвал метод lifecycleFileUpload () в методе manageFileUpload (), и теперь файлы перемещаются в каталог.Это правильный способ загрузки?

...