Combining #Gedmo\NestedTree and #ORM\UniqueEntity - symfony

I'm creating a folder structure implemented with the NestedTree behaviour.
Furthermore, I don't want that two folders may have the same name if they are siblings.
For this, I use the combination of #UniqueEntity and #UniqueConstraint annotations, but it does not work.
First my entity (stripped to the minimum since it is 100% identical to the NestedTree defaults) :
/**
* #ORM\Entity
* #Gedmo\Tree(type="nested")
* #ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
* #UniqueEntity(fields={"parent", "name"})
* #ORM\Table(uniqueConstraints={#ORM\UniqueConstraint(name="uniq_url", columns={"parent_id", "name"})})
*/
class Folder
{
/**
* #ORM\Column(type="string", nullable=false)
*/
protected $name;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Folder", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $parent;
}
First try (ignoreNull = true)
When I create two folders with the same name, I have an integrity constraint violation, meaning that the #UniqueConstraints in the database worked but that the #UniqueEntity didn't :
Integrity constraint violation: 1062 Duplicate entry 'name_of_folder' for key 'uniq_url'
Second try (ignoreNull = false)
I also tried with the ignoreNull key set to false (the default is true) :
#UniqueEntity(fields={"parent", "name"}, ignoreNull=false)
but then I get this error :
Warning: ReflectionProperty::getValue() expects parameter 1 to be object, null given in vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php line 670
I've nailed the error down to these lines in Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator :
$criteria[$fieldName] = $class->reflFields[$fieldName]->getValue($entity);
if ($constraint->ignoreNull && null === $criteria[$fieldName]) {
return;
}
if ($class->hasAssociation($fieldName)) {
/* Ensure the Proxy is initialized before using reflection to
* read its identifiers. This is necessary because the wrapped
* getter methods in the Proxy are being bypassed.
*/
$em->initializeObject($criteria[$fieldName]);
$relatedClass = $em->getClassMetadata($class->getAssociationTargetClass($fieldName));
//problem
$relatedId = $relatedClass->getIdentifierValues($criteria[$fieldName]);
if (count($relatedId) > 1) {
throw new ConstraintDefinitionException(
"Associated entities are not allowed to have more than one identifier field to be " .
"part of a unique constraint in: " . $class->getName() . "#" . $fieldName
);
}
$criteria[$fieldName] = array_pop($relatedId);
}
The problem appears on the line marked with //problem. It appears that $criteria[$fieldName] === null is the reason of the error.
So here I am, not knowing what to do...
Does anybody have an idea on what's going on ?
Thank you.

There is no easy way to get out of this situation.
I finally went my own way and created a validator :
Entity
/**
* #ORM\Entity(repositoryClass="Ibiz\DoctrineExtensionsBundle\Entity\Repository\NestedTreeRepository")
* #Gedmo\Tree(type="nested")
* #ORM\Table(uniqueConstraints={#ORM\UniqueConstraint(name="uniq_url", columns={"parent_id", "name"})})
* #IbizAssert\UniquePath("getName")
*/
class Folder
{
/**
* #ORM\Column(type="string", nullable=false)
*/
protected $name;
public function getName()
{
return $this->name;
}
}
Validator/Constraints/UniquePath.php
namespace Ibiz\DoctrineExtensionsBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* #Annotation
*/
class UniquePath extends Constraint
{
public $em = null;
public $errorMethod = null;
public $message = 'The name "%name%" already exists.';
public $service = 'ibiz.validator.unique_path';
public function validatedBy()
{
return $this->service;
}
public function getRequiredOptions()
{
return array('errorMethod');
}
public function getDefaultOption()
{
return 'errorMethod';
}
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}
Validator/Constraints/UniquePathValidator.php
namespace Ibiz\DoctrineExtensionsBundle\Validator\Constraints;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class UniquePathValidator extends ConstraintValidator
{
private $registry;
public function __construct(ManagerRegistry $registry)
{
$this->registry = $registry;
}
public function validate($entity, Constraint $constraint)
{
if ($constraint->errorMethod === null)
{
throw new ConstraintDefinitionException('ErrorMethod should be set');
} else if (!is_string($constraint->errorMethod)) {
throw new UnexpectedTypeException($constraint->errorMethod, 'string');
}
if ($constraint->em) {
$em = $this->registry->getManager($constraint->em);
} else {
$em = $this->registry->getManagerForClass(get_class($entity));
}
$className = $this->context->getClassName();
$repo = $em->getRepository($className);
$count = $repo->getSameNameSiblingsCount($entity);
if ($count != 0) {
$this->context->addViolation($constraint->message, array('%name%' => $entity->{$constraint->errorMethod}()));
}
}
}
Entity/Repository/NestedTreeRepository.php
namespace Ibiz\DoctrineExtensionsBundle\Entity\Repository;
use Gedmo\Tree\Entity\Repository\NestedTreeRepository as BaseRepository;
class NestedTreeRepository extends BaseRepository
{
public function getSameNameSiblingsCountQueryBuilder($node)
{
$meta = $this->getClassMetadata();
if (!$node instanceof $meta->name) {
throw new InvalidArgumentException("Node is not related to this repository");
}
$config = $this->listener->getConfiguration($this->_em, $meta->name);
$qb = $this->_em->createQueryBuilder();
$qb->select($qb->expr()->count('n.id'))
->from($config['useObjectClass'], 'n');
if ($node->getParent() === null) {
$qb->where($qb->expr()->andx(
$qb->expr()->eq('n.name', ':name'),
$qb->expr()->isNull('n.parent')
))
->setParameters(array(
'name' => $node->getName(),
));
} else {
$qb->leftJoin('n.parent', 'p')
->where($qb->expr()->andx(
$qb->expr()->eq('n.name', ':name'),
$qb->expr()->eq('p.name', ':parent')
))
->setParameters(array(
'name' => $node->getName(),
'parent' => $node->getParent()->getName(),
));
}
return $qb;
}
public function getSameNameSiblingsCountQuery($node)
{
return $this->getSameNameSiblingsCountQueryBuilder($node)->getQuery();
}
public function getSameNameSiblingsCount($node)
{
return $this->getSameNameSiblingsCountQuery($node)->getSingleScalarResult();
}
}

Related

Symfony get curent entity from custom DBAL type

I have class that define custom type and i want to make validation based on class that call that type.
Its in purpose of having 2 tables when one is managed by symfony and other is not for yet.
The table that not managed by symfony ned value of 0, when is null.
namespace App\DBAL\Types\Null;
use Doctrine\DBAL\Types\IntegerType as DeafaultType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class IdentityType extends DeafaultType
{
const NULLIDENTITY = 'nullidentity';
public function getName()
{
return self::NULLIDENTITY;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
#some logic
if ($entity instanceof ClassNotManagedBySymfony) {
return $value === null? 0: (int)$value;
}
return $value
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
#some logic
if ($entity instanceof ClassNotManagedBySymfony) {
return $value === 0? null: (int)$value;
}
return $value;
}
}
Edit
Question:
Its posible to get Entity instance inside custom type?
class User extends ClassNotManagedBySymfony
{
/**
* #var int
*
* #ORM\Column(name="entities_id", type="nullidentity")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
}

Doctrine throwing error connected with field not related to current operation

I'm currently doing app that's similar to imgur and I'm receiving following error
An exception occurred while executing 'INSERT INTO user_gallery_views (gallery_id, user_id) VALUES (?, ?)' with params [1, 1]:
SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: user_gallery_views.gallery_id, user_gallery_views.user_id
It occurs while calling path to add object as saved in users collection
Related part of App Controller
/**
* #Route("/image/{id}", name="imgDisp", methods={"GET"})
*/
public function imgDisp($id)
{
$img = $this->gR->findBy(['id'=>$id]);
if ($img) {
$img = $img[0];
$img->setImage(stream_get_contents($img->getImage()));
}
if($this->ls)
{
$this->viewMod($id);
}
return $this->render('app/imgDisp.html.twig', [
'img'=>$img
]);
}
/**
* #Route("/image/{id}/like", name="likeImg", methods={"POST"})
*/
public function likeImg($id)
{
$img = $this->gR->findBy(['id'=>$id])[0];
$user = $this->uR->findBy(['id'=>$this->session->get('user')->getId()])[0];
if(!$img->getLikes()->contains($user))
{
$img->addLike($user);
}
else
{
$img->removeLike($user);
}
$this->em->flush();
return $this->redirectToRoute('imgDisp', ['id'=>$id]);
}
/**
* #Route("/image/{id}/save", name="saveImg", methods={"POST"})
*/
public function saveImg($id)
{
$img = $this->gR->findBy(['id'=>$id])[0];
$user = $this->uR->findBy(['id'=>$this->session->get('user')->getId()])[0];
if(!$img->getSaves()->contains($user))
{
$img->addSave($user);
}
else
{
$img->removeSave($user);
}
$this->em->flush();
return $this->redirectToRoute('imgDisp', ['id'=>$id]);
}
private function viewMod($id)
{
$img = $this->gR->findBy(['id'=>$id])[0];
$user = $this->uR->findBy(['id'=>$this->session->get('user')->getId()])[0];
if(!$img->getViews()->contains($user))
{
$img->addView($user);
$this->em->flush();
}
}
Gallery entity (part related to problem)
/**
* #ORM\ManyToMany(targetEntity="App\Entity\User", inversedBy="likes")
* #ORM\JoinTable(name="user_gallery_likes")
*/
private $likes;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\User", inversedBy="collection")
* #ORM\JoinTable(name="user_gallery_saves")
*/
private $saves;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\User", inversedBy="views")
* #ORM\JoinTable(name="user_gallery_views")
*/
private $views;
/**
* #return Collection|User[]
*/
public function getLikes(): Collection
{
return $this->likes;
}
public function addLike(User $like): self
{
if (!$this->likes->contains($like)) {
$this->likes[] = $like;
}
return $this;
}
public function removeLike(User $like): self
{
if ($this->likes->contains($like)) {
$this->likes->removeElement($like);
}
return $this;
}
/**
* #return Collection|User[]
*/
public function getSaves(): Collection
{
return $this->saves;
}
public function addSave(User $save): self
{
if (!$this->saves->contains($save)) {
$this->views[] = $save;
}
return $this;
}
public function removeSave(User $save): self
{
if ($this->saves->contains($save)) {
$this->saves->removeElement($save);
}
return $this;
}
/**
* #return Collection|User[]
*/
public function getViews(): Collection
{
return $this->views;
}
public function addView(User $view): self
{
if (!$this->views->contains($view)) {
$this->views[] = $view;
}
return $this;
}
Users entity (part related to problem)
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Gallery", mappedBy="saves")
*/
private $collection;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Gallery", mappedBy="likes")
*/
private $likes;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Gallery", mappedBy="views")
*/
private $views;
/**
* #return Collection|Gallery[]
*/
public function getCollection(): Collection
{
return $this->collection;
}
public function addCollection(Gallery $collection): self
{
if (!$this->collection->contains($collection)) {
$this->collection[] = $collection;
}
return $this;
}
public function removeCollection(Gallery $collection): self
{
if ($this->collection->contains($collection)) {
$this->collection->removeElement($collection);
}
return $this;
}
/**
* #return Collection|Gallery[]
*/
public function getLikes(): Collection
{
return $this->likes;
}
public function addLike(Gallery $like): self
{
if (!$this->likes->contains($like)) {
$this->likes[] = $like;
$like->addLike($this);
}
return $this;
}
public function removeLike(Gallery $like): self
{
if ($this->likes->contains($like)) {
$this->likes->removeElement($like);
$like->removeLike($this);
}
return $this;
}
/**
* #return Collection|Gallery[]
*/
public function getViews(): Collection
{
return $this->views;
}
public function addView(Gallery $view): self
{
if (!$this->views->contains($view)) {
$this->views[] = $view;
$view->addView($this);
}
return $this;
}
The point I don't get is why error concern user_galler_views when it's not even used in /image/{id}/save?
I'm for sure not seeing something but don't even know what, so I'm full of hope u gonna help me
It looks like you are storing the entity to the wrong Array.
public function addSave(User $save): self
{
if (!$this->saves->contains($save)) {
$this->views[] = $save;
}
return $this;
}
You check for $this->saves->contains($save) but then you store the data not to saves but to views.
$this->views[] = $save;
It is probably a coincidence that the save entity has the same id as another view entity that is already assigned to the gallery.

JMSSerializerBundle deserialization skip groups exclusion on id property using DoctrineObjectConstructor

I'm using jms/serializer-bundle 2.4.3 on a symfony 4.2 and a I noticed an annoying problem in my application :
when I post an entity, the DoctrineObjectConstructor uses id in content to retrieve another entity and thus patch it while it is excluded by my security groups
see rather entity
class Entity
{
/**
* #var int
*
* #ORM\Column(name="id", type="int")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #Serializer\Groups({"GetEntity"})
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string")
* #Serializer\Groups({"GetEntity", "PostEntity"})
*/
private $name;
}
controller
/**
* #Route("/entity", name="post_entity", methods={"POST"})
*/
public function postEntity(Request $request, EntityManagerInterface $entityManager, SerializerInterface $serializer): JsonResponse
{
$deserializationContext = DeserializationContext::create();
$deserializationContext->setGroups(['PostEntity']);
$entity = $serializer->deserialize($request->getContent(), Entity::class, 'json', $deserializationContext);
$entityManager->persist($entity);
$entityManager->flush();
return $this->json($entity, Response::HTTP_OK, [], ['groups' => ['GetEntity']]);
}
I have some JMS configurations changes in services
jms_serializer.object_constructor:
alias: jms_serializer.doctrine_object_constructor
public: true
jms_serializer.unserialize_object_constructor:
class: App\Serializer\ObjectConstructor
If anyone can explain to me how to ignore the id in this case I'm open to any suggestions.
Regards and thanks for any help
To resolve, just add override in your services.yaml
jms_serializer.doctrine_object_constructor:
class: App\Serializer\DoctrineObjectConstructor
arguments:
- '#doctrine'
- '#jms_serializer.unserialize_object_constructor'
jms_serializer.object_constructor:
alias: jms_serializer.doctrine_object_constructor
and add a local DoctrineObjectConstructor updated to ignore entities without current deserialization group on id property
class DoctrineObjectConstructor implements ObjectConstructorInterface
{
const ON_MISSING_NULL = 'null';
const ON_MISSING_EXCEPTION = 'exception';
const ON_MISSING_FALLBACK = 'fallback';
private $fallbackStrategy;
private $managerRegistry;
private $fallbackConstructor;
/**
* Constructor.
*
* #param ManagerRegistry $managerRegistry Manager registry
* #param ObjectConstructorInterface $fallbackConstructor Fallback object constructor
* #param string $fallbackStrategy
*/
public function __construct(ManagerRegistry $managerRegistry, ObjectConstructorInterface $fallbackConstructor, $fallbackStrategy = self::ON_MISSING_NULL)
{
$this->managerRegistry = $managerRegistry;
$this->fallbackConstructor = $fallbackConstructor;
$this->fallbackStrategy = $fallbackStrategy;
}
/**
* {#inheritdoc}
*/
public function construct(VisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context)
{
// Locate possible ObjectManager
$objectManager = $this->managerRegistry->getManagerForClass($metadata->name);
if (!$objectManager) {
// No ObjectManager found, proceed with normal deserialization
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
// Locate possible ClassMetadata
$classMetadataFactory = $objectManager->getMetadataFactory();
if ($classMetadataFactory->isTransient($metadata->name)) {
// No ClassMetadata found, proceed with normal deserialization
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
// Managed entity, check for proxy load
if (!\is_array($data)) {
// Single identifier, load proxy
return $objectManager->getReference($metadata->name, $data);
}
// Fallback to default constructor if missing identifier(s)
$classMetadata = $objectManager->getClassMetadata($metadata->name);
$identifierList = [];
foreach ($classMetadata->getIdentifierFieldNames() as $name) {
$propertyGroups = [];
if ($visitor instanceof AbstractVisitor) {
/** #var PropertyNamingStrategyInterface $namingStrategy */
$namingStrategy = $visitor->getNamingStrategy();
$dataName = $namingStrategy->translateName($metadata->propertyMetadata[$name]);
$propertyGroups = $metadata->propertyMetadata[$name]->groups;
} else {
$dataName = $name;
}
if (!array_key_exists($dataName, $data) || true === empty(array_intersect($context->getAttribute('groups'), $propertyGroups))) {
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
$identifierList[$name] = $data[$dataName];
}
// Entity update, load it from database
$object = $objectManager->find($metadata->name, $identifierList);
if (null === $object) {
switch ($this->fallbackStrategy) {
case self::ON_MISSING_NULL:
return null;
case self::ON_MISSING_EXCEPTION:
throw new ObjectConstructionException(sprintf('Entity %s can not be found', $metadata->name));
case self::ON_MISSING_FALLBACK:
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
default:
throw new InvalidArgumentException('The provided fallback strategy for the object constructor is not valid');
}
}
$objectManager->initializeObject($object);
return $object;
}
}

Symfony2 form and Doctrine2 - creat foreign key in assigned entities fails

i'm trying to add my data into my database , i was trying to not use a formbuilder, inside that i put all my form into the controller,and my entity contains a foreign key but i got an this error :
Neither the property "id_classe" nor one of the methods "getIdClasse()", "idClasse()", "isIdClasse()", "hasIdClasse()", "__get()" exist and have public access in class "MyApp\SchoolBundle\Entity\Etudiant".
here is my function in the controller :
public function AjoutAction(Request $request)
{ $classe=new Etudiant();
$formBuilder = $this->get('form.factory')->createBuilder('form', $classe);
$formBuilder
->add('prenom', 'text')
->add('nom', 'text')
->add('Cin', 'integer')
->add('id_classe', 'integer')
->add('save', 'submit')
;
$form = $formBuilder->getForm();
if ($form->handleRequest($request)->isValid()) {
$objToPersist = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($objToPersist);
$em->flush();
}
return $this->render('MyAppSchoolBundle:Etudiant:ajout.html.twig',array(
'form' => $form->createView(),
));
}
and here is my Entity
namespace MyApp\SchoolBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity
*/
class Etudiant {
/**
* #ORM\id
*#ORM\GeneratedValue
*#ORM\Column(type="integer",name="ID_Etudiant")
*/
private $Id;
/**
*#ORM\Column{type="string",length=255}
*/
private $prenom;
/**
*#ORM\Column{type="string",length=255}
*/
private $nom;
/**
*#Assert\NotBlank
*#ORM\Column(type="integer", unique=true)
*/
private $cin; //unique ne fonctionne pas qu'avec les assert
/**
* #ORM\ManyToOne(targetEntity="Classes",cascade={"ALL"})
*/
private $id_classe;
function getId() {
return $this->Id;
}
function getPrenom() {
return $this->prenom;
}
function getNom() {
return $this->nom;
}
function setId($Id) {
$this->Id = $Id;
}
function setPrenom($prenom) {
$this->prenom = $prenom;
}
function setNom($nom) {
$this->nom = $nom;
}
function getCin() {
return $this->cin;
}
function setCin($cin) {
$this->cin = $cin;
}
public function getId_classe() {
return $this->id_classe;
}
function setId_classe($id_classe) {
$this->id_classe = $id_classe;
}
}
In your form you have:
->add('id_classe', 'integer')
Add a setter in your entity
public function setIdClasse($idClasse) {
$this->id_classe = $idClasse;
}
Edit
Also, as a suggestion:
1 Always add visibility to your functions (public function blabla() or private function blabla())
2 Use camel case is preferred (so your properties are $nomClasse, $idClasse, $id, etc..)
3 Not compulsory, but a good idea to return the object in your setter
4 You're not very consistent in your notations (see your form builder->add('nom', 'text') ->add('Cin', 'integer'))
Getters and Setter would normally look like this:
public function getNomClasse()
{
return $this->nomClasse;
}
public function setNomClasse($nomClasse)
{
$this->nomClasse = $nomClasse;
return $this;
}

how to get the uploded filenames of a form in the controller

i used the following code in the controller inorder to get the filenames of the uploaded files
My controller is
class uploadController extends Controller
{
public function uploadAction(Request $request)
{
$id= $_GET['id'];
$user = new attachments();
$form = $this->createFormBuilder($user)->add('files','file',array("data_class" => null,"attr"=>array("multiple" =>"multiple",)))->getForm();
$formView = $form->createView();
$formView->getChild('files')->set('full_name','files[]');
if ($request->getMethod() == 'POST')
{
$em = $this->getDoctrine()->getManager();
$data = $form["files"]->getData();
}
}
when i print the $data it is not giving the filenames of uploaded files it is returning the null values
my entity is:
use Symfony\Component\HttpFoundation\File\UploadedFile;
class attachments
{
private $id;
/**
* #var integer
* #ORM\Column(name="user", type="integer", nullable=false)
* #ORM\ManyToOne(targetEntity="users", inversedBy="annotations")
*/
protected $userId;
/**
* #var string
*
* #Assert\File(maxSize="6000000")
* #ORM\Column(name="files", type="array", length=255, nullable=true)
*/
public $files=array();
public function __construct()
{
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set userId
*
* #param integer $userId
* #return attachments
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/**
* Set files
* #param object $files
*
* #return attachments
*/
public function setFiles($files)
{
$this->files = $files;
}
/**
* Get files
*
* #return object
*/
public function getFiles()
{
return $this->files;
}
public function uploadFiles()
{
// the files property can be empty if the field is not required
if (null === $this->files)
{
return;
}
else
{
$this->files->move($this->getUploadRootDir(), $this->files->getClientOriginalName());
}
$this->setFiles($this->files->getClientOriginalName());
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->userId;
}
public function getAbsolutePath()
{
return null === $this->path
? null
: $this->getUploadRootDir() . DIRECTORY_SEPARATOR . $this->path;
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir() . DIRECTORY_SEPARATOR . $this->path;
}
protected function getUploadRootDir()
{
return __DIR__ . '/../../../../web/'. $this->getUploadDir();
}
protected function getUploadDir()
{
return 'uploads/';
}
}
Uploaded Files in Symfony2 are of type Symfony/Component/HttpFoundation/File/UploadedFile.
You can get the original client name ( php will rename files when putting them into php_upload_tmp_dir ) with:
$file->getClientOriginalName();
... move the file to a new location with:
$file->move('path/to/your_file', 'new_name.jpg');
You can not use the assert File Constraint for an array.
* #Assert\File(maxSize="6000000")
*/
protected $files = array();
Therefore you need the All constraint.
Furthermore you can't just call the move method on an array or collection... you will have to loop over the collection/array.
$this->files->move('..') // this is never going to work...
Use an array collection and create a property for your uploaded files if thats what you want.
protected $files;
protected $uploadedFiles;
public function __construct()
{
$this->files = new ArrayCollection;
$this->uploadedFiles = new Array();
}
If you want to transform your Doctrine Collection of UploadedFile entities into an Array do the following:
$collection = $entity->getFiles();
$array = $collection->toArray();
But whatever you're trying to do ... better use OOP instead of arrays like you're attempting here.

Resources