2

我正在努力寻找一种方法来验证提交的奏鸣曲媒体类型表单。我的实体与具有一对一关系的媒体表相关。这是关系

 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'

我的表格在这里:

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

我尝试的验证:

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

最近几天,我在寻找解决方案方面的帮助减少了。因为如果我提交的不是图像文件。它抛出了两个异常RuntimeException& InvalidArgumentException。所以请帮助我!

4

3 回答 3

1

在您的validation.yml 文件中,您为以下内容创建了一个规则:图像、徽标和优惠组。但是在您的表单中,您将validation_groups 指定为默认值;因此,如果您想应用该规则,您需要:

将组添加到表单:

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

或者删除validation.yml的组:

- File: { mimeTypes: [ image/png ] }
于 2013-09-26T18:30:13.917 回答
1

有多种方法可以做到这一点

来自实体:

/**  
* @Assert\NotBlank() 
* @Assert\File(
*     maxSize = "5m",
*     mimeTypes = {"application/pdf", "application/x-pdf", "application/msword"},
* )  
* @ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"remove", "persist"}, fetch="LAZY")  */ 
protected $cv;

/**  
* @Assert\NotBlank()  
* @Assert\File(
*     maxSize = "5m",
*     mimeTypes = {"application/pdf", "application/x-pdf", "application/msword"},
* )  
* @ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"remove", "persist"}, fetch="LAZY")  */ 
protected $letter;

或者,从 Admin 类

<?php # Sapiens\Bundle\JobBundle\Form\Type\JobApplyType

public function validate(ErrorElement $errorElement, JobApply $jobApply)
{
    $errorElement
        ->with('cv.binaryContent')
            ->assertNotNull(array())
            ->assertNotBlank()
            ->assertFile(array('maxSize' => '3000000', 'mimeTypes' => array("application/pdf", "application/x-pdf", "application/msword")))
        ->end()
        ->with('letter.binaryContent')
            ->assertNotNull(array())
            ->assertNotBlank()
            ->assertFile(array('maxSize' => '3000000', 'mimeTypes' => array("application/pdf", "application/x-pdf", "application/msword")))
        ->end();
}
于 2016-10-20T10:55:00.763 回答
1

我想,可能是创建另一个提供程序并指定某些验证过程的情况。我将尝试通过png图像提供者(Symfony 4 兼容)解释我的愿景。

首先,创建提供者。它只是盒子中一些现有提供者的扩展(ImageProvider在这种情况下):

namespace App\Provider;

use Sonata\MediaBundle\Provider\ImageProvider;

class PngProvider extends ImageProvider
{
}

二、在services.yaml中定义DI配置:

sonata.media.provider.png:
    class: App\Provider\PngProvider
    tags:
        - { name: sonata.media.provider }
    arguments:
        - 'sonata.media.provider.png'
        - '@sonata.media.filesystem.local'
        - '@sonata.media.cdn.server'
        - '@sonata.media.generator.default'
        - '@sonata.media.thumbnail.format'
        - ['png']
        - ['image/png', 'image/x-png']
    calls:
      - [ setTemplates, [{"helper_view":"SonataMediaBundle:Provider:view_image.html.twig","helper_thumbnail":"SonataMediaBundle:Provider:thumbnail.html.twig"}]]

如您所见,最后两个参数定义了要上传的文件的文件扩展名和 mime 类型。

然后,为您的实体文件添加属性:

namespace App\Entity;

use App\Entity\Media; // or you Media class
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

class SomeEntity
{
    /**
     * @var Media
     * @Assert\Valid
     * @ORM\ManyToOne(targetEntity="Media", cascade={"all"})
     */
    private $pngFileProperty;

请注意@Assert\Valid媒体属性的限制,否则媒体文件在上传过程中会跳过验证。

现在您可以将您的提供程序与一些奏鸣曲媒体上下文一起使用:

sonata_media:
    contexts:
        some_context:
            providers:
                - sonata.media.provider.png
            formats: ~

例如,在表单类型中使用它:

use Sonata\MediaBundle\Form\Type\MediaType;
...
$builder->add('pngFileProperty', MediaType::class, [
    'context'  => 'some_context',
    'provider' => 'sonata.media.provider.png',
])

PngProvider::validate()您可以通过覆盖您的自定义提供程序的方法来提供一些额外的验证条件(最大文件大小或类似的东西) :

namespace App\Provider;

use Sonata\CoreBundle\Validator\ErrorElement;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\Provider\ImageProvider;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class PngProvider extends ImageProvider
{   
    const VERY_BIG_FILE = 100000; // bytes

    public function validate(ErrorElement $errorElement, MediaInterface $media)
    {
        parent::validate($errorElement, $media);

        if ($media->getBinaryContent() instanceof UploadedFile) {
            $size = $media->getBinaryContent()->getClientSize();
        } elseif ($media->getBinaryContent() instanceof File) {
            $size = $media->getBinaryContent()->getSize();
        } else {
            // parent would throw an Exception in this case so be happy, don't worry
        }

        if ($size > self::VERY_BIG_FILE) {
            $errorElement
                ->with('binaryContent')
                    ->addViolation('The file is too big, max size: '.self::VERY_BIG_FILE)
                ->end();
        }
    }
}
于 2018-06-21T09:13:17.557 回答