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
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.