Dispaly Blob image from database using Symfony Twig - php

I am trying to display images for each blog post. I have them set up so that it is displaying the blog name, excerpt and published date, but I am struggling to get the images which I have stored as Blobs. I have attached my code, which is in 3 parts: the entity, which has set and get variables; the index.html.twig file, which is the front end (how I am displaying the image); and the post.orm.yml file, which is to set the type of item the image is, i.e., BLOB.
Post entity
/**
* Set image
*
* #param /post/blob $image
*
* #return Post
*/
public function setimage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return post/blob
*/
public function getimage()
{
return $this->image;
}
index.html.twig
{{post.image}}
post.orm.yml
Shannon\BlogBundle\Entity\Post:
type: entity
table: null
repositoryClass: Shannon\BlogBundle\Repository\PostRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
title:
type: string
length: '255'
body:
type: text
publishedAt:
type: datetime
column: published_at
image:
type:image
lifecycleCallbacks: { }
postcontroller.php
public function imageAction($id)
{
$image = $this->getDoctrine()->getRepository('ShannonBlogBundle:Image')->findOneBy(array('id'=> $id));
return $this->render('index.html.twig', array('image' => $image));
}
}
public function imageAction($id)
{
$image = $this->getDoctrine()->getRepository('ShannonBlogBundle:Image')->findOneBy(array('id'=> $id));
return $this->render('index.html.twig', array('image' => $image)``);
}

You need to encode your image in base64 and simply embed it in the HTML:
<img src="data:image/png;base64,{{ imageBase64 }}" />

Related

How to add image on push notification using brozot / Laravel-FCM

How to add image on push notification using brozot / Laravel-FCM ?
I'm sending notifications correctly, but I would like to know how can I send an image with the notification?
I tried this code but not working
$pushData = ['body' => $message, 'title'=>$title,'image'=>'image-url'];
$pushJsonData = json_encode($pushData);
if(count($tokens)>0)
{
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20);
$notificationBuilder = new PayloadNotificationBuilder($title);
$notificationBuilder->setClickAction('NOTIFICATION');
$notificationBuilder->setBody($message)->setSound('default');
$notificationBuilder->setTag(strtotime("now"));
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['a_data' => $pushJsonData]);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
$downstreamResponse = FCM::sendTo($tokens, $option, $notification, $data);
$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
$downstreamResponse->numberModification();
//return Array - you must remove all this tokens in your database
$downstreamResponse->tokensToDelete();
//return Array (key : oldToken, value : new token - you must change the token in your database )
$downstreamResponse->tokensToModify();
//return Array - you should try to resend the message to the tokens in the array
$downstreamResponse->tokensToRetry();
// return Array (key:token, value:errror) - in production you should remove from your database the tokens present in this array
$downstreamResponse->tokensWithError();
You need to create a custom script that herance the vendor script and add some properties on it.
Create a new path in app: app/Notifications/Message
Add a new script called CustomPayloadNotification.php
Here you need to:
Extends PayloadNotification (vendor);
Add a new variable $image;
Override __construct method, changing the parameter type to CustomPayloadNotificationBuilder. Set all the variables like is in PayloadNotification and also set the new variable $image.
Override toArray method, setting all the properties like is in PayloadNotification and also set a new property image with $image value.
Something like this:
<?php
namespace App\Notifications\Messages;
use LaravelFCM\Message\PayloadNotification;
use App\Notifications\Messages\CustomPayloadNotificationBuilder;
class CustomPayloadNotification extends PayloadNotification // Extends vendor script
{
protected $image; // New variable
/**
* CustomPayloadNotificationBuilder constructor.
*
* #param CustomPayloadNotificationBuilder $builder
*/
public function __construct(CustomPayloadNotificationBuilder $builder) // Change the type of parameter
{
$this->title = $builder->getTitle();
$this->body = $builder->getBody();
$this->icon = $builder->getIcon();
$this->sound = $builder->getSound();
$this->badge = $builder->getBadge();
$this->tag = $builder->getTag();
$this->color = $builder->getColor();
$this->clickAction = $builder->getClickAction();
$this->bodyLocationKey = $builder->getBodyLocationKey();
$this->bodyLocationArgs = $builder->getBodyLocationArgs();
$this->titleLocationKey = $builder->getTitleLocationKey();
$this->titleLocationArgs = $builder->getTitleLocationArgs();
$this->image = $builder->getImage(); // Set image
}
/**
* convert CustomPayloadNotification to array
*
* #return array
*/
function toArray()
{
$notification = [
'title' => $this->title,
'body' => $this->body,
'icon' => $this->icon,
'sound' => $this->sound,
'badge' => $this->badge,
'tag' => $this->tag,
'color' => $this->color,
'click_action' => $this->clickAction,
'body_loc_key' => $this->bodyLocationKey,
'body_loc_args' => $this->bodyLocationArgs,
'title_loc_key' => $this->titleLocationKey,
'title_loc_args' => $this->titleLocationArgs,
'image' => $this->image, // Set property image with $image value
];
// remove null values
$notification = array_filter($notification, function($value) {
return $value !== null;
});
return $notification;
}
}
Add a new script called CustomPayloadNotificationBuilder.php
Here you need to:
Extends PayloadNotificationBuild (vendor);
Add a new variable protected $image;
Create the set/get methods to $image;
Override build method, returning a new CustomPayloadNotification instead PayloadNotification.
Something like this:
<?php
namespace App\Notifications\Messages;
use LaravelFCM\Message\PayloadNotificationBuilder;
use App\Notifications\Messages\CustomPayloadNotification;
class CustomPayloadNotificationBuilder extends PayloadNotificationBuilder // Extends vendor script
{
protected $image; // New variable
/**
* Set image
*
* #param string $image
*
* #return CustomPayloadNotificationBuilder
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image.
*
* #return null|string
*/
public function getImage()
{
return $this->image;
}
/**
* Build an CustomPayloadNotification
*
* #return CustomPayloadNotification
*/
public function build()
{
return new CustomPayloadNotification($this); // Change the object returned
}
}
Reference CustomPayloadNotificationBuilder instead PayloadNotificationBuilder scripts in your code.
Use the method setImage
Your code should be something like this:
use App\Notifications\Messages\CustomPayloadNotificationBuilder; // Add the reference on the top of your code
// No changes before here [...]
$notificationBuilder = new CustomPayloadNotificationBuilder($title); // Replace here
$notificationBuilder->setClickAction('NOTIFICATION');
$notificationBuilder->setBody($message)->setSound('default');
$notificationBuilder->setTag(strtotime("now"));
$notificationBuilder->setImage("Image URL here"); // Add an image
// No changes after here [...]
you need to do some change in vendor for this
Step-1 : Go to the following url I am sharing here-
Laravel-FCM-master\Laravel-FCM-master\src\Message\PayloadNotification.php
Step-2 : here you have to add a instance variable as
protected $image;
Step - 3 find the public function __construct(PayloadNotificationBuilder $builder)
step -4 add $this->image = $builder->getImage(); in this function.
step -5 find the public function toArray()
step -6 add here 'image' => $this->image,
step -7 save and exit.
step -8 then follow this url in vendor again Laravel-FCM-master\Laravel-FCM-master\src\Message\PayloadNotificationBuilder.php:
step -9 add in above page
/**
* Indicates the image that can be displayed in the notification
* Supports an url or internal image.
*
* #param string $image
*
* #return PayloadNotificationBuilder current instance of the builder
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
step - 10 then add
/**
* Get image.
*
* #return null|string
*/
public function getImage()
{
return $this->image;
}
step - 11 that's it, now you can easily able to add a new field in your controller where your code was written asked in question.
simply modify as
$notificationBuilder = new PayloadNotificationBuilder($title);
$notificationBuilder->setClickAction('NOTIFICATION');
$notificationBuilder->setBody($message)->setImage("https://yourdoamin.com/yourdesiredimage.jpeg")->setSound('default');
$notificationBuilder->setTag(strtotime("now"));
and send you will get exact what you are looking for.

Edit file name in entity with Symfony

Hello (excuse my English, not too confident with it)
I'm actually working on a Symfony website that display some spectacles' information.
For now, I need to add an image when I create one of them. I managed to do so with the help of this tutorial.
It basically works like this: I upload an image into site's directory and then send file's name to the entity (Store in a MySQL database). I can then display the image in spectacle's details.
The issue appeared when I want to edit a spectacle. I can't update the image's name. I have two only possibilities are to 1/not edit the entity, or to 2/change the image name and then get a random one that I can't display anymore (these names are usually like /tmp/phpWb8kwV)
My image is instantiate like this in the entity (in Spectacle.php):
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255)
* #Assert\NotBlank(message="Veuillez ajouter une image à votre spectacle.")
* #Assert\File(mimeTypes={ "image/png" })
*/
private $image;
And the FormType for the spectacle's form is made like this (in SpectacleType.php):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom')
->add('lieu')
->add('dateSpectacle', null, array(
'label' => 'Date du spectacle',
))
->add('annee')
->add('image',FileType::class, array(
'label' => 'Image du spectacle',
'required' => false, //(Still need to provide a file to finalize the creation/edit)
));
}
And the controller to acces this page is made like this (in SpectacleController.php):
/**
* Creates a new spectacle entity.
*
* #Route("/new", name="admin_spectacle_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$spectacle = new Spectacle();
$form = $this->createForm('FabopBundle\Form\SpectacleType', $spectacle);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
//--------------------------------------------------------------------
$file = $spectacle->getImage();
$fileName = (md5(uniqid())).'.'.$file->guessExtension();
// moves the file to the directory where image are stored
$file->move(
$this->getParameter('img_directory'), //(Define in the service.yml)
$fileName
);
$spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
//---------------------------------------------------------------------
$em->persist($spectacle);
$em->flush();
return $this->redirectToRoute('admin_spectacle_show', array('id' => $spectacle->getId()));
}
return $this->render('spectacle/new.html.twig', array(
'spectacle' => $spectacle,
'form' => $form->createView(),
));
}
The function that is routed to the edit view is approximatively the same, but i can't use
$spectacle->setImage($fileName);
There is two possibilities to solve this: I would like being able to update the new filename in the entity (with the other information) or being able to update the entity without changing filename.
I hope I was clear enough to explain my problem...
Thanks in advance for your responses.
I had this problem when trying to upload a PDF/TEXT.. file.
But for managing images, I advice you to use ComurImageBundle, it helps you a lot and your problem will be resolved.
It's very simple, you download the bundle like it's explained in this link.
Then you modify your code like this :
1/ Instantiation of your image in Spectacle.php (your image is stored in the DB like string)
/**
* #ORM\Column(type="string", nullable=true)
*/
private $image;
2/ Update your base ( php bin/console doctrine:schema:update --force)
3/ Add these functions to your Spectacle.php after updating your DB schema, these functions let you upload and stock your images under specific directory (web/uploads/spectacles) and don't forget to add this two libraries
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #Assert\File()
*/
private $file;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* #ORM\PrePersist
*/
public function preUpload()
{
if (null !== $this->file) {
$this->image = uniqid() . '.' . $this->file->guessExtension();
}
}
/**
* #ORM\PostPersist
*/
public function upload()
{
if (null === $this->file) {
return;
}
// If there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->file->move($this->getUploadRootDir(), $this->image);
}
public function getUploadDir()
{
return 'uploads/spectacles';
}
public function getBaseUrl()
{
$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);
return substr($pathInfo['dirname']."/", 1);
}
public function getUploadRootDir()
{
return $this->getBaseUrl() . $this->getUploadDir();
}
public function getWebPath()
{
return null === $this->image ? null : $this->getUploadDir() . '/' . $this->image;
}
public function getAbsolutePath()
{
return null === $this->image ? null : $this->getUploadRootDir() . '/' . $this->image;
}
4/ Modify the FormType (SpectacleType.php)like this
use Comur\ImageBundle\Form\Type\CroppableImageType;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom')
->add('lieu')
->add('dateSpectacle', null, array(
'label' => 'Date du spectacle',
))
->add('annee')
->add('image', CroppableImageType::class, array('label' => 'Image', 'required' => true,
'uploadConfig' => array(
'uploadUrl' => $myEntity->getUploadDir(), // required - see explanation below (you can also put just a dir path)
'webDir' => $myEntity->getUploadRootDir(), // required - see explanation below (you can also put just a dir path)
'fileExt' => '*.png', // required - see explanation below (you can also put just a dir path)
'showLibrary' => false,
),
'cropConfig' => array(
'minWidth' => 128,
'minHeight' => 128,
'aspectRatio' => true,
)
));
}
5/ Remove all these lines from your controller you won't need them
//--------------------------------------------------------------------
$file = $spectacle->getImage();
$fileName = (md5(uniqid())).'.'.$file->guessExtension();
// moves the file to the directory where image are stored
$file->move(
$this->getParameter('img_directory'), //(Define in the service.yml)
$fileName
);
$spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
//---------------------------------------------------------------------
6/ That's it you can call the form of your image in new.html.twig and edit.html.twig, all will get well, try it please and notify me if there is any problem.
The solution was stupid ...
In fact, the controller to access the edit route didn't have those lines:
$em = $this->getDoctrine()->getManager();
...
$em->persist($spectacle);
$em->flush();
I need to finish this quickly. If i have more time later, i'll try to make it work with the ComurImageBundle.
Thank you for your help, i'll be more carefull next time ...

Validating symfony collection based on getters instead of properties

I have 2 questions regarding validation. I make a lot of use of property methods (getters) in my entities (nicer code imho). This is one such entity:
class Spec2Events implements ValueAssignable
{
private $values;
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getValues()
{
return $this->values;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getCauseOfDeathValues()
{
$codPms=array();
array_push($codPms,'Cause of death::Natural');
array_push($codPms,'Cause of death::Bycatch');
array_push($codPms,'Cause of death::Ship strike');
array_push($codPms,'Cause of death::Predation');
array_push($codPms,'Cause of death::Other');
array_push($codPms,'Cause of death::Unknown');
return $this->getValues()->filter(
function($entry) use ($codPms) {
return in_array($entry->getPmdSeqno()->getName(), $codPms);
}
);
}
}
$values in this case is a collection of SpecimenValues (which implements EntityValues). ValueAssignables have a collection of EntityValues.
An EntityValuesType class is the form for any class that implements EntityValues. This form has some text or choice childs.
EntityValuesType forms are called like this:
$builder->add('causeOfDeathValues', 'collection', array('type' => new EntityValuesType($this->doctrine),
'options' => array('data_class' => 'AppBundle\Entity\SpecimenValues'),
'allow_delete' => true,
'delete_empty' => true
)); //in order to check if using a class getter as a property works (fails)
$builder->add('values', 'collection', array('type' => new EntityValuesType($this->doctrine),
'options' => array('data_class' => 'AppBundle\Entity\SpecimenValues'),
'allow_delete' => true,
'delete_empty' => true
)); //in order to check if using a class member as a property works (works)
Validation.yml for SpecimenValues looks like this:
AppBundle\Entity\SpecimenValues:
properties:
pmdSeqno:
- NotBlank: ~
- NotNull: ~
s2eScnSeqno:
- NotBlank: ~
- NotNull: ~
description:
- Length:
min: 0
max: 250
value:
- NotBlank: ~
- NotNull: ~
- Length:
min: 1
max: 50
valueFlag:
- Length:
min: 0
max: 50
The Controller looks like this:
public function newAction()
{
$observation = $this->prepareObservation();
$form = $this->createForm(new ObservationsType($this->getDoctrine()), $observation);
return $this->render('AppBundle:Page:add-observations-specimens.html.twig', array(
'form' => $form->createView()
));
}
private function prepareObservation(){
$observation = new Observations();
$event = new EventStates();
$observation->setEseSeqno($event);
$s2e = new Spec2Events();
$event->setSpec2Events($s2e);
$this->instantiateSpecimenValues('Cause of death::Natural', $s2e, false);
$this->instantiateSpecimenValues('Cause of death::Bycatch', $s2e, false);
$this->instantiateSpecimenValues('Cause of death::Ship strike', $s2e, false);
$this->instantiateSpecimenValues('Cause of death::Predation', $s2e, false);
$this->instantiateSpecimenValues('Cause of death::Other', $s2e, false);
$this->instantiateSpecimenValues('Cause of death::Unknown', $s2e, false);
//...
return $observation;
}
private function instantiateSpecimenValues($pmName, &$s2e, $mustBeFlagged)
{
$em = $this->getDoctrine()->getManager();
$pm = $em->getRepository("AppBundle:ParameterMethods")->getParameterMethodByName($pmName);
$sv = new SpecimenValues();
$sv->setPmdSeqno($pm);
$sv->setS2eScnSeqno($s2e);
$sv->setValueFlagRequired($mustBeFlagged);
return $sv;
}
Now, my problem is that empty values are not blocked by the validator (no form error message appears).
If I add a validation constraint programmatically in FormEvents::PRE_SET_DATA, like this:
$options2['constraints'] = array(new \Symfony\Component\Validator\Constraints\NotNull());
it works, but the constraints placed in the .yml file are ignored. Is it possible to combine doing this 'programmatically' AND with validation.yml? In any case I'll write a callback to add in the .yml, so I prefer validation.yml.
Using a form child with name 'values', corresponding to the pure class member variable, works as it should: all required empty fields get a message. All other validation works normally.
What could solve this? I could also use 'values' and use twig to split the collection, but I like using methods as property accessors better.
Thanks!
I've solved this simply by creating the fields both as getters and as properties. The properties themselves are set in the setters. This is necessary otherwise the validator is never called.
So:
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="AppBundle\Entity\SpecimenValues", mappedBy="s2eScnSeqno")
*/
private $values;
private $causeOfDeathValues;
/**
* #param \Doctrine\Common\Collections\Collection $values
* #return Spec2Events
*/
public function setCauseOfDeathValues(\Doctrine\Common\Collections\Collection $values)
{
$this->causeOfDeathValues=$values;
$this->values= new \Doctrine\Common\Collections\ArrayCollection(
array_merge($this->getValues()->toArray(), $values->toArray())
);
return $this;
}

Explode an Entity Object in Symfony2

I'm trying to create galleries in my Symfony2 Web App.
Each post may or may not have a gallery. My galleries are text mapping types, under the Post entity/class:
#Post.orm.yml
MyProject\MyProjectBundle\Entity\Post:
type: entity
table: post
repositoryClass: MyProject\MyProjectBundle\Entity\PostRepository
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
# ...
gallery:
type: text
nullable: true
#...
As there are many images in a gallery, I figured it would have made sense to separate each image with a comma via my data fixture:
image1.png, image2.jpg, examplename-3rdimage.gif, 4thandfinal.jpg
However, I want the gallery to be output like this when it's viewed:
<li>image1.png</li>
<li>image2.jpg</li>
<li>examplename-3rdimage.gif</li>
<li>4thandfinal.jpg</li>
My controller then calls for the Post Entity:
/* PostController.php */
public function postshowAction($id)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MPMPBBundle:Post')->find($id);
$gallery = $em->getRepository('MPMPBBundle:Post')->getGallery();
if (!$entities) {
throw $this->createNotFoundException('Unable to find Post entity.');
}
return $this->render('MPMPBBundle:Post:postshow.html.twig', array(
'entities' => $entities,
'gallery' => $gallery
));
}
As you may have noticed, I reference the function: getGallery() from my repository class: PostRepository:
/* PostRepository.php */
class PostRepository extends EntityRepository
{
public function getGallery()
{
$postGallery = $this->createQueryBuilder('e')
->select('e.gallery')
->getQuery()
->getResult();
$gallery = array();
foreach ($postGallery as $postGal)
{
$gallery = array_merge(explode(",", $postGal['gallery']), $gallery);
}
foreach ($gallery as &$gal)
{
$gal = trim($gal);
}
return $gallery;
}
}
Finally, my twig file: postshow.html.twig, looks like this:
{% for gallery in gallery %}
<li>{{ gallery }}</li>
{% endfor %}
To clarify, what I am looking to achieve is this:
# mysite.com/post/post-1
<li>image1.png</li>
<li>image2.jpg</li>
<li>examplename-3rdimage.gif</li>
<li>4thandfinal.jpg</li>
# mysite.com/post/post-2
<li>image5.png</li>
<li>image11.jpg</li>
<li>examplename-18thimage.gif</li>
<li>22ndandfinal.jpg</li>
Each post displays it's respective gallery.
With what's written above, what is achieved is that ALL the Gallery items from every Post is output, whereas I only need the gallery item for individual posts:
# mysite.com/post/post-1
<li>image1.png</li>
<li>image2.jpg</li>
<li>examplename-3rdimage.gif</li>
<li>4thandfinal.jpg</li>
<li>image5.png</li>
<li>image11.jpg</li>
<li>examplename-18thimage.gif</li>
<li>22ndandfinal.jpg</li>
# mysite.com/post/post-2
<li>image1.png</li>
<li>image2.jpg</li>
<li>examplename-3rdimage.gif</li>
<li>4thandfinal.jpg</li>
<li>image5.png</li>
<li>image11.jpg</li>
<li>examplename-18thimage.gif</li>
<li>22ndandfinal.jpg</li>
The gallery field is in the Post table, so you dont need to query again in the db, just get the gallery from the current entitie and explode() it like this:
/* PostController.php */
public function postshowAction($id)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MPMPBBundle:Post')->find($id);
$gallery = null;
if (null !== $entities->getGallery())
{
$gallery = explode(",", $entities->getGallery());
$gallery = array_map("trim", $gallery);
}
if (!$entities) {
throw $this->createNotFoundException('Unable to find Post entity.');
}
return $this->render('MPMPBBundle:Post:postshow.html.twig', array(
'entities' => $entities,
'gallery' => $gallery
));
}

Symfony2 validation of OneToMany ArrayCollection of Image entities

I am facing a problem with validation of new uploaded file.
I have my Product entity:
// src/Acme/DemoBundle/Entity/Product
...
/**
* #ORM\OneToMany(targetEntity="Image", mappedBy="product", cascade={"persist"})
* #Assert\Image(
* minWidth = 10,
* maxWidth = 20,
* minHeight = 10,
* maxHeight = 20
* )
*/
protected $images;
...
public function __construct()
{
$this->images= new \Doctrine\Common\Collections\ArrayCollection();
}
public function getImages(){
return $this->images;
}
public function setImages($images){
$this->images = $images;
return $this;
}
Image entity is a very simple, with name, size, mimetype.
And I have working on some custom upload listener, so I am not using form and form->isValid. I validate like this:
...
public function onUpload(PostPersistEvent $event)
{
$em= $this->doctrine->getManager();
$product = $this->doctrine->getRepository('Acme\DemoBundle\Entity\Product')->findOneById($customId);
$image = new Image();
$image->setProduct($product)
->setName($uploadInfo->name)
->setStoredName($uploadInfo->storedName)
->setUuid($uploadInfo->uuid)
->setSize($uploadInfo->size)
->setMimeType($uploadInfo->mimeType);
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator();
$a = $product->getImages();
$a->add($image);
$product->setImages($a);
$errors = $validator->validate($product);
And I've got an error:
{"message":"Expected argument of type string, object given","class":"Symfony\\Component\\Validator\\Exception\\UnexpectedTypeException","trace":[{"namespace":"","short_class":"","class":"","type":"","function":"","file":".../vendor\/symfony\/symfony\/src\/Symfony\/Component\/Validator\/Constraints\/FileValidator.php","line":98,"args":[]}
If let say I do NotNull annotation Assert on enother field (like name) - it works, I can get errors. But with ArrayCollection - is not.
I am doing something wrong and can't find info in the internet.
Could the gurus help me out?
To validate collection you can use All and Valid validators.
Acme\DemoBundle\Entity\Product:
properties:
images:
- Valid: ~
- All:
- NotNull: ~
Acme\DemoBundle\Entity\Image:
properties:
file:
- Image:
minWidth: 200
maxWidth: 400
minHeight: 200
maxHeight: 400

Categories