Symfony 2 | Form exception when modifying an object that has a file(picture) field

前端 未结 3 1358
鱼传尺愫
鱼传尺愫 2021-02-01 06:51

I\'m using Symfony2. I have an entity Post that has a title and a picture field.

My problem : Everything is fine when I create a post, I have my picture e

相关标签:
3条回答
  • 2021-02-01 07:22

    I would recommend you to read the documentation of file upload with Symfony and Doctrine How to handle File Uploads with Doctrine and a strong recommendation to the part Lifecycle callbacks

    In a brief you usually in the form use the 'file' variable (see documentation), you can put a different label through the options, then in your 'picture' field, you just store the name of the file, because when you need the src file you can just call getWebpath() method.

    ->add('file', 'file', array('label' => 'Post Picture' )
    );
    

    to call in your twig template

    <img src="{{ asset(entity.webPath) }}" />
    
    0 讨论(0)
  • 2021-02-01 07:30

    Please make below change in your PostType.php.

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('title')
        ->add('picture', 'file', array(
                'data_class' => 'Symfony\Component\HttpFoundation\File\File',
                'property_path' => 'picture'
            )
        );
    }
    
    0 讨论(0)
  • 2021-02-01 07:38

    I solved the problem setting data_class to null as follows:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('title')
        ->add('picture', 'file', array('data_class' => null)
        );
    }
    
    0 讨论(0)
提交回复
热议问题