Search code examples
symfonysymfony-sonata

How to validation to sonata media type in symfony 2


I'm trying hard to find out a way to validate sonata media type form filed. My entity is related to media table with one-to-one relation . Here is relation

 oneToOne:
  user:
    targetEntity: Sinepulse\UserBundle\Entity\User
    mappedBy: profile_info
    cascade: [all]
  profile_image:
    targetEntity: Sinepulse\Sonata\MediaBundle\Entity\Media
    cascade:      [ all ]
    joinColumn:
        name: profile_image_id
        referencedColumnName: id
        nullable: true
        onDelete: 'SET NULL'

My Form here:

                ->add('profile_image', 'sonata_media_type', array(
                'provider' => 'sonata.media.provider.image',
                'context' => 'user',
                'required'=>false,
                'validation_groups' => 'Default'
            ))

My attempted validation:

    profile_image:
    - File: { mimeTypes: [ image/png ], groups: [image,logo, offer] } 

I am help less last few day for finding the solution. Because If I submit other than image file. It threw two exception RuntimeException & InvalidArgumentException. So please help me!


Solution

  • In your validation.yml file you created a rule only for: image, logo and offer groups. But in your form you specify the validation_groups to Default; so if you want to apply that rule, you need to:

    Add the group to the form:

    ->add('profile_image', 'sonata_media_type', array(
        // ...
        'validation_groups' => array('Default', 'image') // or logo or offer
    ))
    

    Or remove the groups of the validation.yml:

    - File: { mimeTypes: [ image/png ] }