1

I can't figure out how to display an image uploaded via EasyAdmin. When it uploads the image it displays an absolute path on the server and stores the whole thing together with the filename to the database, so it can't be used for the html <img> tag.

How can I store a relative path to the image instead? Or do I need to apply some filter in twig to display it?

I have an EasyAdmin form with a field:

- { property: 'imageFile', type: 'file_upload', type_options: { upload_dir: '/public/data/gallery/images/', upload_filename: '[uuid]-[timestamp].[extension]'}}

I am using an inbuilt EasyAdmin file uploader, not a separate Bundle or Service: https://symfony.com/doc/current/bundles/EasyAdminBundle/book/edit-new-configuration.html#file-upload

3
  • Check out this link regarding file upload in symfony. You can then use this solution with easyadmin or use a dedicated bundle. Commented Mar 31, 2020 at 8:04
  • Just check the documentation Commented Mar 31, 2020 at 10:36
  • I am not using VichUploader nor a custom Service - I am using EasyAdmin inbuilt file uploader. I will add a link to the question. Commented Apr 1, 2020 at 11:44

1 Answer 1

3

You can fix this using a virtual field property, manipulating the data before saving/retrieving the real field.

This is my field definition in easy_admin.yaml:

 - { property: 'virtualFilename', type: 'file_upload', type_options: {upload_dir: 'public/imageswerk',upload_filename: '[uuid].[extension]' }}

And this is how my setters/getters look in the Entity:

    /**
     * @var string
     *
     * @ORM\Column(name="filename", type="string", length=80, nullable=false)
     */
    private $filename;

    /**
     * @return string|null
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * @param string $filename
     */
    public function setFilename(string $filename)
    {
        $this->filename = $filename;
    }

    public function getVirtualFilename()
    {
        //Set path for easyadmin
        return realpath(__DIR__.'/../../public/imageswerk/'.$this->filename);
    }

    public function setVirtualFilename($filename)
    {
        //Only keep last part of filepath
        $this->setFilename(basename($filename));
    }

I'm setting a manual path in getVirtualFilename, but ideally you would inject something like the %project_dir% or something to prevent hardcoded paths like this.

Sign up to request clarification or add additional context in comments.

1 Comment

Just a note: the getter for the virtual path needs to be returning NULL instead of FALSE if there is no image - otherwise an error is thrown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.