回答
要使用你需要重寫奏鳴曲媒體ImageProvider
類奏鳴曲媒體驗證圖像尺寸,索納塔使用這個類來處理圖像manipulation.If你已經有了奏鳴曲媒體捆綁的extended bundle然後services.yml文件你可以如下定義自己的供應商,請確保您的YML文件包含在主config.yml
parameters:
sonata.media.provider.file.class: Application\Sonata\MediaBundle\Provider\ImageProvider
現在創建您的供應商,並與奏鳴曲媒體ImageProvider
擴展它置換器validate()
功能和定義自己的驗證,或者可以覆蓋buildCreateForm()/buildEditForm()
並定義你的斷言binaryContent
字段
namespace Application \ Sonata \ MediaBundle \ Provider;
//... other uses classes
use Sonata\MediaBundle\Provider\ImageProvider as BaseProvider;
class ImageProvider extends BaseProvider
{
public function __construct($name, Filesystem $filesystem, CDNInterface $cdn, GeneratorInterface $pathGenerator, ThumbnailInterface $thumbnail, array $allowedExtensions = array(), array $allowedMimeTypes = array(), MetadataBuilderInterface $metadata = null)
{
parent::__construct($name, $filesystem, $cdn, $pathGenerator, $thumbnail);
$this->allowedExtensions = $allowedExtensions;
$this->allowedMimeTypes = $allowedMimeTypes;
$this->metadata = $metadata;
}
/**
* {@inheritdoc}
*/
public function validate(ErrorElement $errorElement, MediaInterface $media)
{
if (!$media->getBinaryContent() instanceof \SplFileInfo) {
return;
}
if ($media->getBinaryContent() instanceof UploadedFile) {
$fileName = $media->getBinaryContent()->getClientOriginalName();
} elseif ($media->getBinaryContent() instanceof File) {
$fileName = $media->getBinaryContent()->getFilename();
} else {
throw new \RuntimeException(sprintf('Invalid binary content type: %s', get_class($media->getBinaryContent())));
}
if (!in_array(strtolower(pathinfo($fileName, PATHINFO_EXTENSION)), $this->allowedExtensions)) {
$errorElement
->with('binaryContent')
->addViolation('Invalid extensions')
->end();
}
if (!in_array($media->getBinaryContent()->getMimeType(), $this->allowedMimeTypes)) {
$errorElement
->with('binaryContent')
->addViolation('Invalid mime type : ' . $media->getBinaryContent()->getMimeType())
->end();
}
if ($media->getWidth() > '1280' || $media->getHeight() > 1280) {
$errorElement
->with('binaryContent')
->addViolation('Invalid File Dimension : Please upload 1280px * (1280px) image')
->end();
}
}
}
* @Assert\Image(
* minWidth = 200,
* maxWidth = 400,
* minHeight = 200,
* maxHeight = 400
*)
您可以爲Entity添加Assert註解。請看:http://symfony.com/doc/current/reference/constraints/Image.html
註釋驗證在SonataMedia領域不工作。 –
此代碼適用於我。 僅在MyBundle中使用SonataMedia(此處爲AppBundle)。我在SonataUserBundle(Application \ Sonata \ UserBundle \ Entity)中使用了相同的代碼。但它失敗了。
實體:
<?php
// To reduce code i deleted many lines
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* FZHomeSlider
*
* @ORM\Table(name="fz__home_slider")
* @ORM\Entity(repositoryClass="AppBundle\Repository\FZHomeSliderRepository")
* @ORM\HasLifecycleCallbacks()
* @Assert\Callback(methods={ "isMediaSizeValid" })
*/
class FZHomeSlider {
const FILE_PATH = 'image';
const FILE_SIZE = 200; # kb
const FILE_MIN_WIDTH = 1024;
const FILE_MAX_WIDTH = 1024;
const FILE_MIN_HEIGHT = 250;
const FILE_MAX_HEIGHT = 250;
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\OneToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media")
* @ORM\JoinColumns({ @ORM\JoinColumn(referencedColumnName="id", onDelete="CASCADE") })
* @Assert\NotNull()
*/
private $image;
/**
* Set image
*
* @param \Application\Sonata\MediaBundle\Entity\Media $image
*
* @return FZHomeSlider
*/
public function setImage(\Application\Sonata\MediaBundle\Entity\Media $image = null) {
$this->image = $image;
return $this;
}
/**
* Get image
*
* @return \Application\Sonata\MediaBundle\Entity\Media
*/
public function getImage() {
return $this->image;
}
/**
* @param ExecutionContextInterface $context Description
*/
public function isMediaSizeValid(ExecutionContextInterface $context) {
$this->fzValidateImage($context, $this->getImage());
}
private function fzValidateImage($context, $f) {
if ($f == NULL) {
$context->buildViolation('Please select an image.')->atPath(self::FILE_PATH)->addViolation();
} else if ($f->getSize() > (self::FILE_SIZE * 1024)) {
$context->buildViolation('The file is too large (%a% kb). Allowed maximum size is %b% kb.')->atPath(self::FILE_PATH)->setParameters(['%a%' => intval($f->getSize()/1024), '%b%' => self::FILE_SIZE])->addViolation();
} else if ($f->getWidth() < self::FILE_MIN_WIDTH) {
$context->buildViolation('The image width is too small (%a% px). Minimum width expected is %b% px.')->atPath(self::FILE_PATH)->setParameters(['%a%' => $f->getWidth(), '%b%' => self::FILE_MIN_WIDTH])->addViolation();
} else if ($f->getWidth() > self::FILE_MAX_WIDTH) {
$context->buildViolation('The image width is too big (%a% px). Allowed maximum width is %b% px.')->atPath(self::FILE_PATH)->setParameters(['%a%' => $f->getWidth(), '%b%' => self::FILE_MAX_WIDTH])->addViolation();
} else if ($f->getHeight() < self::FILE_MIN_HEIGHT) {
$context->buildViolation('The image height is too small (%a% px). Minimum height expected is %b% px.')->atPath(self::FILE_PATH)->setParameters(['%a%' => $f->getHeight(), '%b%' => self::FILE_MIN_HEIGHT])->addViolation();
} else if ($f->getHeight() > self::FILE_MAX_HEIGHT) {
$context->buildViolation('The image height is too big (%a% px). Allowed maximum height is %b% px.')->atPath(self::FILE_PATH)->setParameters(['%a%' => $f->getHeight(), '%b%' => self::FILE_MAX_HEIGHT])->addViolation();
}
}
}
在管理員:
$formMapper
->with('Media')
->add('image', 'sonata_type_model_list', ['btn_delete' => false, 'help' => self::$FORM_IMG_HELP, 'required' => false], ['link_parameters' => ['provider' => 'sonata.media.provider.image', 'context' => 'home_slider']])->end()
終於解決&的解決方案:
UserAdmin
public function getFormBuilder() {
$this->formOptions['data_class'] = $this->getClass();
$options = $this->formOptions;
$options['validation_groups'] = "";
$formBuilder = $this->getFormContractor()->getFormBuilder($this->getUniqid(), $options);
$this->defineFormBuilder($formBuilder);
return $formBuilder;
}
public function validate(ErrorElement $errorElement, $object) {
// throw new \Exception("bingo");
$errorElement
->with('phone')
->assertLength(['min' => 10, 'max' => '14', 'minMessage' => "Phone number must be at least {{ limit }} characters long", 'maxMessage' => "Phone number cannot be longer than {{ limit }} characters"])
->end()
;
}
這裏驗證電話僅供參考。您也可以使用validation.yml文件進行驗證。
應用/索納塔/ UserBundle /資源/配置/ validation.yml
Application\Sonata\UserBundle\Entity\User:
properties:
phone:
- Length:
min: 10
minMessage: "Phone number must be at least {{ limit }} characters long"
max: 13
maxMessage: "Phone number cannot be longer than {{ limit }} characters"
- Regex:
pattern: "/^[\d]{10,13}$/"
biography:
- Length:
min: 5
minMessage: "Biography must be at least {{ limit }} characters long"
max: 7
maxMessage: "Biography cannot be longer than {{ limit }} characters"
# image:
# - Image validation is done in Entity
$ options ['validation_groups'] = 「」;是主要的事情。 –
你能否用最初的問題的一個實例來完成你的最終安澤?謝謝 –
@jjgarcíaAppBundle \ Entity \ FZHomeSlider檢查註釋行* @Assert \ Callback(methods = {「isMediaSizeValid」})這指向函數/方法isMediaSizeValid。在ADMIN AppBundle \ Admin \ FZHomeSliderAdmin中,請參閱getFormBuilder(){$ options ['validation_groups'] =「」;}。我解決了這個問題,完成代碼如上,如果有人需要更多的細節,請讓我知道.. –
- 1. 索納塔管理員捆綁電子郵件驗證
- 2. 索納塔媒體庫
- 3. 索納塔管理員表單集合
- 4. 索納塔管理員一般角色
- 5. 索納塔管理員捆綁翻譯
- 6. Symfony2的索納塔管理員錯誤
- 7. 的Symfony2 - 索納塔管理員 - 場
- 8. 索納塔管理員,自定義flashBag
- 9. 根據管理員(索納塔管理員)的角色
- 10. 索納塔管理員,編輯實體內嵌
- 11. 索納塔管理包 - 字符串驗證
- 12. 索納塔媒體包安裝錯誤
- 13. 整合索納塔媒體包(媒體實體)和索納塔Classiffication包(標籤實體)
- 14. 查詢在索納塔管理
- 15. 標籤在索納塔管理員捆綁
- 16. 索納塔管理員,重寫在模板中選擇?
- 17. 索納塔管理員:在編輯頁面列出一對多
- 18. 索納塔管理員:在創建項目
- 19. 索納塔管理軟件包訂單
- 20. 索納塔管理職位字段
- 21. 索納塔管理重定向preremove
- 22. 索納塔管理的Symfony2與生產
- 23. 索納塔管理prepersist編碼密碼
- 24. 索納塔管理套件configureRoutes getPersistentParameters
- 25. 索納塔管理MongoDB的sonata_type_model_autocomplete
- 26. 索納塔管理,每不使用FOSUserBundle
- 27. 索納塔管理空白儀表盤
- 28. 索納塔管理包,Symfony2的
- 29. 定製索納塔管理員批量操作錯誤
- 30. 索納塔異常得到太多的管理員註冊
我們不能使用這個。它改變了整個驗證。使用多個實體(使用奏鳴曲媒體)。如何驗證? –
根據你的答案我用buildCreateForm()但我有問題,請檢查鏈接。 http://stackoverflow.com/questions/38308774/how-to-remove-category-from-sonata-type-model-list-at-url-admin-sonata-media-me –