Context
I have a User entity which has one Team and Team which can have several users.
I'm trying to fetch one team and to get the list of users associated with.
User Entity
<?php
namespace Enterprise\PortailBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User entity class
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="Enterprise\PortailBundle\Repository\TeamRepository")
* #category Entity
* #package Entity
*/
class User
{
/*
* Relationship Mapping Metadata
*/
public function __toString()
{
return $this->firstName . ' - ' . $this->lastName . ' - ' . $this->enterprise . ' - ' . $this->team;
}
/**
* #ORM\ManyToOne(targetEntity="Team", inversedBy="users")
* #ORM\JoinColumn(name="team_id", referencedColumnName="id")
*/
private $team;
/*
* Autogenerated methods / variables
*/
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le prénom de l'utilisateur doit être supérieur à 2 caractères.")
* #Assert\Length(max=32, maxMessage="Le prénom de l'utiisateur doit être inférieur à 32 caractères.")
* #ORM\Column(name="firstName", type="string", length=32)
*/
private $firstName;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le nom de l'utilisateur doit être supérieur à 2 caractères.")
* #Assert\Length(max=64, maxMessage="Le nom de l'utilisateur doit être inférieur à 64 caractères.")
* #ORM\Column(name="lastName", type="string", length=64)
*/
private $lastName;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le nom de l'entreprise doit être supérieur à 2 caractères.")
* #Assert\Length(max=64, maxMessage="Le nom de l'entreprise doit être inférieur à 64 caractères.")
* #ORM\Column(name="enterprise", type="string", length=64)
*/
private $enterprise;
/**
* #Assert\File(mimeTypes={ "image/jpeg", "image/jpg", "image/png" })
* #ORM\Column(name="image", type="string")
*/
private $image;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName
*
* #param string $firstName
*
* #return User
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* #param string $lastName
*
* #return User
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set enterprise
*
* #param string $enterprise
*
* #return User
*/
public function setEnterprise($enterprise)
{
$this->enterprise = $enterprise;
return $this;
}
/**
* Get enterprise
*
* #return string
*/
public function getEnterprise()
{
return $this->enterprise;
}
/**
* Set image
*
* #param string $image
*
* #return User
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set team
*
* #param Team $team
*
* #return User
*/
public function setTeam(Team $team)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* #return Team
*/
public function getTeam()
{
return $this->team;
}
}
Team entity
<?php
namespace Enterprise\PortailBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Team entity class
*
* #ORM\Table(name="team")
* #ORM\Entity(repositoryClass="Enterprise\PortailBundle\Repository\TeamRepository")
* #category Entity
* #package Entity
*/
class Team
{
public function __toString()
{
return $this->name . ' - ' . $this->role;
}
/**
* #ORM\OneToMany(targetEntity="User", mappedBy="team")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/*
* Autogenerated methods / variables
*/
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le nom de l'équipe doit être supérieur à 2 caractères.")
* #Assert\Length(max=64, maxMessage="Le nom de l'équipe doit être inférieur à 64 caractères.")
* #ORM\Column(name="name", type="string", length=64)
*/
private $name;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le role de l'équipe doit être supérieur à 2 caractères.")
* #Assert\Length(max=64, maxMessage="Le role de l'équipe doit être inférieur à 64 caractères.")
* #ORM\Column(name="role", type="string", length=64)
*/
private $role;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Team
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
/**
* Set role
*
* #param string $role
*
* #return Team
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Get role
*
* #return string
*/
public function getRole()
{
return $this->role;
}
}
Doctrine version
2.5.14
The database
The team and the user table
In my controller I succeed to get informations when going from user to the team
$user = $this->getDoctrine()->getRepository(User::class)->find(6);
dump($user);
$teamName = $user->getTeam()->getName();
dump($teamName);
But the contrary doesn't returns me the list of users
$team = $this->getDoctrine()->getRepository(Team::class)->find(1);
dump($team);
$users = $team->getUsers();
dump($users);
The output of this last part is:
So my question is why $users = $team1->getUsers(); doesn't return the list of users ?
Thanks
Probably for efficiency reasons, it seems that Symfony does not populate data until you request them.
Try this, you should see that the collection is not empty anymore, and that you can actually access the user data from a team:
$team = $this->getDoctrine()->getRepository(Team::class)->find(1);
dump($team);
$users = $team->getUsers();
dump($users); // #collection: ArrayCollection is not empty anymore
$firstName = $users[0]->getFirstName();
dump($firstName);
Related
Symfony3 with PhpStorm.2016.3.2
I succeeded in making a file uploader for one picture only. But now I need to make it "multiple"
I will show you the code and the error that comes up with it as I canno't upload multiple files.
here is the controller
public function newAction(Request $request)
{
$restaurant = new Restaurant();
$form = $this->createForm(RestaurantType::class, $restaurant);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
// file upload
if ($request->files->get('restaurant')['picture'] != null) {
$file = $request->files->get('restaurant')['picture'];
$targetDir = $this->getParameter('uploaded_restaurants');
$filename = $this->get('app.uploader')->upload($file, $targetDir);
$mediaRestaurant = null;
if ($restaurant->getId() != null) {
$mediaRestaurant = $this->getDoctrine()->getRepository('AppBundle:Media')->findPictureByRestaurant($restaurant);
}
if ($mediaRestaurant) {
$media = $mediaRestaurant;
$fs = new Filesystem();
try {
$fs->remove($this->get('kernel')->getRootDir().'/../web/uploads/restaurants/'.$media->getName());
} catch (IOException $e) {
echo "error";
}
} else {
$media = new Media();
$media->setCreatedAt(new \DateTime());
}
$originalName = $file->getClientOriginalName();
$media->setName($filename)
->setOriginalName($originalName)
->setType('img')
->setContext('restaurant_picture')
->setUpdatedAt(new \DateTime())
;
$media->setRestaurant($restaurant);
$em->persist($media);
}
$restaurant->setIsActivated(false);
$em->persist($restaurant);
$em->flush();
}
return $this->render('admin/restaurant/new.html.twig', array(
'restaurant' => $restaurant,
'form' => $form->createView(),
));
}
my FormType(called RestaurantType) where I added a field for file upload (when I set up multiple to false it actually works for only one picture)
$builder
->add('picture', FileType::class, array(
'label' => 'Photos du restaurant',
'multiple' => true,
'required' => false,
'mapped' => false,
'attr' => array(
'accept' => '.jpg,.jpeg,.png'),
))
The service to uploads file
class FileUploader
{
/**
* #param UploadedFile $file
* #param $targetDir
* #return string
*/
public function upload(UploadedFile $file, $targetDir)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($targetDir, $fileName);
return $fileName;
}
}
the queryBuilder in the MediaRepository
public function findPictureByRestaurant(Restaurant $restaurant)
{
return $this->createQueryBuilder('m')
->select('m')
->where('m.restaurant = :restaurant')
->setParameter('restaurant', $restaurant)
->andWhere('m.context = :restaurant_picture')
->setParameter('restaurant_picture', 'restaurant_picture')
->getQuery()
->getOneOrNullResult();
}
in my show.html.twig where you can see the picture
{% if restaurant.medias != null and restaurant.medias.count > 0 and restaurant.medias[0].name != null %}
<img src="/uploads/restaurants/{{ restaurant.medias[0].name }}">
{% endif %}
my config.yml where the files are uploaded
parameters:
locale: fr
uploaded_restaurants: "%kernel.root_dir%/../web/uploads/restaurants"
And the entity Restaurant which is pretty long (sorry)
/**
* Restaurant
*
* #ORM\Table(name="restaurant")
* #ORM\Entity(repositoryClass="AppBundle\Repository\RestaurantRepository")
*/
class Restaurant
{
/**
* #var FoodType
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\FoodType", inversedBy="restaurants")
* #ORM\JoinColumn(name="food_type_id", referencedColumnName="id")
*/
private $foodType;
/**
* #var City
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\City", inversedBy="restaurants")
* #ORM\JoinColumn(name="city_id", referencedColumnName="id")
*/
private $city;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Media", mappedBy="restaurant")
*/
private $medias;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Privatisation", mappedBy="restaurant")
*/
private $privatisations;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Retrocession", mappedBy="restaurant")
*/
private $retrocessions;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\OpenedSlot", mappedBy="restaurant")
*/
private $openedSlots;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\ExceptionSlot", mappedBy="restaurant")
*/
private $exceptionSlots;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Slot", mappedBy="restaurant")
*/
private $slots;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Chef", mappedBy="restaurant")
*/
private $chefs;
/**
* Constructor
*/
public function __construct()
{
$this->medias = new ArrayCollection();
$this->privatisations = new ArrayCollection();
$this->retrocessions = new ArrayCollection();
$this->openedSlots = new ArrayCollection();
$this->exceptionSlots = new ArrayCollection();
$this->slots = new ArrayCollection();
$this->chefs = new ArrayCollection();
}
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=120, unique=true)
* #Assert\Length(
* max = 120,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255, unique=true)
* #Gedmo\Slug(fields={"name"})
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="webUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $webUrl;
/**
* #var string
*
* #ORM\Column(name="tripAdvisorUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $tripAdvisorUrl;
/**
* #var string
*
* #ORM\Column(name="facebookUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $facebookUrl;
/**
* #var string
*
* #ORM\Column(name="twitterUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $twitterUrl;
/**
* #var string
*
* #ORM\Column(name="instagramUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $instagramUrl;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=20)
* #Assert\Regex(
* pattern="#^0[1-9]([-. ]?[0-9]{2}){4}$#",
* match=true,
* message="Numéro de téléphone invalide."
* )
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="phone2", type="string", length=20, nullable=true)
* #Assert\Regex(
* pattern="#^0[1-9]([-. ]?[0-9]{2}){4}$#",
* match=true,
* message="Numéro de téléphone invalide."
* )
*/
private $phone2;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $email;
/**
* #var float
*
* #ORM\Column(name="latitude", type="float")
* #Assert\Regex(
* pattern="/^-?(?:\d+|\d*\.\d+)$/",
* match=true,
* )
*/
private $latitude;
/**
* #var float
*
* #ORM\Column(name="longitude", type="float")
* #Assert\Regex(
* pattern="/^-?(?:\d+|\d*\.\d+)$/",
* match=true,
* )
*/
private $longitude;
/**
* #var int
*
* #ORM\Column(name="stars", type="integer", nullable=true)
* #Assert\Regex(
* pattern="/^[0-9]+$/",
* match=true,
* message="Ceci n'est pas un chiffre."
* )
*/
private $stars;
/**
* #var int
*
* #ORM\Column(name="seatNumber", type="integer", nullable=true)
* #Assert\Regex(
* pattern="/^[0-9]+$/",
* match=true,
* )
*/
private $seatNumber;
/**
* #var float
*
* #ORM\Column(name="minPrice", type="float", nullable=true)
* #Assert\Regex(
* pattern="/^-?(?:\d+|\d*\.\d+)$/",
* match=true,
* )
*/
private $minPrice;
/**
* #var float
*
* #ORM\Column(name="maxPrice", type="float", nullable=true)
* #Assert\Regex(
* pattern="/^-?(?:\d+|\d*\.\d+)$/",
* match=true,
* )
*/
private $maxPrice;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $address;
/**
* #var bool
*
* #ORM\Column(name="is_activated", type="boolean")
*/
private $isActivated = true;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Restaurant
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set slug
*
* #param string $slug
*
* #return Restaurant
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set description
*
* #param string $description
*
* #return Restaurant
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set webUrl
*
* #param string $webUrl
*
* #return Restaurant
*/
public function setWebUrl($webUrl)
{
$this->webUrl = $webUrl;
return $this;
}
/**
* Get webUrl
*
* #return string
*/
public function getWebUrl()
{
return $this->webUrl;
}
/**
* Set tripAdvisorUrl
*
* #param string $tripAdvisorUrl
*
* #return Restaurant
*/
public function setTripAdvisorUrl($tripAdvisorUrl)
{
$this->tripAdvisorUrl = $tripAdvisorUrl;
return $this;
}
/**
* Get tripAdvisorUrl
*
* #return string
*/
public function getTripAdvisorUrl()
{
return $this->tripAdvisorUrl;
}
/**
* Set facebookUrl
*
* #param string $facebookUrl
*
* #return Restaurant
*/
public function setFacebookUrl($facebookUrl)
{
$this->facebookUrl = $facebookUrl;
return $this;
}
/**
* Get facebookUrl
*
* #return string
*/
public function getFacebookUrl()
{
return $this->facebookUrl;
}
/**
* Set twitterUrl
*
* #param string $twitterUrl
*
* #return Restaurant
*/
public function setTwitterUrl($twitterUrl)
{
$this->twitterUrl = $twitterUrl;
return $this;
}
/**
* Get twitterUrl
*
* #return string
*/
public function getTwitterUrl()
{
return $this->twitterUrl;
}
/**
* Set instagramUrl
*
* #param string $instagramUrl
*
* #return Restaurant
*/
public function setInstagramUrl($instagramUrl)
{
$this->instagramUrl = $instagramUrl;
return $this;
}
/**
* Get instagramUrl
*
* #return string
*/
public function getInstagramUrl()
{
return $this->instagramUrl;
}
/**
* Set phone
*
* #param string $phone
*
* #return Restaurant
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set phone2
*
* #param string $phone2
*
* #return Restaurant
*/
public function setPhone2($phone2)
{
$this->phone2 = $phone2;
return $this;
}
/**
* Get phone2
*
* #return string
*/
public function getPhone2()
{
return $this->phone2;
}
/**
* Set email
*
* #param string $email
*
* #return Restaurant
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set latitude
*
* #param float $latitude
*
* #return Restaurant
*/
public function setLatitude($latitude)
{
$this->latitude = $latitude;
return $this;
}
/**
* Get latitude
*
* #return float
*/
public function getLatitude()
{
return $this->latitude;
}
/**
* Set longitude
*
* #param float $longitude
*
* #return Restaurant
*/
public function setLongitude($longitude)
{
$this->longitude = $longitude;
return $this;
}
/**
* Get longitude
*
* #return float
*/
public function getLongitude()
{
return $this->longitude;
}
/**
* Set stars
*
* #param integer $stars
*
* #return Restaurant
*/
public function setStars($stars)
{
$this->stars = $stars;
return $this;
}
/**
* Get stars
*
* #return int
*/
public function getStars()
{
return $this->stars;
}
/**
* Set seatNumber
*
* #param integer $seatNumber
*
* #return Restaurant
*/
public function setSeatNumber($seatNumber)
{
$this->seatNumber = $seatNumber;
return $this;
}
/**
* Get seatNumber
*
* #return int
*/
public function getSeatNumber()
{
return $this->seatNumber;
}
/**
* Set minPrice
*
* #param float $minPrice
*
* #return Restaurant
*/
public function setMinPrice($minPrice)
{
$this->minPrice = $minPrice;
return $this;
}
/**
* Get minPrice
*
* #return float
*/
public function getMinPrice()
{
return $this->minPrice;
}
/**
* Set maxPrice
*
* #param float $maxPrice
*
* #return Restaurant
*/
public function setMaxPrice($maxPrice)
{
$this->maxPrice = $maxPrice;
return $this;
}
/**
* Get maxPrice
*
* #return float
*/
public function getMaxPrice()
{
return $this->maxPrice;
}
/**
* Set address
*
* #param string $address
*
* #return Restaurant
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Add media
*
* #param Media $media
*
* #return Restaurant
*/
public function addMedia(Media $media)
{
$this->medias[] = $media;
return $this;
}
/**
* Remove media
*
* #param Media $media
*/
public function removeMedia(Media $media)
{
$this->medias->removeElement($media);
}
/**
* Get medias
*
* #return ArrayCollection
*/
public function getMedias()
{
return $this->medias;
}
/**
* Set foodType
*
* #param FoodType $foodType
*
* #return Restaurant
*/
public function setFoodType(FoodType $foodType = null)
{
$this->foodType = $foodType;
return $this;
}
/**
* Get foodType
*
* #return FoodType
*/
public function getFoodType()
{
return $this->foodType;
}
/**
* Add privatisation
*
* #param Privatisation $privatisation
*
* #return Restaurant
*/
public function addPrivatisation(Privatisation $privatisation)
{
$this->privatisations[] = $privatisation;
return $this;
}
/**
* Remove privatisation
*
* #param Privatisation $privatisation
*/
public function removePrivatisation(Privatisation $privatisation)
{
$this->privatisations->removeElement($privatisation);
}
/**
* Get privatisations
*
* #return ArrayCollection
*/
public function getPrivatisations()
{
return $this->privatisations;
}
/**
* Add retrocession
*
* #param Retrocession $retrocession
*
* #return Restaurant
*/
public function addRetrocession(Retrocession $retrocession)
{
$this->retrocessions[] = $retrocession;
return $this;
}
/**
* Remove retrocession
*
* #param Retrocession $retrocession
*/
public function removeRetrocession(Retrocession $retrocession)
{
$this->retrocessions->removeElement($retrocession);
}
/**
* Get retrocessions
*
* #return ArrayCollection
*/
public function getRetrocessions()
{
return $this->retrocessions;
}
/**
* Add openedSlot
*
* #param OpenedSlot $openedSlot
*
* #return Restaurant
*/
public function addOpenedSlot(OpenedSlot $openedSlot)
{
$this->openedSlots[] = $openedSlot;
return $this;
}
/**
* Remove openedSlot
*
* #param OpenedSlot $openedSlot
*/
public function removeOpenedSlot(OpenedSlot $openedSlot)
{
$this->openedSlots->removeElement($openedSlot);
}
/**
* Get openedSlots
*
* #return ArrayCollection
*/
public function getOpenedSlots()
{
return $this->openedSlots;
}
/**
* Add exceptionSlot
*
* #param ExceptionSlot $exceptionSlot
*
* #return Restaurant
*/
public function addExceptionSlot(ExceptionSlot $exceptionSlot)
{
$this->exceptionSlots[] = $exceptionSlot;
return $this;
}
/**
* Remove exceptionSlot
*
* #param ExceptionSlot $exceptionSlot
*/
public function removeExceptionSlot(ExceptionSlot $exceptionSlot)
{
$this->exceptionSlots->removeElement($exceptionSlot);
}
/**
* Get exceptionSlots
*
* #return ArrayCollection
*/
public function getExceptionSlots()
{
return $this->exceptionSlots;
}
/**
* Add slot
*
* #param Slot $slot
*
* #return Restaurant
*/
public function addSlot(Slot $slot)
{
$this->slots[] = $slot;
return $this;
}
/**
* Remove slot
*
* #param Slot $slot
*/
public function removeSlot(Slot $slot)
{
$this->slots->removeElement($slot);
}
/**
* Get slots
*
* #return ArrayCollection
*/
public function getSlots()
{
return $this->slots;
}
/**
* Add chef
*
* #param Chef $chef
*
* #return Restaurant
*/
public function addChef(Chef $chef)
{
$this->chefs[] = $chef;
return $this;
}
/**
* Remove chef
*
* #param Chef $chef
*/
public function removeChef(Chef $chef)
{
$this->chefs->removeElement($chef);
}
/**
* Get chefs
*
* #return ArrayCollection
*/
public function getChefs()
{
return $this->chefs;
}
/**
* Set city
*
* #param City $city
*
* #return Restaurant
*/
public function setCity(City $city = null)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* #return City
*/
public function getCity()
{
return $this->city;
}
/**
* #return bool
*/
public function getIsActivated()
{
return $this->isActivated;
}
/**
* #param bool $isActivated
*/
public function setIsActivated($isActivated)
{
$this->isActivated = $isActivated;
}
}
and the error that comes up when I upload a picture and click on submit button
To sum up it up all, this code works for only one picture when I set up multiple to false in my FormType. But then I am stuck for the multiple file upload and I can't get to find a way around that. Does someone know how to handle it with the code I given you?
Thank you
Because your file definition accept multiple uploads, you need to modify upload part of your controller:
// file upload
if ($request->files->get('restaurant')['picture'] != null) {
$files = $request->files->get('restaurant')['picture'];
foreach ($files as $file) {
$targetDir = $this->getParameter('uploaded_restaurants');
$filename = $this->get('app.uploader')->upload($file, $targetDir);
$mediaRestaurant = null;
if ($restaurant->getId() != null) {
$mediaRestaurant = $this->getDoctrine()->getRepository('AppBundle:Media')->findPictureByRestaurant($restaurant);
}
if ($mediaRestaurant) {
$media = $mediaRestaurant;
$fs = new Filesystem();
try {
$fs->remove($this->get('kernel')->getRootDir().'/../web/uploads/restaurants/'.$media->getName());
} catch (IOException $e) {
echo "error";
}
} else {
$media = new Media();
$media->setCreatedAt(new \DateTime());
}
$originalName = $file->getClientOriginalName();
$media->setName($filename)
->setOriginalName($originalName)
->setType('img')
->setContext('restaurant_picture')
->setUpdatedAt(new \DateTime())
;
$media->setRestaurant($restaurant);
$em->persist($media);
}
}
Notify that I've taken all files from form uploaded data first, and run your code in a foreach loop.
You need to handle an array in your upload method, as itll get that from the form, rather than an individual UploadedFile object.
/**
* #param UploadedFile $file
* #param $targetDir
* #return array
*/
public function upload($files, $targetDir)
{
if(!is_array($files)) {
$files = (array) $files; // cast to array in case of a form that isn't multiple.
}
$filenames = [];
foreach($files as $file) {
$filenames[] = md5(uniqid()).'.'.$file->guessExtension();
$file->move($targetDir, $fileName);
}
return $filenames;
}
youll need to twiddle whatever is getting the return filename variable, as it'll now be an array.
The other way, which in my opinion is a better UX, is to use a CollectionType and render a file input box per file. Heres a quick example.
$builder->add('file_uploads', CollectionType::class, [
'entry_type' => FileType::class,
'entry_options' => [
'label' => 'Photos du restaurant',
'multiple' => true,
'required' => false,
'mapped' => false,
'attr' => [
'accept' => '.jpg,.jpeg,.png',
],
'allow_add' => true,
'allow_delete' => true,
],
'prototype' => true,
]);
Youll then need to handle the resulting ArrayCollection in your upload handler. But this gives a much nicer interface for the user.
Ive not tested this snippet, so you might have to debug or adapt it to fit with what you're doing.
So, my problem is when I'm trying to update schema with command "dotrine:schema:update --force", entity are create but without any relation.
I have two entity "advert" and "category" and a relation ManyToMany on advert entity.
This is entyty advert :
<?php
namespace testBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Advert
*
* #ORM\Table(name="advert")
* #ORM\Entity(repositoryClass="testBundle\Repository\AdvertRepository")
*/
class Advert
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="categories", type="string", length=255)
* /**
* #ORM\ManyToMany(targetEntity="OC\PlatformBundle\Entity\Category", cascade={"persist"})
*/
private $categories;
public function __construct()
{
$this->date = new \Datetime();
$this->categories = new ArrayCollection();
}
// Notez le singulier, on ajoute une seule catégorie à la fois
public function addCategory(Category $category)
{
// Ici, on utilise l'ArrayCollection vraiment comme un tableau
$this->categories[] = $category;
}
public function removeCategory(Category $category)
{
// Ici on utilise une méthode de l'ArrayCollection, pour supprimer la catégorie en argument
$this->categories->removeElement($category);
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set categories
*
* #param string $categories
*
* #return Advert
*/
public function setCategories($categories)
{
$this->categories = $categories;
return $this;
}
/**
* Get categories
*
* #return string
*/
public function getCategories()
{
return $this->categories;
}
}
My entity category :
<?php
namespace testBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="testBundle\Repository\CategoryRepository")
*/
class Category
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
and this is the result of command doctrine:schema:update --force --dump-sql :
CREATE TABLE advert (id INT AUTO_INCREMENT NOT NULL, categories VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE category (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
Like you can see, no relation and no table advert_category
I found some topic about this but no solution working for me.
I hope someone can help me
Thank you !
Relation declared wrong, i think it should be something like this :
/**
* #ORM\ManyToMany(targetEntity="testBundle\Entity\Category")
* #ORM\JoinTable(name="advert_category")
*/
private $categories;
So problem fixed, I have to delete this :
*
* #ORM\Column(name="categories", type="string", length=255)
/**
and it's work , thank you #thomas !
I'm working on my portfolio, and I got a page where I show my project. I created 2 cayegorie for now: Programmation and artistic. Each of my project can be a programming project, an artistique project or both. There for, I made a table project and a table categorie and they are join with a many to many relationship. So far, no probleme.
I started to create my query in the repository file of my project entitie. The problem is when I try to join my project entitie and my categorie entitie, it doesn't look like it works, because I specefy that I want just the project that have at least programmation for categorie at least. But it still returns me ALL the project when it should only give me 2 of them.
Did I made my JOIN right?
Here are the entities (watch out for the french!):
Project:
<?php
namespace PublicBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Projet
*
* #ORM\Table(name="pt_projet");
* #ORM\Entity
* #ORM\Entity(repositoryClass="PublicBundle\Entity\ProjetDepot")
*/
class Projet
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
//ID du projet
protected $id;
/**
* #ORM\Column(name="pro_tag", type="string",length=255, unique=true)
*/
//Tag du projet
protected $tag;
/**
* #ORM\OneToMany(targetEntity="ProjetInt", mappedBy="projetId", orphanRemoval=true)
*/
protected $descriptions;
/**
* #ORM\Column(name="pro_img", type="string", length=64, unique=true)
*/
//Nom du fichier de l'image du projet
protected $image;
/**
* #ORM\Column(name="pro_technologie_utilisee", type="text", length=200)
*/
//Text qui liste tout les technologies utilisées pour le projet
protected $technologie;
/**
* #ORM\Column(name="pro_annee", type="integer", length=4)
*/
//Année de réalisation du projet
protected $annee;
/**
* #ORM\ManyToOne(targetEntity="Type", inversedBy="projets")
* #ORM\JoinColumn(name="pro_type", referencedColumnName="id", nullable=false)
*/
//Clef étrangère du type de projet
//Le type de projet ne correspond pas à la catégore. Il peu être Unity, flash, image, vidéo, etc. Il permet de savoir quelle page charger pour pouvoir intégrer le projet dans le portfolio.
protected $type;
/**
* #ORM\Column(name="pro_fichier", type="string", length=64, unique=true)
*/
//Nom du fichier du projet
private $fichier;
/**
* #ORM\ManyToMany(targetEntity="Categorie", cascade={"persist"})
*/
//La ou les catégories du projet
private $categories;
/**
* Constructor
*/
public function __construct()
{
$this->descriptions=new ArrayCollection();
$this->categories=new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set image
*
* #param string $image
* #return Projet
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set technologie
*
* #param string $technologie
* #return Projet
*/
public function setTechnologie($technologie)
{
$this->technologie = $technologie;
return $this;
}
/**
* Get technologie
*
* #return string
*/
public function getTechnologie()
{
return $this->technologie;
}
/**
* Set annee
*
* #param integer $annee
* #return Projet
*/
public function setAnnee($annee)
{
$this->annee = $annee;
return $this;
}
/**
* Get annee
*
* #return integer
*/
public function getAnnee()
{
return $this->annee;
}
/**
* Set fichier
*
* #param string $fichier
* #return Projet
*/
public function setFichier($fichier)
{
$this->fichier = $fichier;
return $this;
}
/**
* Get fichier
*
* #return string
*/
public function getFichier()
{
return $this->fichier;
}
/**
* Set type
*
* #param Type $type
* #return Projet
*/
public function setType(Type $type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return Type
*/
public function getType()
{
return $this->type;
}
/**
* Add categories
*
* #param Categorie $categories
* #return Projet
*/
public function addCategory(Categorie $categories)
{
$this->categories[] = $categories;
return $this;
}
/**
* Remove categories
*
* #param Categorie $categories
*/
public function removeCategory(Categorie $categories)
{
$this->categories->removeElement($categories);
}
/**
* Get categories
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
/**
* Add description
*
* #param \PublicBundle\Entity\ProjetInt $description
* #return Projet
*/
public function addDescription(\PublicBundle\Entity\ProjetInt $description)
{
$this->description[] = $description;
return $this;
}
/**
* Remove description
*
* #param \PublicBundle\Entity\ProjetInt $description
*/
public function removeDescription(\PublicBundle\Entity\ProjetInt $description)
{
$this->description->removeElement($description);
}
/**
* Get description
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDescription()
{
return $this->description;
}
}
Category:
<?php
namespace PublicBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Catégorie
*
* #ORM\Table(name="pt_categorie");
* #ORM\Entity
* #ORM\Entity(repositoryClass="PublicBundle\Entity\CategorieDepot")
*/
class Categorie
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
//ID de la catégorie
protected $id;
/**
* #ORM\Column(name="cat_tag", type="string",length=255, unique=true)
*/
//Tag de la catégorie
protected $tag;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set tag
*
* #param string $tag
* #return Categorie
*/
public function setTag($tag)
{
$this->tag = $tag;
return $this;
}
/**
* Get tag
*
* #return string
*/
public function getTag()
{
return $this->tag;
}
}
And the reposetory:
<?php
namespace PublicBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ProjetDepot
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ProjetDepot extends EntityRepository
{
public function rechercherProjets($lang, $cat)
{
return $this->getEntityManager()->createQuery(
'SELECT p.tag,
p.image,
pi.nom,
pi.descriptionCours,
pi.descriptionComplete,
pi.roles,
p.technologie,
pi.aptitudesDeveloppees,
p.annee
FROM PublicBundle:Projet p
JOIN PublicBundle:ProjetInt pi
WITH p.id=pi.projetId
JOIN PublicBundle:Categorie c
WHERE pi.langue=:lang
AND c.tag=:cat'
)->setParameters(array('lang'=>$lang,'cat'=>$cat))->getResult();
}
}
Try this
public function rechercherProjets($lang, $cat) {
$qb = $this->createQueryBuilder('p')
->innerJoin ('p.description', 'pi')
->innerJoin('p.categories', 'pc')
->andWhere('pc.tag = :cat')
->andWhere('pi.langue = :lang')
->setParameters(array('lang'=>$lang,'cat'=>$cat));
return $qb->getQuery()->getResult()
}
I generated the CRUD for the entity Evenement(event) , which is working. But now I want to update a field in another entity called notification everytime an Evenement is added. Each Evenement has a categorie
Evenement.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Mql14\mqlmeBundle\Entity\Evenement
*
* #ORM\Table(name="evenement")
* #ORM\Entity
*/
class Evenement
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $nom
*
* #ORM\Column(name="nom", type="string", length=45, nullable=true)
*/
private $nom;
/**
* #var datetime $date
*
* #ORM\Column(name="date", type="datetime", nullable=true)
*/
private $date;
/**
* #var string $description
*
* #ORM\Column(name="description", type="string", length=400, nullable=true)
*/
private $description;
/**
* #var integer $ticket
*
* #ORM\Column(name="Ticket", type="integer", nullable=true)
*/
private $ticket;
/**
* #var User
*
* #ORM\ManyToMany(targetEntity="User", mappedBy="evenement")
*/
private $user;
/**
* #var Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie", inversedBy="evenement")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="categorie_id", referencedColumnName="id")
* })
*/
private $categorie;
/**
* #var Lieu
*
* #ORM\ManyToOne(targetEntity="Lieu")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="lieu_id", referencedColumnName="id")
* })
*/
private $lieu;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
*/
public function setNom($nom)
{
$this->nom = $nom;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set date
*
* #param datetime $date
*/
public function setDate($date)
{
$this->date = $date;
}
/**
* Get date
*
* #return datetime
*/
public function getDate()
{
return $this->date;
}
/**
* Set description
*
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set ticket
*
* #param integer $ticket
*/
public function setTicket($ticket)
{
$this->ticket = $ticket;
}
/**
* Get ticket
*
* #return integer
*/
public function getTicket()
{
return $this->ticket;
}
/**
* Add user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function addUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user[] = $user;
}
/**
* Get user
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Set categorie
*
* #param Mql14\mqlmeBundle\Entity\Categorie $categorie
*/
public function setCategorie(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$this->categorie = $categorie;
}
/**
* Get categorie
*
* #return Mql14\mqlmeBundle\Entity\Categorie
*/
public function getCategorie()
{
return $this->categorie;
}
/**
* Set lieu
*
* #param Mql14\mqlmeBundle\Entity\Lieu $lieu
*/
public function setLieu(\Mql14\mqlmeBundle\Entity\Lieu $lieu)
{
$this->lieu = $lieu;
}
/**
* Get lieu
*
* #return Mql14\mqlmeBundle\Entity\Lieu
*/
public function getLieu()
{
return $this->lieu;
}
public function getCategorieId(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$idc= $categorie->getId();
return $idc;
}
}
Categorie.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mql14\mqlmeBundle\Entity\Categorie
*
* #ORM\Table(name="categorie")
* #ORM\Entity
*/
class Categorie
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $nomcat
*
* #ORM\Column(name="nomCat", type="string", length=45, nullable=true)
*/
private $nomcat;
/**
* #var string $photo
*
* #ORM\Column(name="photo", type="string", length=45, nullable=true)
*/
private $photo;
/**
* #var $evenement
*
* #ORM\OneToMany(targetEntity="Evenement", mappedBy="categorie")
*/
private $evenement;
/**
* #var User
*
* #ORM\ManyToMany(targetEntity="User", mappedBy="categorie")
*/
private $user;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nomcat
*
* #param string $nomcat
*/
public function setNomcat($nomcat)
{
$this->nomcat = $nomcat;
}
/**
* Get nomcat
*
* #return string
*/
public function getNomcat()
{
return $this->nomcat;
}
/**
* Set photo
*
* #param string $photo
*/
public function setPhoto($photo)
{
$this->photo = $photo;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto()
{
return $this->photo;
}
/**
* Add user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function addUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user[] = $user;
}
/**
* Get user
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Add evenement
*
* #param Mql14\mqlmeBundle\Entity\Categorie $evenement
*/
public function addEvenement(\Mql14\mqlmeBundle\Entity\Evenement $evenement)
{
$this->evenement[] = $evenement;
}
/**
* Get evenement
*
* #return Doctrine\Common\Collections\Collection
*/
public function getEvenement()
{
return $this->evenement;
}
}
Notification.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mql14\mqlmeBundle\Entity\Notification
*
* #ORM\Table(name="notification")
* #ORM\Entity
*/
class Notification
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $etat
*
* #ORM\Column(name="etat", type="integer", nullable=true)
*/
private $etat;
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="User_id", referencedColumnName="id")
*
* })
*/
private $user;
/**
* #var Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="Categorie_id", referencedColumnName="id")
*
* })
*/
private $categorie;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set etat
*
* #param string $etat
*/
public function setEtat($etat)
{
$this->etat = $etat;
}
/**
* Get etat
*
* #return string
*/
public function getEtat()
{
return $this->etat;
}
/**
* Set user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function setUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user = $user;
}
/**
* Get user
*
* #return Mql14\mqlmeBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set categorie
*
* #param Mql14\mqlmeBundle\Entity\Categorie $categorie
*/
public function setCategorie(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$this->categorie = $categorie;
}
/**
* Get categorie
*
* #return Mql14\mqlmeBundle\Entity\Categorie
*/
public function getCategorie()
{
return $this->categorie;
}
}
In the createAction that was generated after the execution of the CRUD for the Evenement entity I added the update query :
public function createAction(Request $request)
{
$entity = new Evenement();
$request = $this->getRequest();
$form = $this->createForm(new EvenementType(), $entity);
$form->bindRequest($request);
$entity->upload();
$cat=$entity->getCategorie();
if ($cat) {
$catn = $cat->getNomCat();
$query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie LIKE :catn ' );
$query->setParameter('categorie', $catn);
$query->execute();
}
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('mql14mqlme_adminshow', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
And the error I'm getting is this:
[Semantical Error] line 0, col 61 near 'categorie LIKE': Error:
Invalid PathExpression. Must be a StateFieldPathExpression.
You set the wrong parameter in the update query.
On this line:
$query = $this->container->get('doctrine')->getEntityManager()->createQuery(
'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1
WHERE n.categorie LIKE :catn' );
$query->setParameter('categorie', $catn);
$query->execute();
It should be:
$query = $this->container->get('doctrine')->getEntityManager()->createQuery(
'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1
WHERE n.categorie LIKE :catn' );
$query->setParameter('catn', $catn);
$query->execute();
n.categorie is an entity (of type Mql14\mqlmeBundle\Entity\Categorie) and you can't compare entities using LIKE.
Try replacing LIKE with =.
Change
UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie LIKE :catn
To
UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie = :catn
I am trying to upload files with Doctrine in Symfony2.
I followed all the steps in this tutorial tutorial but whene I submit my form I get no errors but the file is not uploaded and the path in the table "document" is null.
This is my entity
<?php
namespace projet\ClasseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Projet
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="projet\ClasseBundle\Entity\ProjetRepository")
* #ORM\HasLifecycleCallbacks
*/
class Projet
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="idMembre", type="integer")
*/
private $idMembre;
/**
* #var integer
*
* #ORM\Column(name="idAssociation", type="integer")
*/
private $idAssociation;
/**
* #var integer
*
* #ORM\Column(name="StatutProjet", type="integer")
*/
private $StatutProjet;
/**
* #var string
*
* #ORM\Column(name="nomProjet", type="string", length=255)
*/
private $nomProjet;
/**
* #var boolean
*
* #ORM\Column(name="visibilite", type="boolean")
*/
private $visibilite;
/**
* #var string
*
* #ORM\Column(name="dateDebut", type="string", length=255)
*/
private $dateDebut;
/**
* #var string
*
* #ORM\Column(name="dateFin", type="string", length=255)
*/
private $dateFin;
/**
* #var float
*
* #ORM\Column(name="budgetActuel", type="float", nullable=true)
*/
private $budgetActuel;
/**
* #var float
*
* #ORM\Column(name="budget", type="float")
*/
private $budget;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="ficheProjet", type="string", length=255, nullable=true)
*/
private $ficheProjet;
/**
* #Assert\File(maxSize="6000000")
*/
public $file;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set idMembre
*
* #param integer $idMembre
* #return Projet
*/
public function setIdMembre($idMembre)
{
$this->idMembre = $idMembre;
return $this;
}
/**
* Get idMembre
*
* #return integer
*/
public function getIdMembre()
{
return $this->idMembre;
}
/**
* Set idAssociation
*
* #param integer $idAssociation
* #return Projet
*/
public function setIdAssociation($idAssociation)
{
$this->idAssociation = $idAssociation;
return $this;
}
/**
* Get idAssociation
*
* #return integer
*/
public function getIdAssociation()
{
return $this->idAssociation;
}
/**
* Set StatutProjet
*
* #param integer $StatutProjet
* #return Tache
*/
public function setStatutProjet($StatutProjet)
{
$this->StatutProjet = $StatutProjet;
return $this;
}
/**
* Get StatutProjet
*
* #return integer
*/
public function getStatutProjet()
{
return $this->StatutProjet;
}
/**
* Set nomProjet
*
* #param string $nomProjet
* #return Projet
*/
public function setNomProjet($nomProjet)
{
$this->nomProjet = $nomProjet;
return $this;
}
/**
* Get nomProjet
*
* #return string
*/
public function getNomProjet()
{
return $this->nomProjet;
}
/**
* Set visibilite
*
* #param boolean $visibilite
* #return Projet
*/
public function setVisibilite($visibilite)
{
$this->visibilite = $visibilite;
return $this;
}
/**
* Get visibilite
*
* #return boolean
*/
public function getVisibilite()
{
return $this->visibilite;
}
/**
* Set dateDebut
*
* #param string $dateDebut
* #return Projet
*/
public function setDateDebut($dateDebut)
{
$this->dateDebut = $dateDebut;
return $this;
}
/**
* Get dateDebut
*
* #return string
*/
public function getDateDebut()
{
return $this->dateDebut;
}
/**
* Set dateFin
*
* #param string $dateFin
* #return Projet
*/
public function setDateFin($dateFin)
{
$this->dateFin = $dateFin;
return $this;
}
/**
* Get dateFin
*
* #return string
*/
public function getDateFin()
{
return $this->dateFin;
}
/**
* Set budget
*
* #param float $budget
* #return Projet
*/
public function setBudget($budget)
{
$this->budget = $budget;
return $this;
}
/**
* Get budget
*
* #return float
*/
public function getBudget()
{
return $this->budget;
}
/**
* Set budgetActuel
*
* #param float $budgetActuel
* #return Projet
*/
public function setBudgetActuel($budgetActuel)
{
$this->budgetActuel = $budgetActuel;
return $this;
}
/**
* Get budgetActuel
*
* #return float
*/
public function getBudgetActuel()
{
return $this->budgetActuel;
}
/**
* Set description
*
* #param string $description
* #return Projet
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set ficheProjet
*
* #param string $ficheProjet
* #return Projet
*/
public function setFicheProjet($ficheProjet)
{
$this->ficheProjet = $ficheProjet;
return $this;
}
/**
* Get ficheProjet
*
* #return string
*/
public function getFicheProjet()
{
return $this->ficheProjet;
}
public function getAbsolutePath()
{
return null === $this->ficheProjet ? null : $this->getUploadRootDir().'/'.$this->ficheProjet;
}
public function getWebPath()
{
return null === $this->ficheProjet ? null : $this->getUploadDir().'/'.$this->ficheProjet;
}
protected function getUploadRootDir()
{
// le chemin absolu du répertoire où les documents uploadés doivent être sauvegardés
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
// on se débarrasse de « __DIR__ » afin de ne pas avoir de problème lorsqu'on affiche
// le document/image dans la vue.
return 'uploads/documents';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
// faites ce que vous voulez pour générer un nom unique
$this->ficheProjet = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
// s'il y a une erreur lors du déplacement du fichier, une exception
// va automatiquement être lancée par la méthode move(). Cela va empêcher
// proprement l'entité d'être persistée dans la base de données si
// erreur il y a
$this->file->move($this->getUploadRootDir(), $this->ficheProjet);
unset($this->file);
}
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
}
NB : I mean ficheProjet by path.
Anny suggestion ? And thanks.
You should try to use Doctrine Uploadable Extension
You have to install the StofDoctrineExtensionBundle
After you should be able to add on your entity :
namespace My\Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* MyEntity
*
* #ORM\Table(name="my_entity")
* #ORM\Entity()
* #Gedmo\Uploadable(
* path="uploads/my_entity",
* allowOverwrite=true,
* allowedTypes="image/jpeg,image/pjpeg,image/png,image/x-png"
* )
*/
class MyEntity
{
//...
/**
* #var string
*
* #ORM\Column(name="picture", type="string", length=255, nullable=true)
* #Gedmo\UploadableFilePath
* #Assert\File(
* mimeTypes={"image/jpeg", "image/pjpeg", "image/png", "image/x-png"}
* )
*/
private $picture;
//...
}
Don't forget to create the upload folder and set right permissions:
mkdir -p web/uploads/my_entity
chmod -R 777 web/uploads