I'm stuck with this error:
Mapping "paint_images" does not exist. The configuration for the class "App\Entity\Painting" is probably incorrect as the mapping to use for the field "imageFile" could not be found. I'm on symfony 5.4.10. Problem occurs when creating a new painting.
I put you the entity that where the problem would come from :
´´´
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\PeintureRepository;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\File\File;
use Doctrine\Common\Collections\ArrayCollection;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use App\Entity\Categorie;
/**
* #ORM\Entity(repositoryClass=PeintureRepository::class)
* #Vich\Uploadable
*/
class Peinture
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $nom;
/**
* #ORM\Column(type="decimal", precision=6, scale=2, nullable=true)
*/
private $largeur;
/**
* #ORM\Column(type="decimal", precision=6, scale=2, nullable=true)
*/
private $hauteur;
/**
* #ORM\Column(type="boolean")
*/
private $enVente;
/**
* #ORM\Column(type="decimal", precision=10, scale=2, nullable=true)
*/
private $prix;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $dateRealisation;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $date;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="boolean")
*/
private $portefolio;
/**
* #ORM\Column(type="string", length=255)
*/
private $slug;
/**
* #ORM\Column(type="string", length=255)
*/
private $file;
/**
* #Vich\UploadableField(mapping="peinture_images", fileNameProperty="file")
* #var File
*/
private $imageFile;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="peintures")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #ORM\ManyToMany(targetEntity=Categorie::class, inversedBy="peintures")
*/
private $categorie;
/**
* #ORM\OneToMany(targetEntity=Commentaire::class, mappedBy="peinture")
*/
private $commentaires;
public function __construct()
{
$this->categorie = new ArrayCollection();
$this->commentaires = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getLargeur(): ?string
{
return $this->largeur;
}
public function setLargeur(?string $largeur): self
{
$this->largeur = $largeur;
return $this;
}
public function getHauteur(): ?string
{
return $this->hauteur;
}
public function setHauteur(?string $hauteur): self
{
$this->hauteur = $hauteur;
return $this;
}
public function isEnVente(): ?bool
{
return $this->enVente;
}
public function setEnVente(bool $enVente): self
{
$this->enVente = $enVente;
return $this;
}
public function getPrix(): ?string
{
return $this->prix;
}
public function setPrix(?string $prix): self
{
$this->prix = $prix;
return $this;
}
public function getDateRealisation(): ?\DateTimeInterface
{
return $this->dateRealisation;
}
public function setDateRealisation(?\DateTimeInterface $dateRealisation): self
{
$this->dateRealisation = $dateRealisation;
return $this;
}
public function getDate(): ?\DateTimeInterface
{
return $this->date;
}
public function setDate(?\DateTimeInterface $date): self
{
$this->date = $date;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function isPortefolio(): ?bool
{
return $this->portefolio;
}
public function setPortefolio(bool $portefolio): self
{
$this->portefolio = $portefolio;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getFile(): ?string
{
return $this->file;
}
public function setFile(string $file): self
{
$this->file = $file;
return $this;
}
public function setImageFile(File $file=null)
{
$this->file = $file;
if($file) {
$this->date = new \DateTime('now');
}
}
public function getImageFile()
{
return $this->imageFile;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
/**
* #return Collection<int, Categorie>
*/
public function getCategorie(): Collection
{
return $this->categorie;
}
public function addCategorie(Categorie $categorie): self
{
if (!$this->categorie->contains($categorie)) {
$this->categorie[] = $categorie;
}
return $this;
}
public function removeCategorie(Categorie $categorie): self
{
$this->categorie->removeElement($categorie);
return $this;
}
/**
* #return Collection<int, Commentaire>
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
public function addCommentaire(Commentaire $commentaire): self
{
if (!$this->commentaires->contains($commentaire)) {
$this->commentaires[] = $commentaire;
$commentaire->setPeinture($this);
}
return $this;
}
public function removeCommentaire(Commentaire $commentaire): self
{
if ($this->commentaires->removeElement($commentaire)) {
// set the owning side to null (unless already changed)
if ($commentaire->getPeinture() === $this) {
$commentaire->setPeinture(null);
}
}
return $this;
}
}
´´´
Related
I'm trying to keep user in the login page if his email address is not verified yet after registration and he tries to login in.
This is the User class:
<?php
namespace App\Entity;
use App\Repository\UserRepository;
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={"cin"}, message="CIN utilisé par un autre utilisateur!")
* #UniqueEntity(fields={"email"}, message="Email utilisé par un autre utilisateur!")
* #UniqueEntity(fields={"idScout"}, message="Identifiant Scout utilisé par un autre utilisateur!")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, nullable=true, 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=180, nullable=true, unique=true)
*/
private $cin;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $prenom;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $nom;
/**
* #ORM\Column(type="string", length=180, nullable=true, unique=true)
*/
private $idScout;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateNaissance;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $groupe;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $region;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $branche;
// /**
// * #ORM\Column(type="string", length=255, nullable=true)
// */
// private $niveauFormation;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $niveauEducation;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $profession;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $tel;
/**
* #ORM\Column(type="boolean")
*/
private $isVerified = false;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $formationPrimaire;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateFormationPrimaire;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $formationPreliminaire;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateFormationPreliminaire;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $formationBadge;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateFormationBadge;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $M1;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $M2;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateM1;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateM2;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $M3;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateM3;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $S1;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateS1;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $S2;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateS2;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
private $S3;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateS3;
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;
return (string) $this->cin;
}
/**
* #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 $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 getCin(): ?string
{
return $this->cin;
}
public function setCin(?string $cin): self
{
$this->cin = $cin;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(?string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(?string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getIdScout(): ?string
{
return $this->idScout;
}
public function setIdScout(?string $idScout): self
{
$this->idScout = $idScout;
return $this;
}
public function getDateNaissance(): ?\DateTimeInterface
{
return $this->dateNaissance;
}
public function setDateNaissance(?\DateTimeInterface $dateNaissance): self
{
$this->dateNaissance = $dateNaissance;
return $this;
}
public function getGroupe(): ?string
{
return $this->groupe;
}
public function setGroupe(?string $groupe): self
{
$this->groupe = $groupe;
return $this;
}
public function getRegion(): ?string
{
return $this->region;
}
public function setRegion(?string $region): self
{
$this->region = $region;
return $this;
}
public function getBranche(): ?string
{
return $this->branche;
}
public function setBranche(?string $branche): self
{
$this->branche = $branche;
return $this;
}
// public function getNiveauFormation(): ?string
// {
// return $this->niveauFormation;
// }
//
// public function setNiveauFormation(?string $niveauFormation): self
// {
// $this->niveauFormation = $niveauFormation;
//
// return $this;
// }
public function getNiveauEducation(): ?string
{
return $this->niveauEducation;
}
public function setNiveauEducation(?string $niveauEducation): self
{
$this->niveauEducation = $niveauEducation;
return $this;
}
public function getProfession(): ?string
{
return $this->profession;
}
public function setProfession(?string $profession): self
{
$this->profession = $profession;
return $this;
}
public function getTel(): ?string
{
return $this->tel;
}
public function setTel(?string $tel): self
{
$this->tel = $tel;
return $this;
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
public function getFormationPrimaire(): ?bool
{
return $this->formationPrimaire;
}
public function setFormationPrimaire(?bool $formationPrimaire): self
{
$this->formationPrimaire = $formationPrimaire;
return $this;
}
public function getDateFormationPrimaire(): ?\DateTimeInterface
{
return $this->dateFormationPrimaire;
}
public function setDateFormationPrimaire(?\DateTimeInterface $dateFormationPrimaire): self
{
$this->dateFormationPrimaire = $dateFormationPrimaire;
return $this;
}
public function getFormationPreliminaire(): ?bool
{
return $this->formationPreliminaire;
}
public function setFormationPreliminaire(?bool $formationPreliminaire): self
{
$this->formationPreliminaire = $formationPreliminaire;
return $this;
}
public function getDateFormationPreliminaire(): ?\DateTimeInterface
{
return $this->dateFormationPreliminaire;
}
public function setDateFormationPreliminaire(?\DateTimeInterface $dateFormationPreliminaire): self
{
$this->dateFormationPreliminaire = $dateFormationPreliminaire;
return $this;
}
public function getFormationBadge(): ?bool
{
return $this->formationBadge;
}
public function setFormationBadge(?bool $formationBadge): self
{
$this->formationBadge = $formationBadge;
return $this;
}
public function getDateFormationBadge(): ?\DateTimeInterface
{
return $this->dateFormationBadge;
}
public function setDateFormationBadge(?\DateTimeInterface $dateFormationBadge): self
{
$this->dateFormationBadge = $dateFormationBadge;
return $this;
}
public function getM1(): ?bool
{
return $this->M1;
}
public function setM1(?bool $M1): self
{
$this->M1 = $M1;
return $this;
}
public function getM2(): ?bool
{
return $this->M2;
}
public function setM2(?bool $M2): self
{
$this->M2 = $M2;
return $this;
}
public function getDateM1(): ?\DateTimeInterface
{
return $this->dateM1;
}
public function setDateM1(?\DateTimeInterface $dateM1): self
{
$this->dateM1 = $dateM1;
return $this;
}
public function getDateM2(): ?\DateTimeInterface
{
return $this->dateM2;
}
public function setDateM2(?\DateTimeInterface $dateM2): self
{
$this->dateM2 = $dateM2;
return $this;
}
public function getM3(): ?bool
{
return $this->M3;
}
public function setM3(?bool $M3): self
{
$this->M3 = $M3;
return $this;
}
public function getDateM3(): ?\DateTimeInterface
{
return $this->dateM3;
}
public function setDateM3(?\DateTimeInterface $dateM3): self
{
$this->dateM3 = $dateM3;
return $this;
}
public function getS1(): ?bool
{
return $this->S1;
}
public function setS1(?bool $S1): self
{
$this->S1 = $S1;
return $this;
}
public function getDateS1(): ?\DateTimeInterface
{
return $this->dateS1;
}
public function setDateS1(?\DateTimeInterface $dateS1): self
{
$this->dateS1 = $dateS1;
return $this;
}
public function getS2(): ?bool
{
return $this->S2;
}
public function setS2(?bool $S2): self
{
$this->S2 = $S2;
return $this;
}
public function getDateS2(): ?\DateTimeInterface
{
return $this->dateS2;
}
public function setDateS2(?\DateTimeInterface $dateS2): self
{
$this->dateS2 = $dateS2;
return $this;
}
public function getS3(): ?bool
{
return $this->S3;
}
public function setS3(bool $S3): self
{
$this->S3 = $S3;
return $this;
}
public function getDateS3(): ?\DateTimeInterface
{
return $this->dateS3;
}
public function setDateS3(?\DateTimeInterface $dateS3): self
{
$this->dateS3 = $dateS3;
return $this;
}
}
And here is the onAuthenticationSuccess function code:
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new RedirectResponse($targetPath);
}
$role = $token->getUser()->getRoles()[0];
$isVerified = $token->getUser()->isVerified();
if($isVerified===true){
if ($role==='ROLE_ADMIN') {
return new RedirectResponse($this->urlGenerator->generate('dashboard'));
}elseif ($role==='ROLE_CHEF'){
return new RedirectResponse($this->urlGenerator->generate('home'));
}
}else{
$request->getSession()->set(Security::AUTHENTICATION_ERROR, "You are not verified. Check your emails.");
}
throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
}
I also need to display an error message (with addFlash) in the login page. However, That didn't work.
So what's wrong in my code and how can I fix it? Any idea?
Instead of using onAuthenticationSuccess (when authentication mechanic is done) you can use checkCredentials:
public function checkCredentials($credentials, UserInterface $user)
{
// common part
if (!$this->encoder->isPasswordValid($user, $credentials['_password'])) {
return false;
}
// your custom check
if (!$user->isVerified()) {
// and your message
throw new CustomUserMessageAuthenticationException(
'bla-bla-bla'
);
}
return true;
}
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.
I currently have the following error with my entity code, and I don't really understand why I am having this problem.
I only have it in the page of my create dashboard, while I don't call the images but only the heritages, and in the form everything works fine.
I have tried changing Collection to ArrayCollection but nothing has changed.
<?php
namespace App\Entity;
use App\Repository\PatrimoineRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass=PatrimoineRepository::class)
*/
class Patrimoine
{
/**
* #ORM\Id
* #ORM\Column(type="string", unique=true)
* #ORM\GeneratedValue("UUID")
*/
private ?string $id = null;
/**
* #ORM\Column(type="string", length=255)
*/
private ?string $name;
/**
* #ORM\Column(type="string", length=255)
*/
private ?string $description;
/**
* #ORM\Column(type="json")
* #Assert\Collection(
* fields={
* "lat" = {
* #Assert\NotBlank,
* #Assert\Regex("/^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,18})?|180(?:\.0{1,18})?)$/")
* },
* "lng" = {
* #Assert\NotBlank,
* #Assert\Regex("/^(-?[1-8]?\d(?:\.\d{1,18})?|90(?:\.0{1,18})?)$/")
* },
* },
* missingFieldsMessage="Le champs {{ field }} est manquant"
* )
*/
private array $localisation = [];
/**
* #ORM\Column(type="datetime_immutable")
*/
private ?\DateTimeImmutable $created_at;
/**
* #ORM\Column(type="string", length=255)
*/
private ?string $statut;
/**
* #ORM\ManyToOne(targetEntity=CategoryPatrimoine::class, inversedBy="patrimoines")
* #ORM\JoinColumn(nullable=false)
*/
private ?CategoryPatrimoine $category;
/**
* #ORM\Column(type="string", length=255)
*/
private ?string $visibility;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="patrimoines")
* #ORM\JoinColumn(nullable=false)
*/
private ?User $author;
/**
* #ORM\OneToMany(targetEntity=Image::class, mappedBy="patrimoine", orphanRemoval=true)
*/
private ArrayCollection $images;
public function __construct()
{
$this->setCreatedAt(new \DateTimeImmutable());
$this->images = new ArrayCollection();
}
public function getId(): ?string
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getLocalisation(): ?array
{
return $this->localisation;
}
public function setLocalisation(array $localisation): self
{
$this->localisation = $localisation;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeImmutable $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getStatut(): ?string
{
return $this->statut;
}
public function setStatut(string $statut): self
{
$this->statut = $statut;
return $this;
}
public function getCategory(): ?CategoryPatrimoine
{
return $this->category;
}
public function setCategory(?CategoryPatrimoine $category): self
{
$this->category = $category;
return $this;
}
public function getVisibility(): ?string
{
return $this->visibility;
}
public function setVisibility(string $visibility): self
{
$this->visibility = $visibility;
return $this;
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): self
{
$this->author = $author;
return $this;
}
/**
* #return Collection|Image[]
*/
public function getImages(): Collection
{
return $this->images;
}
public function addImage(Image $image): self
{
if (!$this->images->contains($image)) {
$this->images[] = $image;
$image->setPatrimoine($this);
}
return $this;
}
public function removeImage(Image $image): self
{
// set the owning side to null (unless already changed)
if ($this->images->removeElement($image) && $image->getPatrimoine() === $this) {
$image->setPatrimoine(null);
}
return $this;
}
}
I faced a similar problem too. You must declare the property as Collection (interface), not as implementation ArrayCollection because Doctrine ORM uses PersistentCollection when picks up data from database but you declare the property as ArrayCollection, and type mismatch happens.
class SomeEntity {
private Collection $items;
// all other code
}
I just realized that the typing of $ images was wrong, it was "ArrayCollection" whereas it must be "Collection"
I am having trouble in debugging mapping error of Entity.
When I run php bin/console doctrine:schema:validate, It shows the error , which is as follow
[FAIL] The entity-class App\Entity\Company mapping is invalid:
The association App\Entity\Company#policies refers to the owning side field App\Entity\Policy#company_id which does not exist.
I tried this post ( Entity class mapping is invalid) which is pretty much same with me but seems like not working.
This is my Company Entity
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="App\Repository\CompanyRepository")
*/
class Company
{
use TimestampableEntity;
const STATUS_ACTIVE = "ACTIVE";
const STATUS_STAGING = "STAGING";
const STATUS_INACTIVE = "INACTIVE";
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $name;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $address;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $email;
/**
* #ORM\Column(type="string", length=255)
*/
private $status;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $logo;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Policy", mappedBy="company_id")
*/
private $policies;
/**
* #ORM\Column(type="string", length=255)
*/
private $url;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="companies")
*/
private $user;
public function __construct()
{
$this->policies = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getAddress(): ?string
{
return $this->address;
}
public function setAddress(string $address): self
{
$this->address = $address;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getLogo(): ?string
{
return $this->logo;
}
public function setLogo(string $logo): self
{
$this->logo = $logo;
return $this;
}
/**
* #return Collection|Policy[]
*/
public function getPolicies(): Collection
{
return $this->policies;
}
public function addPolicy(Policy $policy): self
{
if (!$this->policies->contains($policy)) {
$this->policies[] = $policy;
$policy->setCompany($this);
}
return $this;
}
public function removePolicy(Policy $policy): self
{
if ($this->policies->contains($policy)) {
$this->policies->removeElement($policy);
// set the owning side to null (unless already changed)
if ( $policy->getCompany() === $this) {
$policy->setCompany(null);
}
}
return $this;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
}
And this is my Policy Entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="App\Repository\PolicyRepository")
*/
class Policy
{
use TimestampableEntity;
const VEH_TYPE_MINIBUS = "Minibus";
const VEH_TYPE_FOUR_WHEEL = "4x4";
const VEH_TYPE_CAR = "Car";
const VEH_PURPOSE_PERSONAL = "Personal";
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $ref_id;
/**
* #ORM\Column(type="string", length=255)
*/
private $policy_code;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Company")
* #ORM\JoinColumn(name="company_id", nullable=false, referencedColumnName="id")
*/
private $company;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $status;
/**
* #ORM\Column(type="datetime")
* #Assert\NotBlank
*/
private $fromDate;
/**
* #ORM\Column(type="datetime")
* #Assert\NotBlank
*/
private $toDate;
/**
* #ORM\Column(type="string", length=255)
*/
private $vehicle_type;
/**
* #ORM\Column(type="string", length=255)
*/
private $purpose;
/**
* #ORM\Column(type="float",scale=2)
*/
private $total_amt;
/**
* #ORM\Column(type="float", scale=2)
*/
private $cover_amt;
/**
* #ORM\Column(type="float", scale=2)
*/
private $discount;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Customer", inversedBy="policies")
*/
private $customer;
public function getId(): ?int
{
return $this->id;
}
public function getRefId(): ?string
{
return $this->ref_id;
}
public function setRefId(string $ref_id): self
{
$this->ref_id = $ref_id;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
public function getFromDate(): ?\DateTimeInterface
{
return $this->fromDate;
}
public function setFromDate(\DateTimeInterface $fromDate): self
{
$this->fromDate = $fromDate;
return $this;
}
public function getToDate(): ?\DateTimeInterface
{
return $this->toDate;
}
public function setToDate(\DateTimeInterface $toDate): self
{
$this->toDate = $toDate;
return $this;
}
public function getTotalAmt(): ?float
{
return $this->total_amt;
}
public function setTotalAmt(float $total_amt): self
{
$this->total_amt = $total_amt;
return $this;
}
public function getCoverAmt(): ?float
{
return $this->cover_amt;
}
public function setCoverAmt(float $cover_amt): self
{
$this->cover_amt = $cover_amt;
return $this;
}
public function getCompany(): ?Company
{
return $this->company;
}
public function setCompany(?Company $company): self
{
$this->company = $company;
return $this;
}
public function getCustomer(): ?Customer
{
return $this->customer;
}
public function setCustomer(?Customer $customer): self
{
$this->customer = $customer;
return $this;
}
public function getVehicleType(): ?string
{
return $this->vehicle_type;
}
public function setVehicleType(string $vehicle_type): self
{
$this->vehicle_type = $vehicle_type;
return $this;
}
public function getPurpose(): ?string
{
return $this->purpose;
}
public function setPurpose(string $purpose): self
{
$this->purpose = $purpose;
return $this;
}
public function getDiscount(): ?float
{
return $this->discount;
}
public function setDiscount(float $discount): self
{
$this->discount = $discount;
return $this;
}
public function getPolicyCode(): ?string
{
return $this->policy_code;
}
public function setPolicyCode(string $policy_code): self
{
$this->policy_code = $policy_code;
return $this;
}
}
company_id does not exist in the entity only in the table. So try mappedBy="company instead? Hope it helps!
I'm trying to serialize an entity with children to an XML file using the buildin serializer from Symfony. The problem is that the serializer doesn't
format the collection of children in the xml the way I expected.
I initiate the serializer as follows:
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
$this->serializer = new Serializer(
[
$normalizer,
new GetSetMethodNormalizer(),
new ArrayDenormalizer()
],
[new XmlEncoder(), new JsonEncoder()]
);
And call the serializer like this:
$this->serializer->serialize(
$entityCollection,
'xml',
[
'xml_format_output' => true,
'xml_root_node_name' => 'events'
]
);
Which results in the following XML:
<item key="140">
<id/>
<name>Lorum ipsum</name>
<lastEdited/>
<url>Lorum ipsum</url>
<region>Limburg</region>
<description>Lorum ipsum</description>
<location/>
<contact/>
<content><![CDATA[<p>Lorum ipsum</p>]]></content>
<priceChild/>
<priceAdult/>
<startTime>15:00:00</startTime>
<endTime>15:45:00</endTime>
<eventDates/>
<eventImages>
<id/>
<url>herfstvoorstelling.jpg</url>
</eventImages>
<eventImages>
<id/>
<url>test.jpg</url>
</eventImages>
</item>
As you can see the <eventImages> node are represented twice where I expected it to have the following structure:
<eventImages>
<eventImage>
<id/>
<url>herfstvoorstelling.jpg</url>
</eventImage>
<eventImage>
<id/>
<url>test.jpg</url>
</eventImage>
</eventImages>
The entities used:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* #ORM\Entity(repositoryClass="App\Repository\EventRepository")
*/
class Event
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\Column(type="string", length=255)
*/
private $lastEdited;
/**
* #ORM\Column(type="string", length=255)
*/
private $url;
/**
* #ORM\Column(type="string", length=255)
*/
private $region;
/**
* #ORM\Column(type="string", length=255)
*/
private $description;
/**
* #ORM\Column(type="string", length=255)
*/
private $location;
/**
* #ORM\Column(type="string", length=255)
*/
private $contact;
/**
* #ORM\Column(type="string", length=255)
*/
private $content;
/**
* #ORM\Column(type="string", length=255)
*/
private $priceChild;
/**
* #ORM\Column(type="string", length=255)
*/
private $priceAdult;
/**
* #ORM\Column(type="string", length=255)
*/
private $startTime;
/**
* #ORM\Column(type="string", length=255)
*/
private $endTime;
/**
* #ORM\OneToMany(targetEntity="App\Entity\EventDate", mappedBy="event")
*/
private $eventDates;
/**
* #MaxDepth(2)
* #ORM\OneToMany(targetEntity="App\Entity\EventImage", mappedBy="event")
*/
private $eventImages;
public function __construct()
{
$this->eventDates = new ArrayCollection();
$this->eventImages = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getLastEdited(): ?string
{
return $this->lastEdited;
}
public function setLastEdited(string $lastEdited): self
{
$this->lastEdited = $lastEdited;
return $this;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
public function getRegion(): ?string
{
return $this->region;
}
public function setRegion(string $region): self
{
$this->region = $region;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getLocation(): ?string
{
return $this->location;
}
public function setLocation(string $location): self
{
$this->location = $location;
return $this;
}
public function getContact(): ?string
{
return $this->contact;
}
public function setContact(string $contact): self
{
$this->contact = $contact;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getPriceChild(): ?string
{
return $this->priceChild;
}
public function setPriceChild(string $priceChild): self
{
$this->priceChild = $priceChild;
return $this;
}
public function getPriceAdult(): ?string
{
return $this->priceAdult;
}
public function setPriceAdult(string $priceAdult): self
{
$this->priceAdult = $priceAdult;
return $this;
}
public function getStartTime(): ?string
{
return $this->startTime;
}
public function setStartTime(string $startTime): self
{
$this->startTime = $startTime;
return $this;
}
public function getEndTime(): ?string
{
return $this->endTime;
}
public function setEndTime(string $endTime): self
{
$this->endTime = $endTime;
return $this;
}
/**
* #return Collection|EventDate[]
*/
public function getEventDates(): Collection
{
return $this->eventDates;
}
public function addEventDate(EventDate $eventDate): self
{
if (!$this->eventDates->contains($eventDate)) {
$this->eventDates[] = $eventDate;
$eventDate->setEvent($this);
}
return $this;
}
public function removeEventDate(EventDate $eventDate): self
{
if ($this->eventDates->contains($eventDate)) {
$this->eventDates->removeElement($eventDate);
// set the owning side to null (unless already changed)
if ($eventDate->getEvent() === $this) {
$eventDate->setEvent(null);
}
}
return $this;
}
/**
* #return Collection|EventImage[]
*/
public function getEventImages(): Collection
{
return $this->eventImages;
}
public function addEventImage(EventImage $eventImage): self
{
if (!$this->eventImages->contains($eventImage)) {
$this->eventImages[] = $eventImage;
$eventImage->setEvent($this);
}
return $this;
}
public function removeEventImage(EventImage $eventImage): self
{
if ($this->eventImages->contains($eventImage)) {
$this->eventImages->removeElement($eventImage);
// set the owning side to null (unless already changed)
if ($eventImage->getEvent() === $this) {
$eventImage->setEvent(null);
}
}
return $this;
}
}
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\EventImageRepository")
*/
class EventImage
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $url;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Event", inversedBy="eventImages")
*/
private $event;
public function getId()
{
return $this->id;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(?string $url): self
{
$this->url = $url;
return $this;
}
public function getEvent(): ?Event
{
return $this->event;
}
public function setEvent(?Event $event): self
{
$this->event = $event;
return $this;
}
}
I can't find out what I'm missing or if it is possible to achieve this with the default serializer from Symfony.