如何添加约束来上传图像,例如:max size,error message,sonata_media的配置中没有关于它的内容。
非常感谢你。答案 0 :(得分:1)
首先,您将使用 CompilerPassInterface 组件根据链接覆盖SonataMediaBundle的MediaAdmin类:
说你在AcmeDemoBundle:
<?php
namespace Acme\DemoBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class OverrideServiceCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition1 = $container->getDefinition('sonata.media.admin.media');
$definition1->setClass('Acme\DemoBundle\Admin\MediaAdmin');
}
}
其次,您将根据链接激活 CompilerPassInterface :
<?php
namespace Acme\DemoBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Acme\DemoBundle\DependencyInjection\OverrideServiceCompilerPass;
class AcmeDemoBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new OverrideServiceCompilerPass());
}
}
并在第三和最后您将根据链接覆盖 MediaAdmin 类 sonatamediabundle :
<?php
namespace Acme\DemoBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\MediaBundle\Provider\Pool;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\MediaBundle\Admin\BaseMediaAdmin as BaseAdmin;
use Sonata\MediaBundle\Form\DataTransformer\ProviderDataTransformer;
use Sonata\AdminBundle\Validator\ErrorElement;
class MediaAdmin extends BaseAdmin
{
// add this method
public function validate(ErrorElement $errorElement, $object)
{
$errorElement
->with('name')
->assertMaxLength(array('limit' => 32))
->end()
->with('description')
->assertNotNull(array())
->assertLength(array('min' => 2,
'max' => 50))
->end()
// remaining field here
;
}
}
现在您可以验证位于
中的SonataMediaBundle媒体类的剩余字段 Sonata\MediaBundle\Model\Media
这完全超出了需要..
答案 1 :(得分:0)
我最近在我的项目中遇到了这个问题。有我的小黑客(symfony 2.3):
use Symfony\Component\Validator\ExecutionContextInterface;
/**
* @ORM\Entity(repositoryClass="CMS\RequestBundle\Repository\RequestVideoRepository")
* @ORM\Table(name="request")
* @Assert\Callback(methods={"isMediaSizeValid"})
*
*/
class RequestVideo
{
属性
/**
* @ORM\OneToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media",cascade={"persist"})
*/
protected $file;
验证方法
/**
* @param ExecutionContextInterface $context
*/
public function isMediaSizeValid(ExecutionContextInterface $context)
{
if($this->getFile() && $this->getFile()->getSize() > 5242880){
$context->addViolationAt('file', 'File is too big. Please upload file less than 5MB', array(), null);
}
}
有点脏,但我没有找到任何东西来解决这个问题。我希望有人会提出比这更好的解决方案。