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

后端 未结 7 2143
广开言路
广开言路 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 20:46

    Teo.sk wrote the method of showing images using VichUploader. I found an option which allow you to show images without this bundle.

    First we need to create our form_type. There is tutorial: symfony_tutorial

    In main Admin class:

    namespace Your\Bundle;
    
    //.....//
    
    class ApplicationsAdmin extends Admin {
    
    //...//
    
    public function getFormTheme() {
        return array_merge(
            parent::getFormTheme(),
            array('YourBundle:Form:image_type.html.twig') //your path to form_type template
        );
    
    protected function configureFormFields(FormMapper $formMapper)
    {
         $formMapper->add('file_photo', 'image', array(
                'data_class' => 'Symfony\Component\HttpFoundation\File\File',
                'label' => 'Photo',
                'image_web_path' => $this->getRequest()->getBasePath().'/'.$subject->getWebPathPhoto()// it's a my name of common getWebPath method
            ))
            //....//
            ;
    }
    
    }
    

    Next part is a code from ImageType class.

    namespace Your\Bundle\Form\Type;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
    use Symfony\Component\OptionsResolver\Options;
    use Symfony\Component\Form\FormView;
    use Symfony\Component\Form\FormInterface;
    use Symfony\Component\Form\FormBuilder;
    use Symfony\Component\Form\FormBuilderInterface;
    
    
    class ImageType extends AbstractType
    {
    
        public function getParent()
        {
            return 'file';
        }
    
        public function getName()
        {
            return 'image';
        } 
    
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'image_web_path'         => ''
            ));
        }
    
        public function buildView(FormView $view, FormInterface $form, array $options)
        {
            $view->vars['image_web_path'] = $options['image_web_path'];
        }
    
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                 ->setAttribute('image_web_path', $options['image_web_path'])
            ;
        }
    }
    

    And on the end time for image_type twig template.

    {% block image_widget %}
    {% spaceless %}
        {% set type = type|default('file') %}
        
        image_photo
    {% endspaceless %}
    {% endblock %}
    

    For me it's working! I'm also using avalanche bundle to resize images.

提交回复
热议问题