Use doctrine in entity - php

how can i get doctrine in entity to get permission list?
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Role\Role;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="`user`")
*/
class User implements UserInterface
{
private $entityManager;
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $discordId;
/**
* #ORM\Column(type="string", length=180)
*/
private $username;
/**
* #ORM\Column(type="string", length=255, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #ORM\OneToMany(targetEntity=Sites::class, mappedBy="owner", orphanRemoval=true)
*/
private $sites;
/**
* #ORM\PostLoad
* #ORM\PostPersist
*/
public function fetchEntityManager(LifecycleEventArgs $args)
{
$this->entityManager = $args->getEntityManager();
}
public function __construct()
{
$this->sites = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getdiscordId(): ?int
{
return $this->discordId;
}
public function setdiscordId(string $discordId): self
{
$this->discordId = $discordId;
return $this;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->username;
}
public function getRoles() :array
{
// get permissions from group
$groupPermissionsRepo = $this->entityManager->getRepository(GroupPermissions::class);
$groupAccessList = $groupPermissionsRepo->getPermissionsForGroup($this->getGroupId());
// create access
$accessList = [];
foreach ($groupAccessList as $access) {
$accessList[] = new Role('ROLE_'.$access);
}
// set default role when group didn't have any access granted
if(count($groupAccessList) == 0)
$accessList[] = new Role('ROLE_USER');
// return access
return $accessList;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
/**
* #return Collection<int, Sites>
*/
public function getSites(): Collection
{
return $this->sites;
}
public function addSite(Sites $site): self
{
if (!$this->sites->contains($site)) {
$this->sites[] = $site;
$site->setOwner($this);
}
return $this;
}
public function removeSite(Sites $site): self
{
if ($this->sites->removeElement($site)) {
// set the owning side to null (unless already changed)
if ($site->getOwner() === $this) {
$site->setOwner(null);
}
}
return $this;
}
}
While using this code i get only error:
App\Entity\User::fetchEntityManager(): Argument #1 ($args) must be of type Doctrine\Common\Persistence\Event\LifecycleEventArgs, Doctrine\ORM\Event\LifecycleEventArgs given, called in C:\xampp\htdocs\dbshop2\vendor\doctrine\orm\lib\Doctrine\ORM\Event\ListenersInvoker.php on line 84

Related

Symfony Delete an user with Foreign Key

I have a problem that i can't resolve. That's why i'm coming here.
On my website, an user can upload pictures and videos. When the user try to delete his account, he got a 500 error :
"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails"
If i understood, i have to use "joinColumn" "onCascade" and "onDelete" (I want to keep the user's pictures and videos)
My User entity :
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #UniqueEntity(fields={"email"}, message="Cette adresse email est déjà utilisée.")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
/**
* #ORM\Column(type="boolean")
*/
private $isVerified = false;
/**
* #ORM\OneToMany(targetEntity=Picture::class, mappedBy="author")
*/
private $pictures;
/**
* #ORM\OneToMany(targetEntity=Video::class, mappedBy="author")
*/
private $videos;
/**
* #ORM\ManyToMany(targetEntity=Picture::class, mappedBy="fav")
*/
private $favoris;
/**
* #ORM\ManyToMany(targetEntity=Video::class, mappedBy="fav")
*/
private $fav;
public function __construct()
{
$this->pictures = new ArrayCollection();
$this->videos = new ArrayCollection();
$this->favoris = new ArrayCollection();
$this->fav = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* #see UserInterface
*/
public function getSalt(): ?string
{
return null;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
/**
* #return Collection|Picture[]
*/
public function getPictures(): Collection
{
return $this->pictures;
}
public function addPicture(Picture $picture): self
{
if (!$this->pictures->contains($picture)) {
$this->pictures[] = $picture;
$picture->setAuthor($this);
}
return $this;
}
public function removePicture(Picture $picture): self
{
if ($this->pictures->removeElement($picture)) {
// set the owning side to null (unless already changed)
if ($picture->getAuthor() === $this) {
$picture->setAuthor(null);
}
}
return $this;
}
/**
* #return Collection|Video[]
*/
public function getVideos(): Collection
{
return $this->videos;
}
public function addVideo(Video $video): self
{
if (!$this->videos->contains($video)) {
$this->videos[] = $video;
$video->setAuthor($this);
}
return $this;
}
public function removeVideo(Video $video): self
{
if ($this->videos->removeElement($video)) {
// set the owning side to null (unless already changed)
if ($video->getAuthor() === $this) {
$video->setAuthor(null);
}
}
return $this;
}
/**
* #return Collection|Picture[]
*/
public function getFavoris(): Collection
{
return $this->favoris;
}
public function addFavori(Picture $favori): self
{
if (!$this->favoris->contains($favori)) {
$this->favoris[] = $favori;
$favori->addFav($this);
}
return $this;
}
public function removeFavori(Picture $favori): self
{
if ($this->favoris->removeElement($favori)) {
$favori->removeFav($this);
}
return $this;
}
/**
* #return Collection|Video[]
*/
public function getFav(): Collection
{
return $this->fav;
}
public function addFav(Video $fav): self
{
if (!$this->fav->contains($fav)) {
$this->fav[] = $fav;
$fav->addFav($this);
}
return $this;
}
public function removeFav(Video $fav): self
{
if ($this->fav->removeElement($fav)) {
$fav->removeFav($this);
}
return $this;
}
}
My Picture entity :
<?php
namespace App\Entity;
use App\Repository\PictureRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* #ORM\Entity(repositoryClass=PictureRepository::class)
*/
class Picture
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=150)
*/
private $title;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Gedmo\Slug(fields={"title"})
*/
private $slug;
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
/**
* #ORM\Column(type="datetime")
*/
private $publication_date;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="pictures")
* #ORM\JoinColumn(nullable=false)
*/
private $author;
/**
* #ORM\Column(type="string", length=150)
*/
private $category;
/**
* #ORM\Column(type="string", length=50)
*/
private $image;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="favoris")
*/
private $fav;
public function __construct()
{
$this->fav = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getPublicationDate(): ?\DateTimeInterface
{
return $this->publication_date;
}
public function setPublicationDate(\DateTimeInterface $publication_date): self
{
$this->publication_date = $publication_date;
return $this;
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): self
{
$this->author = $author;
return $this;
}
public function getCategory(): ?string
{
return $this->category;
}
public function setCategory(string $category): self
{
$this->category = $category;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
/**
* #return Collection|User[]
*/
public function getFav(): Collection
{
return $this->fav;
}
public function addFav(User $fav): self
{
if (!$this->fav->contains($fav)) {
$this->fav[] = $fav;
}
return $this;
}
public function removeFav(User $fav): self
{
$this->fav->removeElement($fav);
return $this;
}
}
My Video entity :
<?php
namespace App\Entity;
use App\Repository\VideoRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=VideoRepository::class)
*/
class Video
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=150)
*/
private $title;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="datetime")
*/
private $publication_date;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="videos")
* #ORM\JoinColumn(nullable=false)
*/
private $author;
/**
* #ORM\Column(type="string", length=150)
*/
private $category;
/**
* #ORM\Column(type="string", length=50)
*/
private $vid;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="fav")
*/
private $fav;
public function __construct()
{
$this->fav = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getPublicationDate(): ?\DateTimeInterface
{
return $this->publication_date;
}
public function setPublicationDate(\DateTimeInterface $publication_date): self
{
$this->publication_date = $publication_date;
return $this;
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): self
{
$this->author = $author;
return $this;
}
public function getCategory(): ?string
{
return $this->category;
}
public function setCategory(string $category): self
{
$this->category = $category;
return $this;
}
public function getVid(): ?string
{
return $this->vid;
}
public function setVid(string $vid): self
{
$this->vid = $vid;
return $this;
}
/**
* #return Collection|User[]
*/
public function getFav(): Collection
{
return $this->fav;
}
public function addFav(User $fav): self
{
if (!$this->fav->contains($fav)) {
$this->fav[] = $fav;
}
return $this;
}
public function removeFav(User $fav): self
{
$this->fav->removeElement($fav);
return $this;
}
}
If you want to - when deleting a user - delete all his pictures and videos as well, you can just add cascade delete to the associations:
/**
* #ORM\OneToMany(targetEntity=Picture::class, mappedBy="author", cascade={"delete"})
*/
private $pictures;
/**
* #ORM\OneToMany(targetEntity=Video::class, mappedBy="author", cascade={"delete"})
*/
private $videos;
If you instead want to keep them and just remove the associoation to the user, add ON DELETE SET NULL to your author_id foreign keys in picture and video tables:
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="videos")
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $author;
Then you have to assume in your code that $this->author can be null.

Symfony 4.2 - Doctrine / schema:validate => The table with name 'fablab.appartment_user already exists

beginner here i'm trying to do an API with Api-platform and Symfony. Actually i want to create my database schema and start testing it but when using php bin/console doctrine:schema:validate, i got this error and i cant figure out how to fix it : The table with name 'mydb.appartment_user' already exists
Unfortunately i didnt found an answer on google to my problem :'(
Here is my appartement entity :
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\AppartmentRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ApiResource()
* #ORM\Entity(repositoryClass=AppartmentRepository::class)
*/
class Appartment
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $adress;
/**
* #ORM\Column(type="string", length=255)
*/
private $latitude;
/**
* #ORM\Column(type="string", length=255)
*/
private $longitude;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="occupied_appartments")
*/
private $current_tenant;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="rented_appartments")
*/
private $landlord;
/**
* #ORM\OneToOne(targetEntity=Lock::class, cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $lock_id;
public function __construct()
{
$this->current_tenant = new ArrayCollection();
$this->landlord = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getAdress(): ?string
{
return $this->adress;
}
public function setAdress(string $adress): self
{
$this->adress = $adress;
return $this;
}
public function getLatitude(): ?string
{
return $this->latitude;
}
public function setLatitude(string $latitude): self
{
$this->latitude = $latitude;
return $this;
}
public function getLongitude(): ?string
{
return $this->longitude;
}
public function setLongitude(string $longitude): self
{
$this->longitude = $longitude;
return $this;
}
/**
* #return Collection|User[]
*/
public function getCurrentTenant(): Collection
{
return $this->current_tenant;
}
public function addCurrentTenant(User $currentTenant): self
{
if (!$this->current_tenant->contains($currentTenant)) {
$this->current_tenant[] = $currentTenant;
}
return $this;
}
public function removeCurrentTenant(User $currentTenant): self
{
$this->current_tenant->removeElement($currentTenant);
return $this;
}
/**
* #return Collection|User[]
*/
public function getLandlord(): Collection
{
return $this->landlord;
}
public function addLandlord(User $landlord): self
{
if (!$this->landlord->contains($landlord)) {
$this->landlord[] = $landlord;
}
return $this;
}
public function removeLandlord(User $landlord): self
{
$this->landlord->removeElement($landlord);
return $this;
}
public function getLockId(): ?Lock
{
return $this->lock_id;
}
public function setLockId(Lock $lock_id): self
{
$this->lock_id = $lock_id;
return $this;
}
}
and my user entity :
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\Table(name="`user`")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
/**
* #ORM\Column(type="string", length=255)
*/
private $firstname;
/**
* #ORM\Column(type="string", length=255)
*/
private $lastname;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $profile_picture;
/**
* #ORM\ManyToMany(targetEntity=Appartment::class, mappedBy="current_tenant")
*/
private $occupied_appartments;
/**
* #ORM\ManyToMany(targetEntity=Appartment::class, mappedBy="landlord")
*/
private $rented_appartments;
/**
* #ORM\ManyToMany(targetEntity=Rental::class, mappedBy="tenant_id")
*/
private $tenant_rentals;
/**
* #ORM\ManyToMany(targetEntity=Rental::class, mappedBy="landlord_id")
*/
private $landlord_rentals;
public function __construct()
{
$this->occupied_appartments = new ArrayCollection();
$this->rented_appartments = new ArrayCollection();
$this->tenant_rentals = new ArrayCollection();
$this->landlord_rentals = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getLastname(): ?string
{
return $this->lastname;
}
public function setLastname(string $lastname): self
{
$this->lastname = $lastname;
return $this;
}
public function getProfilePicture(): ?string
{
return $this->profile_picture;
}
public function setProfilePicture(?string $profile_picture): self
{
$this->profile_picture = $profile_picture;
return $this;
}
/**
* #return Collection|Appartment[]
*/
public function getOccupiedAppartments(): Collection
{
return $this->occupied_appartments;
}
public function addOccupiedAppartment(Appartment $occupied_appartments): self
{
if (!$this->occupied_appartments->contains($occupied_appartments)) {
$this->occupied_appartments[] = $occupied_appartments;
$occupied_appartments->addCurrentTenant($this);
}
return $this;
}
public function removeOccupiedAppartment(Appartment $occupied_appartments): self
{
if ($this->occupied_appartments->removeElement($occupied_appartments)) {
$occupied_appartments->removeCurrentTenant($this);
}
return $this;
}
/**
* #return Collection|Appartment[]
*/
public function getRentedAppartments(): Collection
{
return $this->rented_appartments;
}
public function addRentedAppartment(Appartment $rentedAppartment): self
{
if (!$this->rented_appartments->contains($rentedAppartment)) {
$this->rented_appartments[] = $rentedAppartment;
$rentedAppartment->addLandlord($this);
}
return $this;
}
public function removeRentedAppartment(Appartment $rentedAppartment): self
{
if ($this->rented_appartments->removeElement($rentedAppartment)) {
$rentedAppartment->removeLandlord($this);
}
return $this;
}
/**
* #return Collection|Rental[]
*/
public function getTenantRentals(): Collection
{
return $this->tenant_rentals;
}
public function addTenantRental(Rental $tenantRental): self
{
if (!$this->tenant_rentals->contains($tenantRental)) {
$this->tenant_rentals[] = $tenantRental;
$tenantRental->addTenantId($this);
}
return $this;
}
public function removeTenantRental(Rental $tenantRental): self
{
if ($this->tenant_rentals->removeElement($tenantRental)) {
$tenantRental->removeTenantId($this);
}
return $this;
}
/**
* #return Collection|Rental[]
*/
public function getLandlordRentals(): Collection
{
return $this->landlord_rentals;
}
public function addLandlordRental(Rental $landlordRental): self
{
if (!$this->landlord_rentals->contains($landlordRental)) {
$this->landlord_rentals[] = $landlordRental;
$landlordRental->addLandlordId($this);
}
return $this;
}
public function removeLandlordRental(Rental $landlordRental): self
{
if ($this->landlord_rentals->removeElement($landlordRental)) {
$landlordRental->removeLandlordId($this);
}
return $this;
}
}
I tried to clear-cache and to force but it didnt work.
Thank's in advance for help and ask me if I forget any details !
add a JoinTable annotation for properties which have ManyToMany relation in Appartment entity
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="occupied_appartments")
* #ORM\JoinTable(name="appartment_current_tenant")
*/
private $current_tenant;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="rented_appartments")
* #ORM\JoinTable(name="appartment_landlord")
*/
private $landlord;

SQLSTATE[42S22]: Column not found: 1054 Champ 't0.id' inconnu dans where clause ( Symfony 5 , API Platform )

I have 2 classes , Class Child "Livreur" inherite from Class Parent "Users" .
Problem in return data after insert by API Plateform . (it inserted by success but data deosn't returned + doesn't insert in table Users, before that it inserted in Users+Livreur but now no ).
Class "Users" (parent) :
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\UsersRepository;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping ;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass=UsersRepository::class)
* #ApiResource(
* normalizationContext={"groups"={"read"}},
* collectionOperations={"post"={},"get"={}},
* itemOperations={"get","put"={"denormalization_Context"={"groups"={"put"}}}}
* )
*/
class Users implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180)
* #Groups({"read"})
*/
private $email;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=255)
* #Groups({"read"})
* #Groups({"put"})
*/
private $password;
/**
* #Assert\NotBlank()
* #Assert\Expression("this.getPassword() == this.getRepassword()",message="Mot de pass doit etre le meme dans les 2 deux champs")
*/
private $repassword;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=30)
* #Groups({"read"})
* #Groups({"put"})
*/
private $username;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text")
* #Groups({"read"})
* #Groups({"put"})
*/
private $roles;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=20)
* #Groups({"read"})
*/
private $cin;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=20)
* #Groups({"read"})
*/
private $nom;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=20)
* #Groups({"read"})
*/
private $prenom;
/**
* #Assert\NotBlank()
* #ORM\Column(type="date")
* #Groups({"read"})
*/
private $dtn;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=255, nullable=true)
* #Groups({"read"})
*/
private $dtype;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=255, nullable=true)
* #Groups({"read"})
*/
private $img;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=30, nullable=true)
* #Groups({"read"})
* #Groups({"put"})
*/
private $rib;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Groups({"read"})
* #Groups({"put"})
*/
private $adresse;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", length=20)
* #Groups({"read"})
* #Groups({"put"})
*/
private $tel;
protected function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getRoles(): array
{
return array('ROLE_USER');
}
public function setRoles(string $roles): self
{
$this->roles = $roles;
return $this;
}
public function getCin(): ?string
{
return $this->cin;
}
public function setCin(string $cin): self
{
$this->cin = $cin;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getDtn(): ?\DateTimeInterface
{
return $this->dtn;
}
public function setDtn(\DateTimeInterface $dtn): self
{
$this->dtn = $dtn;
return $this;
}
public function getDtype(): ?string
{
return $this->dtype;
}
public function setDtype(?string $dtype): self
{
$this->dtype = $dtype;
return $this;
}
public function getImg(): ?string
{
return $this->img;
}
public function setImg(?string $img): self
{
$this->img = $img;
return $this;
}
public function getRib(): ?string
{
return $this->rib;
}
public function setRib(?string $rib): self
{
$this->rib = $rib;
return $this;
}
public function getAdresse(): ?string
{
return $this->adresse;
}
public function setAdresse(?string $adresse): self
{
$this->adresse = $adresse;
return $this;
}
public function getTel(): ?string
{
return $this->tel;
}
public function setTel(string $tel): self
{
$this->tel = $tel;
return $this;
}
public function getSalt()
{
// TODO: Implement getSalt() method.
}
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
public function getRepassword()
{
return $this->repassword;
}
public function setRepassword($repassword): void
{
$this->repassword = $repassword;
}
}
Class Livreur (child) :
<?php
namespace App\Entity;
use App\Repository\LivreurRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Core\Annotation\ApiResource;
/**
* #ORM\Entity(repositoryClass=LivreurRepository::class)
* #ApiResource()
*/
class Livreur extends Users
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=20)
*/
private $type_vehicule;
/**
* #ORM\Column(type="string", length=20)
*/
private $permis;
/**
* #ORM\Column(type="boolean")
*/
private $disponibilite;
/**
* #ORM\Column(type="float")
*/
private $coffre;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $log;
/**
* #ORM\OneToMany(targetEntity=Commande::class, mappedBy="livreur")
*/
private $commandes;
/**
* #ORM\OneToMany(targetEntity=Conge::class, mappedBy="livreur")
*/
private $conges;
/**
* #ORM\ManyToOne(targetEntity=Agence::class, inversedBy="livreurs")
* #ORM\JoinColumn(nullable=false)
*/
private $agence;
/**
* #ORM\OneToOne(targetEntity=SalaireEmp::class, inversedBy="livreur", cascade={"persist", "remove"})
*/
private $salaire_emp;
/**
* #ORM\ManyToOne(targetEntity=Ville::class, inversedBy="livreurs")
* #ORM\JoinColumn(nullable=false)
*/
private $ville;
public function __construct()
{
$this->commandes = new ArrayCollection();
$this->conges = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTypeVehicule(): ?string
{
return $this->type_vehicule;
}
public function setTypeVehicule(string $type_vehicule): self
{
$this->type_vehicule = $type_vehicule;
return $this;
}
public function getPermis(): ?string
{
return $this->permis;
}
public function setPermis(string $permis): self
{
$this->permis = $permis;
return $this;
}
public function getDisponibilite(): ?int
{
return $this->disponibilite;
}
public function setDisponibilite(int $disponibilite): self
{
$this->disponibilite = $disponibilite;
return $this;
}
public function getCoffre(): ?float
{
return $this->coffre;
}
public function setCoffre(float $coffre): self
{
$this->coffre = $coffre;
return $this;
}
public function getLog(): ?string
{
return $this->log;
}
public function setLog(?string $log): self
{
$this->log = $log;
return $this;
}
/**
* #return Collection|Commande[]
*/
public function getCommandes(): Collection
{
return $this->commandes;
}
public function addCommande(Commande $commande): self
{
if (!$this->commandes->contains($commande)) {
$this->commandes[] = $commande;
$commande->setLivreur($this);
}
return $this;
}
public function removeCommande(Commande $commande): self
{
if ($this->commandes->removeElement($commande)) {
// set the owning side to null (unless already changed)
if ($commande->getLivreur() === $this) {
$commande->setLivreur(null);
}
}
return $this;
}
/**
* #return Collection|Conge[]
*/
public function getConges(): Collection
{
return $this->conges;
}
public function addConge(Conge $conge): self
{
if (!$this->conges->contains($conge)) {
$this->conges[] = $conge;
$conge->setLivreur($this);
}
return $this;
}
public function removeConge(Conge $conge): self
{
if ($this->conges->removeElement($conge)) {
// set the owning side to null (unless already changed)
if ($conge->getLivreur() === $this) {
$conge->setLivreur(null);
}
}
return $this;
}
public function getAgence(): ?Agence
{
return $this->agence;
}
public function setAgence(?Agence $agence): self
{
$this->agence = $agence;
return $this;
}
public function getSalaireEmp(): ?SalaireEmp
{
return $this->salaire_emp;
}
public function setSalaireEmp(?SalaireEmp $salaire_emp): self
{
$this->salaire_emp = $salaire_emp;
return $this;
}
public function getVille(): ?Ville
{
return $this->ville;
}
public function setVille(?Ville $ville): self
{
$this->ville = $ville;
return $this;
}
}
Looks like you forgot to set an inheritance mapping strategy. Here is an example:
// (..)
/**
* #ORM\Entity(repositoryClass=UsersRepository::class)
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({"users" = "Users", "livreur" = "Livreur"})
* #ApiResource(
* normalizationContext={"groups"={"read"}},
* collectionOperations={"post"={},"get"={}},
* itemOperations={"get","put"={"denormalization_Context"={"groups"={"put"}}}}
* )
*/
class Users implements UserInterface
{
// (..)
This will add an extra field "discr" to the tables of both your classes so you will have to update their table configurations, for example with:
bin/console doctrine:schema:update --force
or if you use migrations:
bin/console doctrine:migrations:diff
bin/console doctrine:migrations:migrate
For explanation of Mapping Strategies and their alternatives see the Inheritance Mapping page on doctrine-project.org

#Doctrine\ORM\Mapping\ "Annotation was never imported"

so i'm new to Doctrine and PHP in general and i have a small issue that i don't know how to fix...
I need to create a PHP app (using Doctrine) and to make communication with the DB my predecessor used Doctrine ORM; so i tried to use one of his files as a templates to make my part of the app but it does not seem to work...
First, his file used as template:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
* #UniqueEntity("email")
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
* #Groups({"campaign_get", "user_logged"})
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
* #Assert\NotBlank
* #Assert\Email
* #Groups({"campaign_get", "user_logged"})
*/
private $email;
/**
* #var string The hashed password
* #ORM\Column(type="string")
* #Assert\NotBlank
* #Assert\Regex(
* pattern="/^(?=.{8,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$/",
* message="Votre mot de passe doit contenir au moins 1 chiffre, 1 majuscule, 1 minuscule et avoir une longueur d'au moins 8 caractères."
* )
*/
private $password;
/**
* #ORM\Column(type="string", length=100)
* #Assert\NotBlank
* #Groups("campaign_get")
*/
private $firstname;
/**
* #ORM\Column(type="string", length=100)
* #Assert\NotBlank
* #Groups("campaign_get")
*/
private $lastname;
/**
* #ORM\Column(type="boolean")
*/
private $status;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $idInstagram;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $idFacebook;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $idYoutube;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $idSnapchat;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $idTiktok;
/**
* #ORM\Column(type="datetime")
*/
private $createdAt;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $updatedAt;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Role")
* #Groups("campaign_get")
*/
private $userRoles;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Article", mappedBy="users")
*/
private $articles;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $companyName;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Campaign", mappedBy="users")
*/
private $campaigns;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $resetToken;
public function __construct()
{
$this->userRoles = new ArrayCollection();
$this->articles = new ArrayCollection();
$this->status = 1;
$this->createdAt = new \DateTime();
$this->campaigns = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->userRoles;
$userRoles = [];
foreach ($roles as $role) {
$userRoles[] = $role->getName();
}
return $userRoles;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getLastname(): ?string
{
return $this->lastname;
}
public function setLastname(string $lastname): self
{
$this->lastname = $lastname;
return $this;
}
public function getStatus(): ?bool
{
return $this->status;
}
public function setStatus(bool $status): self
{
$this->status = $status;
return $this;
}
public function getIdInstagram(): ?string
{
return $this->idInstagram;
}
public function setIdInstagram(?string $idInstagram): self
{
$this->idInstagram = $idInstagram;
return $this;
}
public function getIdFacebook(): ?string
{
return $this->idFacebook;
}
public function setIdFacebook(?string $idFacebook): self
{
$this->idFacebook = $idFacebook;
return $this;
}
public function getIdYoutube(): ?string
{
return $this->idYoutube;
}
public function setIdYoutube(?string $idYoutube): self
{
$this->idYoutube = $idYoutube;
return $this;
}
public function getIdSnapchat(): ?string
{
return $this->idSnapchat;
}
public function setIdSnapchat(?string $idSnapchat): self
{
$this->idSnapchat = $idSnapchat;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
public function getIdTiktok(): ?string
{
return $this->idTiktok;
}
public function setIdTiktok(?string $idTiktok): self
{
$this->idTiktok = $idTiktok;
return $this;
}
/**
* #return Collection|Role[]
*/
public function getUserRoles(): Collection
{
return $this->userRoles;
}
public function addUserRole(Role $userRole): self
{
if (!$this->userRoles->contains($userRole)) {
$this->userRoles[] = $userRole;
}
return $this;
}
public function removeUserRole(Role $userRole): self
{
if ($this->userRoles->contains($userRole)) {
$this->userRoles->removeElement($userRole);
}
return $this;
}
/**
* #return Collection|Article[]
*/
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Article $article): self
{
if (!$this->articles->contains($article)) {
$this->articles[] = $article;
$article->addUser($this);
}
return $this;
}
public function removeArticle(Article $article): self
{
if ($this->articles->contains($article)) {
$this->articles->removeElement($article);
$article->removeUser($this);
}
return $this;
}
public function getCompanyName(): ?string
{
return $this->companyName;
}
public function setCompanyName(?string $companyName): self
{
$this->companyName = $companyName;
return $this;
}
/**
* #return Collection|Campaign[]
*/
public function getCampaigns(): Collection
{
return $this->campaigns;
}
public function addCampaign(Campaign $campaign): self
{
if (!$this->campaigns->contains($campaign)) {
$this->campaigns[] = $campaign;
$campaign->addUser($this);
}
return $this;
}
public function removeCampaign(Campaign $campaign): self
{
if ($this->campaigns->contains($campaign)) {
$this->campaigns->removeElement($campaign);
$campaign->removeUser($this);
}
return $this;
}
public function getResetToken(): ?string
{
return $this->resetToken;
}
public function setResetToken(?string $resetToken): self
{
$this->resetToken = $resetToken;
return $this;
}
}
Then, mine using the same philosophy:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* #ORM\Entity(repositoryClass="App\Repository\AgencyRepository")
*/
class Agency
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\nameAgency()
* #ORM\Column(type"string")
*/
private $nameAgency;
/**
* #ORM\nameContact
* #ORM\Column(type="string")
* #Assert\NotBlank
*/
private $nameContact;
}
Then i try to run this:
php bin/console doctrine:migrations:diff
into a terminal to update the DB, it works fine with the previous file (User Class) but mine (Agency Class) throw a error:
[Semantical Error] The annotation "#Doctrine\ORM\Mapping\nameAgency" in property App\Entity\Agency::$nameAgency was never imported. Did you maybe forget to add
a "use" statement for this annotation?
At first i thought it was an issue with import, so i made exactly the sames imports as in User Class but the error is still present.
Googling the error lead me to a github issue that leeds to this as a fix; but it doesn't seems to work's for me...
What should i do to fix this issue?
You are using
#ORM\nameAgency()
obviously this annotation does not exist, why do you have it there?
Remove #ORM\nameAgency() and #ORM\nameContact, it doesn't make any sense.
Explanation: by #ORM\nameAgency() you actually mean Doctrine\ORM\Mapping\nameAgency and this annotation naturally doesn't exist in Doctrine.

EntityType form returns a String instead of object

I have a user entity that has a many-to-many relationship with another entity Roles.
I have a form that allows me to create a new user and for that, I use an EntityType for the manyToMany relationship 'roles'.
Here is my form
$builder
->add('username',null,['label' => 'Email'])
->add('password',null,['label'=>'Password'])
->add('roles',EntityType::class, [
'multiple' => true,
'class' => Role::class,
'choice_label' => 'role_name',
]
)
;
Everything works fine but when I submit the form I got this error:
Expected argument of type "App\Entity\Role", "string" given at
property path "roles".
EDIT:
here is my User entity :
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $username;
/**
* #ORM\Column(type="string", length=255)
*/
private $password;
/**
* #ORM\ManyToMany(targetEntity=Role::class, inversedBy="users")
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getRoles()
{
return ['ROLE_ADMIN'];
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function addRole(Role $role): self
{
if (!$this->roles->contains($role)) {
$this->roles[] = $role;
$role->addUser($this);
}
return $this;
}
public function removeRole(Role $role): self
{
if ($this->roles->contains($role)) {
$this->roles->removeElement($role);
$role->removeUser($this);
}
return $this;
}
}
Here is my Role entity :
<?php
namespace App\Entity;
use App\Repository\RoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=RoleRepository::class)
*/
class Role
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $role_name;
/**
* #ORM\ManyToMany(targetEntity=User::class, mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRoleName(): ?string
{
return $this->role_name;
}
public function setRoleName(string $role_name): self
{
$this->role_name = $role_name;
return $this;
}
/**
* #return Collection|User[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->contains($user)) {
$this->users->removeElement($user);
}
return $this;
}
}
I guess the problem is here
public function getRoles()
{
return ['ROLE_ADMIN'];
}
you should return an array or Role entity not string, it should be something like this
public function getRoles()
{
return $this->roles;
}
what if i'm using ArrayCollection in User entity?
/**
* #var Collection|Role[]
* #ORM\ManyToMany(targetEntity="App\Entity\Role")
* #ORM\JoinTable(
* name="user_roles",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getRoles()
{
return $this->roles;
}

Categories