Search code examples
symfonyvichuploaderbundle

VichUploaderBundle raise error on delete/update product


i uses symfony 4 and VichUploaderBundle to handle images of my web-project. i did everything according to documentation

vich_uploader:
    db_driver: orm

    mappings:
        article_image:
            uri_prefix: /image/articles
            upload_destination: '%kernel.project_dir%/public/image/articles'

            inject_on_load: false
            delete_on_update: true
            delete_on_remove: true


class ArticleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('articleTitle')
            ->add('articleBody')
            ->add('thumbNumber')
            ->add('seoDescription')
            ->add('imageFile', VichImageType::class, [
                'required' => false,
                'allow_delete' => true,
                'download_label' => '...',
                'download_uri' => true,
                'image_uri' => true,
            ])
            ->add('save', SubmitType::class, array('label' => 'Создать статью'))
//            ->add('imageSize')
//            ->add('updatedAt')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Article::class,
        ]);
    }
}

/**
 * @Route("/gate/delete_article/{id}", name="delete_article")
 */
public function deleteArticle($id)
{
    $article = $this->getDoctrine()
        ->getRepository(Article::class)
        ->find($id);

    $entityManager = $this->getDoctrine()->getManager();
    $entityManager->remove($article);
    $entityManager->flush();

    return $this->redirectToRoute("gate");
}

I got an error telling me, that i have problem:

Argument 1 passed to App\Entity\Article::setArticleImage() must be of the type string, null given, called in 

So image deleted, but the rest of product is still in database.

public function setArticleImage(string $articleImage): self
    {
        $this->articleImage = $articleImage;

        return $this;
    }

If i set delete_on_update: true and delete_on_remove: true to false, the image will be stored(as aspected) and product deleted from database. So what should i do, to make deleting of image and product instance


Solution

  • It sounds to me like the application tries to correctly set articleImage to null, but you don't let it because of type hint. If you want to allow null values in setter, prefix type hint with ? (PHP 7.1+):

    public function setArticleImage(?string $articleImage): self
    {
        $this->articleImage = $articleImage;
        return $this;
    }
    

    http://php.net/manual/en/migration71.new-features.php#migration71.new-features.nullable-types