I am using SonataAdminBundle (with Doctrine2 ORM) and I have successfully added a file upload feature to my Picture model.
I would like, on the
The answer from @kkochanski is the cleanest way I found so far. Here a version ported to Symfony3. I also fixed some bugs.
Create a new template image.html.twig
for your new form type (full path: src/AppBundle/Resources/views/Form/image.html.twig
):
{% block image_widget %}
{% spaceless %}
{% set type = type|default('file') %}
{% if image_web_path is not empty %}
{% endif %}
{% endspaceless %}
{% endblock %}
Register the new form type template in your config.yml
:
twig:
form_themes:
- AppBundle::Form/image.html.twig
Create a new form type and save it as ImageType.php
(full path: src/AppBundle/Form/Type/ImageType.php
):
setDefaults(array(
'image_web_path' => ''
));
}
/**
* @param FormView $view
* @param FormInterface $form
* @param array $options
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['image_web_path'] = $options['image_web_path'];
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAttribute('image_web_path', $options['image_web_path'])
;
}
}
If you have done this. You can just import the new ImageType
in your entity admin class:
use AppBundle\Form\Type\ImageType
And then, finally use the new form type without any inline-html or boilerplate code in configureFormFields
:
$formMapper
->add('imageFile', ImageType::class, ['image_web_path' => $image->getImagePath()])
;
Instead of $image->getImagePath()
you have to call your own method that returns the url to your image.
Creating a new image entity using sonata admin:
Editing a image entity using sonata admin: