How to display the current picture above the upload field in SonataAdminBundle?

后端 未结 7 2048
广开言路
广开言路 2021-02-01 20:31

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

7条回答
  •  借酒劲吻你
    2021-02-01 21:03

    Solution for Symfony3

    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 %}
                image_photo
            {% 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.

    Screenshots

    Creating a new image entity using sonata admin:

    Editing a image entity using sonata admin:

提交回复
热议问题