Vichuploaderbundle: Problem with Vichuploader and Symfony Validion

Created on 18 Mar 2019  路  6Comments  路  Source: dustin10/VichUploaderBundle

I put this question here, after no answer on stackoverflow.

I have this form, a report with oneToMany document attached

class ReportType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('documentDatas', CollectionType::class, array(
                'entry_type' => DocumentType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'label' => false
            ))
            ->add('comment', TextType::class, array(
            'label' => 'vat',
            'required' => false,
             ))
            ->add('save', SubmitType::class);
    }
}

and this is the document Type

class DocumentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('examDocument', VichImageType::class, array(
                'label' => 'examDocument',
                'data_class' => null,
                'attr' => array('class' => 'upload-image'),
            ))
            ->add('note', TextType::class, array(
                'label' => 'notes',
                'required' => false,
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Model\DocumentData',
        ));
    }
}

Where I use the VichImageType to upload. When the form validation is ok, all this go right, the file is uploaded and the document entities add in my DB.
But when some validation violated (on the document or on the comment) I receive this strange error:

The class "AppBundle\Model\DocumentData" is not uploadable. If you use
annotations to configure VichUploaderBundle, you probably just forgot
to add @Vich\Uploadable on top of your entity. If you don't use
annotations, check that the configuration files are in the right
place. In both cases, clearing the cache can also solve the issue.

I receive this when my action try response with the view, when form is not valid:

public function commentAction(Request $request) {
        $reportData = new ReportData();

    $form = $this->createForm(ReportType::class, $reportData);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()){

        //some logic
    }

    return $this->render('report/form.html.twig', [
        'form' => $form->createView(),  //symfony evidence this row in the exception
    ]);
}
Support

All 6 comments

Please provide your mapping

This is my document entity

/**
 * Document.
 *
 * @ORM\Entity
 * @Vich\Uploadable
 * @ORM\Table(name="documents")
 */
class Document
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;

    /**
     * @ORM\ManyToOne(targetEntity="Report", inversedBy="documents")
     * @ORM\JoinColumn(name="report_id", referencedColumnName="id", nullable = true)
     */
    private $record;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="document_file", fileNameProperty="examDocument")
     *
     * @var File
     */
    private $documentFile;

    /**
     * @var string
     *
     * @ORM\Column(name="exam_document", type="string", length=255, nullable = true)
     */
    private $examDocument;

    /**
     * @var string
     *
     * @ORM\Column(name="note", type="text", nullable = true)
     */
    private $note;

    /**
     * @var string
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    private $createdAt;
}

The stange things is that the error is refer to AppBundle\Model\DocumentData, when I use this model only for validation but the logic of Vichbundle is on entity Document.

Mapping the entity is not enough.
If you use a DTO, you need to map the DTO itself too

Ok, maybe I don't know well this part. I'm reading DTO doc and I never do this.

Maybe is implicit when I use del Model Data as validation? I never config some DTO, but ever use this pattern validation, also with upload file (but with other logic, not Vich).

Can you advice me some documentation or other for close this flux?

Question is: this bundle needs a mapped object for using its types in forms.
If you tie your form to an entity, the entity should be already mapped.
If instead you use a DTO, the DTO needs to be mapped.
Please notice that data transformers used in Symfony are not related to DTO, that is a more general topic.

Ok, I resolve adding the mapping in my model class, like this:

/**
 * @Vich\Uploadable
 */
class DocumentData
{
    /**
     * @Assert\NotNull()
     * @Assert\File(
     *     maxSize = "5M",
     *     mimeTypes = {"image/*", "application/pdf"}
     * )
     * @Vich\UploadableField(mapping="document_file", fileNameProperty="examDocument")
     */
    public $examDocument;

    /**
     * @Assert\Length(
     *      min = 2,
     *      max = 30,
     * )
     */
    public $note;

    public function getExamDocument()
    {
        return $this->examDocument;
    }

    public function setExamDocument($examDocument)
    {
        $this->examDocument = $examDocument;
    }

    public static function create(Document $document)
    {
        $edm = new static();
        $edm->examDocument = $document->getExamDocument();
        $edm->note = $document->getNote();

        return $edm;
    }
}

Thanks for the help!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

WassabiVl picture WassabiVl  路  3Comments

jcg678 picture jcg678  路  6Comments

manguecreative picture manguecreative  路  4Comments

smilesrg picture smilesrg  路  6Comments

webkmua picture webkmua  路  4Comments