Symfony simple form filter question only allow unique entries - symfony

I'm stuck for a while now in trying to get the following scenario to work.
I have a registration system for a sporting team.
Each team can register for any available contest. The problem is that each team is only allowed once to register on a contest. I simply want to filter the teams that are already registered for the current selected contest. I'm using the Symfony framework together with Doctrine ORM and the symfony form system.
I tried to create a custom function inside the teamRepository to only get the teams that are not registered for a given contest. But i can't seem to find a way to gt this to work.
I'm using 3 entities for this: User, Team, Registration, Contest
The registration entity holds all te submitted registrations with a relation to the Contest and the User (team). I hope that someone can help me here. For reference, this is my registration entity:
class Registrations
{
use TimestampableEntity;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\ManyToOne(targetEntity: Team::class, inversedBy: 'registrations')]
private $Team;
#[ORM\ManyToMany(targetEntity: Dancers::class, inversedBy: 'registrations', fetch: 'EAGER')]
private $Dancers;
#[ORM\Column(type: 'text', nullable: true)]
private $Comments;
#[ORM\ManyToOne(targetEntity: Contest::class, fetch: 'EAGER', inversedBy: 'registrations')]
#[ORM\JoinColumn(nullable: false)]
private $Contest;
#[ORM\Column(type: 'string', length: 255)]
#[Gedmo\Blameable(on: 'create')]
private $RegisteredBy;
#[ORM\OneToMany(mappedBy: 'Registration', targetEntity: Orders::class)]
private $orders;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private $MusicFile;
public function __construct()
{
$this->Dancers = new ArrayCollection();
$this->orders = new ArrayCollection();
}
public function __toString()
{
return $this->id;
}
public function getId(): ?int
{
return $this->id;
}
public function getTeam(): ?Team
{
return $this->Team;
}
public function setTeam(?Team $Team): self
{
$this->Team = $Team;
return $this;
}
/**
* #return Collection|Dancers[]
*/
public function getDancers(): Collection
{
return $this->Dancers;
}
public function addDancer(Dancers $dancer): self
{
if (!$this->Dancers->contains($dancer)) {
$this->Dancers[] = $dancer;
}
return $this;
}
public function removeDancer(Dancers $dancer): self
{
$this->Dancers->removeElement($dancer);
return $this;
}
public function getComments(): ?string
{
return $this->Comments;
}
public function setComments(?string $Comments): self
{
$this->Comments = $Comments;
return $this;
}
public function getRegisteredBy(): ?string
{
return $this->RegisteredBy;
}
public function setRegisteredBy(?string $RegisteredBy): self
{
$this->RegisteredBy = $RegisteredBy;
return $this;
}
public function getContest(): ?Contest
{
return $this->Contest;
}
public function setContest(?Contest $Contest): self
{
$this->Contest = $Contest;
return $this;
}
/**
* #return Collection<int, Orders>
*/
public function getOrders(): Collection
{
return $this->orders;
}
public function addOrder(Orders $order): self
{
if (!$this->orders->contains($order)) {
$this->orders[] = $order;
$order->setRegistration($this);
}
return $this;
}
public function removeOrder(Orders $order): self
{
if ($this->orders->removeElement($order)) {
// set the owning side to null (unless already changed)
if ($order->getRegistration() === $this) {
$order->setRegistration(null);
}
}
return $this;
}
public function getMusicFile(): ?string
{
return $this->MusicFile;
}
public function setMusicFile(string $MusicFile): self
{
$this->MusicFile = $MusicFile;
return $this;
}
}
This is the repo function as mentioned:
public function getTeamsNotRegistered($organisation, $contest)
{
return $this->createQueryBuilder('t')
->leftJoin('t.Registrations', 'r')
->andWhere('t.Organisation = :org')
->andWhere('r.Contest = :contest')
->setParameter('org', $organisation)
->setParameter('contest', $contest)
->getQuery()
->getResult();
}

Related

Cannot assign Symfony\Component\VarDumper\Caster\CutStub to reference held by property App\Entity\AccountName::$accountType

I am developing a project by Symfony 6.2. In this project one entity AccountType with many to one relationship another entity AccountCategory.
#[ORM\Entity(repositoryClass: AccountTypeRepository::class)]
class AccountType
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(length: 255)]
private ?string $code = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $remarks = null;
#[ORM\OneToMany(mappedBy: 'accountType', targetEntity: AccountName::class)]
private Collection $accountNames;
#[ORM\ManyToOne(inversedBy: 'accountTypes')]
#[ORM\JoinColumn(nullable: false)]
private ?AccountCategory $accountCategory = null;
public function __construct()
{
$this->accountNames = 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 getCode(): ?string
{
return $this->code;
}
public function setCode(string $code): self
{
$this->code = $code;
return $this;
}
public function getRemarks(): ?string
{
return $this->remarks;
}
public function setRemarks(?string $remarks): self
{
$this->remarks = $remarks;
return $this;
}
/**
* #return Collection<int, AccountName>
*/
public function getAccountNames(): Collection
{
return $this->accountNames;
}
public function addAccountName(AccountName $accountName): self
{
if (!$this->accountNames->contains($accountName)) {
$this->accountNames->add($accountName);
$accountName->setAccountType($this);
}
return $this;
}
public function removeAccountName(AccountName $accountName): self
{
if ($this->accountNames->removeElement($accountName)) {
// set the owning side to null (unless already changed)
if ($accountName->getAccountType() === $this) {
$accountName->setAccountType(null);
}
}
return $this;
}
public function getAccountCategory(): ?AccountCategory
{
return $this->accountCategory;
}
public function setAccountCategory(?AccountCategory $accountCategory): self
{
$this->accountCategory = $accountCategory;
return $this;
}
}
Another Entity:
#[ORM\Entity(repositoryClass: AccountCategoryRepository::class)]
class AccountCategory
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(inversedBy: 'accountCategories')]
#[ORM\JoinColumn(nullable: false)]
private ?AccountReport $accountReport = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(length: 255)]
private ?string $code = null;
#[ORM\Column(length: 555, nullable: true)]
private ?string $remarks = null;
#[ORM\OneToMany(mappedBy: 'accountCategory', targetEntity: AccountType::class)]
private Collection $accountTypes;
public function __construct()
{
$this->accountTypes = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getAccountReport(): ?AccountReport
{
return $this->accountReport;
}
public function setAccountReport(?AccountReport $accountReport): self
{
$this->accountReport = $accountReport;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getCode(): ?string
{
return $this->code;
}
public function setCode(string $code): self
{
$this->code = $code;
return $this;
}
public function getRemarks(): ?string
{
return $this->remarks;
}
public function setRemarks(?string $remarks): self
{
$this->remarks = $remarks;
return $this;
}
/**
* #return Collection<int, AccountType>
*/
public function getAccountTypes(): Collection
{
return $this->accountTypes;
}
public function addAccountType(AccountType $accountType): self
{
if (!$this->accountTypes->contains($accountType)) {
$this->accountTypes->add($accountType);
$accountType->setAccountCategory($this);
}
return $this;
}
public function removeAccountType(AccountType $accountType): self
{
if ($this->accountTypes->removeElement($accountType)) {
// set the owning side to null (unless already changed)
if ($accountType->getAccountCategory() === $this) {
$accountType->setAccountCategory(null);
}
}
return $this;
}
}
When data retrieve for editing of Account Type form then shown below error.
"Cannot assign Symfony\Component\VarDumper\Caster\CutStub to reference held by property App\Entity\AccountCategory::$accountReport of type ?App\Entity\AccountReport"
Seems to be an issue related to php version. I had the same issue and just upgrade my php to 8.2 and the issue disapears.
See also --> https://github.com/symfony/symfony/issues/49091

How to add a dynamic constraint on a form field

I have a non required field in my 'Session' entity, field is named 'location'. I want to make it required only if another field is equal to true, this other property is named 'isVirtual'
I thaught i'd create an eventSubscriber with the event BeforeEntityUpdatedEvent but I don't know how to add a constraint and I am not sure when this event is triggered.
I tried to do a custom validation constraint but I don't know how to get value of 'isVirtual' value in my ConstraintValidator class.
I need someone to help me look in the right direction. I put there my Entity
<?php
namespace App\Entity;
use App\Repository\SessionRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: SessionRepository::class)]
class Session
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column]
private ?\DateTimeImmutable $beginsAt = null;
#[ORM\Column]
private ?\DateTimeImmutable $endsAt = null;
#[ORM\ManyToOne(inversedBy: 'sessions')]
#[ORM\JoinColumn(nullable: false)]
private ?Formation $formation = null;
#[ORM\ManyToOne(inversedBy: 'sessions')]
#[ORM\JoinColumn(nullable: true)]
private ?Location $location = null;
#[ORM\Column]
private ?bool $isVirtual = null;
#[ORM\OneToMany(mappedBy: 'session', targetEntity: UserSession::class)]
private Collection $users;
#[ORM\Column(nullable: true)]
private ?int $numberOfSeats = null;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getBeginsAt(): ?\DateTimeImmutable
{
return $this->beginsAt;
}
public function setBeginsAt(\DateTimeImmutable $beginsAt): self
{
$this->beginsAt = $beginsAt;
return $this;
}
public function getEndsAt(): ?\DateTimeImmutable
{
return $this->endsAt;
}
public function setEndsAt(\DateTimeImmutable $endsAt): self
{
$this->endsAt = $endsAt;
return $this;
}
public function getFormation(): ?Formation
{
return $this->formation;
}
public function setFormation(?Formation $formation): self
{
$this->formation = $formation;
return $this;
}
public function getLocation(): ?Location
{
return $this->location;
}
public function setLocation(?Location $location): self
{
$this->location = $location;
return $this;
}
public function isIsVirtual(): ?bool
{
return $this->isVirtual;
}
public function setIsVirtual(bool $isVirtual): self
{
$this->isVirtual = $isVirtual;
return $this;
}
/**
* #return Collection<int, UserSession>
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(UserSession $user): self
{
if (!$this->users->contains($user)) {
$this->users->add($user);
$user->setSession($this);
}
return $this;
}
public function removeUser(UserSession $user): self
{
if ($this->users->removeElement($user)) {
// set the owning side to null (unless already changed)
if ($user->getSession() === $this) {
$user->setSession(null);
}
}
return $this;
}
public function getNumberOfSeats(): ?int
{
return $this->numberOfSeats;
}
public function setNumberOfSeats(int $numberOfSeats): self
{
$this->numberOfSeats = $numberOfSeats;
return $this;
}
public function retrieveSeat($number): self
{
$this->setNumberOfSeats($this->getNumberOfSeats() - $number);
return $this;
}
}
and my EasyAdmin Controller
<?php
namespace App\Controller\Admin;
use App\Entity\Session;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
class SessionCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return Session::class;
}
public function configureFields(string $pageName): iterable
{
return [
IdField::new('id')->hideOnForm(),
AssociationField::new('formation'),
DateField::new('beginsAt'),
DateField::new('endsAt'),
BooleanField::new('isVirtual'),
AssociationField::new('location')
->setRequired(false)
->setFormTypeOption('attr', ['placeholder' => 'Enter location']),
IntegerField::new('numberOfSeats')
->setRequired(false)
];
}
}
Thanks a lot in advance.
Here is the callback implementation. Thanks to craigh
<?php
namespace App\Entity;
........
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
class Session
{
........
#[Assert\Callback]
public function validate(ExecutionContextInterface $context, $payload)
{
if (!$this->isIsVirtual()) {
if ($this->getLocation() === null) {
$context->buildViolation("Session needs a location when it's not virtual")
->atPath('location')
->addViolation();
}
if ($this->getNumberOfSeats() === null) {
$context->buildViolation("Session needs a number of seats when it's not virtual")
->atPath('numberOfSeats')
->addViolation();
}
}
}
}

How to exactly use the findBy to display articles by category

I'm new to symfony, I work on an e-commerce website. I solved some bugs already trying different solutions but with this one I feel stuck. I'm trying to display my articles by categories but it's not working because it displays an error:
Warning: Trying to access array offset on value of type null
I made a consoles controller in symfony to call the view associated to display only articles with that category, expected to do the same with the games after but it doesn't seem to find the category associated with the articles ?
This is my consolescontroller:
namespace App\Controller;
use App\Repository\ArticlesRepository;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class ConsolesController extends AbstractController
{
#[Route('/consoles', name: 'app_consoles')]
public function index(ArticlesRepository $repositoryArticles): Response
{
$consoles = $repositoryArticles->findBy(['category' => 1]);
return $this->render('consoles/index.html.twig', [
'controller_name' => 'ConsolesController',
'consoles' => $consoles,
]);
}
}
My Entity Articles
<?php
namespace App\Entity;
use App\Repository\ArticlesRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ArticlesRepository::class)]
class Articles
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 80)]
private ?string $nomArticle = null;
#[ORM\Column(length: 255)]
private ?string $imageArticle = null;
#[ORM\Column]
private ?float $prixArticle = null;
#[ORM\Column(length: 200)]
private ?string $descriptionArticle = null;
#[ORM\ManyToMany(targetEntity: Categories::class, inversedBy: 'articles')]
#[ORM\JoinColumn(nullable: false)]
private Collection $category;
public function __construct()
{
$this->category = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNomArticle(): ?string
{
return $this->nomArticle;
}
public function setNomArticle(string $nomArticle): self
{
$this->nomArticle = $nomArticle;
return $this;
}
public function getImageArticle(): ?string
{
return $this->imageArticle;
}
public function setImageArticle(string $imageArticle): self
{
$this->imageArticle = $imageArticle;
return $this;
}
public function getPrixArticle(): ?float
{
return $this->prixArticle;
}
public function setPrixArticle(float $prixArticle): self
{
$this->prixArticle = $prixArticle;
return $this;
}
public function getDescriptionArticle(): ?string
{
return $this->descriptionArticle;
}
public function setDescriptionArticle(string $descriptionArticle): self
{
$this->descriptionArticle = $descriptionArticle;
return $this;
}
/**
* #return Collection<int, Categories>
*/
public function getCategory(): Collection
{
return $this->category;
}
public function addCategory(Categories $category): self
{
if (!$this->category->contains($category)) {
$this->category->add($category);
}
return $this;
}
public function removeCategory(Categories $category): self
{
$this->category->removeElement($category);
return $this;
}
public function __toString()
{
return $this->nomArticle;
}
}
And my Entity Categories
<?php
namespace App\Entity;
use App\Repository\CategoriesRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: CategoriesRepository::class)]
class Categories
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 50)]
private ?string $nomCategorie = null;
#[ORM\ManyToMany(targetEntity: Articles::class, mappedBy: 'category')]
private Collection $articles;
public function __construct()
{
$this->articles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNomCategorie(): ?string
{
return $this->nomCategorie;
}
public function setNomCategorie(string $nomCategorie): self
{
$this->nomCategorie = $nomCategorie;
return $this;
}
/**
* #return Collection<int, Articles>
*/
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Articles $article): self
{
if (!$this->articles->contains($article)) {
$this->articles->add($article);
$article->addCategory($this);
}
return $this;
}
public function removeArticle(Articles $article): self
{
if ($this->articles->removeElement($article)) {
$article->removeCategory($this);
}
return $this;
}
public function __toString()
{
return $this->nomCategorie;
}
}
They're both linked by a "many to many" relationship and they're both supposed to have access to the other but there still something not working.
Thank you in advance for your help.

How to make left join in dql Symfony

I would like to understand dql logic and i would like to create this kind of request.
Bellow this is the SQL request i would like to do :
SELECT titlemission,descriptionmission,onsetdate,deadline,budgetmission,prioritymission,company FROM mission
left join mission_tag mt on mission.id = mt.mission_id
left join tag on mt.tag_id = tag.id
left join user on user.id = mission.iduser_id
where nomtag = "test20";
I read a lot of documentation but no one explain exatly how to use this QueryBuilder.
Symfony documentation is too abstract for me.
I only know that you have to forget the way you edit the sql request and think in object and entity relation. But i don't know how to do that.
This is my entity Tag
<?php
namespace App\Entity;
use App\Repository\TagRepository;
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: TagRepository::class)]
class Tag
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 100)]
#[Assert\NotBlank]
#[Assert\Length(min:2)]
#[Assert\Valid]
private ?string $nomtag = null;
#[ORM\ManyToMany(targetEntity: Mission::class, mappedBy: 'tags', cascade: ['persist'])]
#[ORM\JoinTable(name: 'mission_tag')]
#[ORM\JoinColumn(name: 'tag_id',referencedColumnName: 'id')]
#[ORM\InverseJoinColumn(name:'mission_id', referencedColumnName: 'id')] // Mission_id est couplé à l'id de mission
private Collection $missions;
public function __construct()
{
$this->missions = new ArrayCollection();
}
// #[ORM\ManyToMany(targetEntity: Mission::class, inversedBy:"$idtagmissionassign")]
// private $genusScientists;
public function getId(): ?int
{
return $this->id;
}
public function getNomtag(): ?string
{
return $this->nomtag;
}
public function setNomtag(string $nomtag): self
{
$this->nomtag = $nomtag;
return $this;
}
/**
* #return Collection<int, Mission>
*/
public function getMissions(): Collection
{
return $this->missionstag;
}
public function addMission(Mission $missions): self
{
if (!$this->missions->contains($missions)) {
$this->missions->add($missions);
$missions->addTag($this);
}
return $this;
}
public function removeMission(Mission $missions): self
{
if ($this->missions->removeElement($missions)) {
$missions->removeTag($this);
}
return $this;
}
public function __toString(): string
{
return $this->nomtag;
}
}
This is my entity user :
<?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\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: 'user')]
#[UniqueEntity(fields: ['email'], message: 'Un compte existe déjà avec cette adresse email')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
private ?string $email = null;
#[ORM\Column]
private array $roles = [];
/**
* #var string The hashed password
*/
#[ORM\Column]
private ?string $password = null;
#[ORM\Column(length: 100)]
private ?string $name = null;
#[ORM\Column(length: 100)]
private ?string $firstname = null;
#[ORM\Column(length: 150)]
private ?string $company = null;
#[ORM\Column(type: 'boolean')]
private $isVerified = false;
#[ORM\Column(length: 255)]
private ?string $companyadress = null;
#[ORM\OneToMany(mappedBy: 'iduser', targetEntity: Mission::class)]
private Collection $missions;
#[ORM\OneToMany(mappedBy: 'iduser', targetEntity: Service::class)]
private Collection $services;
#[ORM\ManyToMany(targetEntity: Service::class, mappedBy: 'idserviceassign')]
private Collection $servicesassign;
#[ORM\ManyToMany(targetEntity: Mission::class, mappedBy: 'idmissionassign')]
#[ORM\JoinTable(name: 'mission_user')]
#[ORM\JoinColumn(name: 'user_id',referencedColumnName: 'id')]
#[ORM\InverseJoinColumn(name:'mission_id', referencedColumnName: 'id')]
private Collection $missionsassign;
public function __construct()
{
$this->missions = new ArrayCollection();
$this->services = new ArrayCollection();
$this->servicesassign = new ArrayCollection();
$this->missionsassign = 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 getUserIdentifier(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'USER_DISCOVER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getCompany(): ?string
{
return $this->company;
}
public function setCompany(string $company): self
{
$this->company = $company;
return $this;
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
public function getCompanyadress(): ?string
{
return $this->companyadress;
}
public function setCompanyadress(string $companyadress): self
{
$this->companyadress = $companyadress;
return $this;
}
public function __toString(){
return $this->name;
}
/**
* #return Collection<int, Mission>
*/
public function getMissions(): Collection
{
return $this->missions;
}
public function addMission(Mission $missions): self
{
if (!$this->missions->contains($missions)) {
$this->missions->add($missions);
$missions->setIduser($this);
}
return $this;
}
public function removeMission(Mission $missions): self
{
if ($this->missions->removeElement($missions)) {
// set the owning side to null (unless already changed)
if ($missions->getIduser() === $this) {
$missions->setIduser(null);
}
}
return $this;
}
/**
* #return Collection<int, Service>
*/
public function getServices(): Collection
{
return $this->services;
}
public function addService(Service $service): self
{
if (!$this->services->contains($service)) {
$this->services->add($service);
$service->setIduser($this);
}
return $this;
}
public function removeService(Service $service): self
{
if ($this->services->removeElement($service)) {
// set the owning side to null (unless already changed)
if ($service->getIduser() === $this) {
$service->setIduser(null);
}
}
return $this;
}
/**
* #return Collection<int, Service>
*/
public function getServicesassign(): Collection
{
return $this->servicesassign;
}
public function addServicesassign(Service $servicesassign): self
{
if (!$this->servicesassign->contains($servicesassign)) {
$this->servicesassign->add($servicesassign);
$servicesassign->addIdserviceassign($this);
}
return $this;
}
public function removeServicesassign(Service $servicesassign): self
{
if ($this->servicesassign->removeElement($servicesassign)) {
$servicesassign->removeIdserviceassign($this);
}
return $this;
}
/**
* #return Collection<int, Mission>
*/
public function getMissionsassign(): Collection
{
return $this->missionsassign;
}
public function addMissionsassign(Mission $missionsassign): self
{
if (!$this->missionsassign->contains($missionsassign)) {
$this->missionsassign->add($missionsassign);
$missionsassign->addIdmissionassign($this);
}
return $this;
}
public function removeMissionsassign(Mission $missionsassign): self
{
if ($this->missionsassign->removeElement($missionsassign)) {
$missionsassign->removeIdmissionassign($this);
}
return $this;
}
}
And this is my entity Mission
<?php
namespace App\Entity;
use App\Repository\MissionRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: MissionRepository::class)]
#[ORM\Table(name: 'mission')]
class Mission
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $titlemission = null;
#[ORM\Column(length: 255)]
private ?string $descriptionmission = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private ?\DateTimeInterface $onsetdate = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private ?\DateTimeInterface $deadline = null;
#[ORM\Column]
private ?int $budgetmission = null;
/*#[ORM\Column(length: 255)]
private ?string $codeapemission = null;*/
#[ORM\Column(length: 255)]
private ?string $prioritymission = null;
#[ORM\ManyToMany(targetEntity: Tag::class, inversedBy: 'missions', cascade: ['persist'])]
#[ORM\JoinTable(name: 'mission_tag')]
#[ORM\JoinColumn(name: 'mission_id',referencedColumnName: 'id')]
#[ORM\InverseJoinColumn(name:'tag_id', referencedColumnName: 'id')] //tag_id qui est couplé avec id de tag
private Collection $tags;
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'missions', cascade: ['persist'], fetch:"EAGER")]
#[ORM\JoinColumn(nullable: false)]
private User $iduser;
#[ORM\ManyToMany(targetEntity: User::class, inversedBy: 'missionsassign')]
#[ORM\JoinTable(name: 'mission_user')]
#[ORM\JoinColumn(name: 'mission_id',referencedColumnName: 'id')]
#[ORM\InverseJoinColumn(name:'user_id', referencedColumnName: 'id')]
private Collection $idmissionassign;
#[ORM\Column(length: 100)]
private ?string $remote = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private ?\DateTimeInterface $datecreation = null;
public function __construct()
{
$this->tags = new ArrayCollection();
$this->idmissionassign = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitlemission(): ?string
{
return $this->titlemission;
}
public function setTitlemission(string $titlemission): self
{
$this->titlemission = $titlemission;
return $this;
}
public function getDescriptionmission(): ?string
{
return $this->descriptionmission;
}
public function setDescriptionmission(string $descriptionmission): self
{
$this->descriptionmission = $descriptionmission;
return $this;
}
public function getOnsetdate(): ?\DateTimeInterface
{
return $this->onsetdate;
}
public function setOnsetdate(\DateTimeInterface $onsetdate): self
{
$this->onsetdate = $onsetdate;
return $this;
}
public function getDeadline(): ?\DateTimeInterface
{
return $this->deadline;
}
public function setDeadline(\DateTimeInterface $deadline): self
{
$this->deadline = $deadline;
return $this;
}
public function getBudgetmission(): ?int
{
return $this->budgetmission;
}
public function setBudgetmission(int $budgetmission): self
{
$this->budgetmission = $budgetmission;
return $this;
}
/*public function getCodeapemission(): ?string
{
return $this->codeapemission;
}
public function setCodeapemission(string $codeapemission): self
{
$this->codeapemission = $codeapemission;
return $this;
}*/
public function getPrioritymission(): ?string
{
return $this->prioritymission;
}
public function setPrioritymission(string $prioritymission): self
{
$this->prioritymission = $prioritymission;
return $this;
}
/**
* #return Collection<int, tag>
*/
public function getIdtagmissionassign(): Collection
{
return $this->tags;
}
public function addIdtagmissionassign(tag $tags): self
{
if (!$this->tags->contains($tags)) {
$this->tags->add($tags);
}
return $this;
}
public function removeIdtagmissionassign(tag $tags): self
{
$this->tags->removeElement($tags);
return $this;
}
public function getIduser(): ?user
{
return $this->iduser;
}
public function setIduser(?user $iduser): self
{
$this->iduser = $iduser;
return $this;
}
/**
* #return Collection<int, user>
*/
public function getIdmissionassign(): Collection
{
return $this->idmissionassign;
}
public function addIdmissionassign(user $idmissionassign): self
{
if (!$this->idmissionassign->contains($idmissionassign)) {
$this->idmissionassign->add($idmissionassign);
}
return $this;
}
public function removeIdmissionassign(user $idmissionassign): self
{
$this->idmissionassign->removeElement($idmissionassign);
return $this;
}
public function getRemote(): ?string
{
return $this->remote;
}
public function setRemote(string $remote): self
{
$this->remote = $remote;
return $this;
}
public function __toString(){
return $this->titlemission;
}
public function getDatecreation(): ?\DateTimeInterface
{
return $this->datecreation;
}
public function setDatecreation(\DateTimeInterface $datecreation): self
{
$this->datecreation = $datecreation;
return $this;
}
}
This is my DQL request but i use Querybuilder without understand the concept. Could you help me ?
public function selectMissionWhereTag($tag){
return $this->createQueryBuilder('mi')
->select('mi.titlemission','mi.descriptionmission','mi.onsetdate','mi.deadline','mi.budgetmission','mi.prioritymission')
->leftJoin(User::class,'user', 'WITH', 'mi.iduser_id = user.id')
->leftJoin(Tag::class,'tag', 'WITH' , 'mi.tags = tag.id')
->where('tag.nomtag = :nomtag')
->setParameter('nomtag',$tag)
->getQuery()
->getResult();
}
Many thanks :)
To better understand how the QueryBuilder works I would recommend reading through how Doctrine ORM Mapping works first: Basic Mapping and Association Mapping
QueryBuilder's Joins use this mapping in a way that looks pretty similar to how you would do things with getters in your PHP code.
For example in a controller to get the tags of a mission you would do something like $tags = $mission->getTags(); well in QueryBuilder you simply do ->leftJoin('mi.tags', 'tag') and that's it. You don't have to worry about WITH unless you need extra conditions.
As you might have guessed there is a lot more to it but this should be enough to get you going.

Mapping entity null value Symfony

This is my issue :
enter image description here
I would like to fill iduser object with user entity.
For the moment i can retreive the id of the user but others fields are empty.
I suppose that my mapping is not correct but i don't found the mistake.
This is my entity witch used to get back all missions :
<?php
namespace App\Entity;
use App\Repository\MissionRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: MissionRepository::class)]
#[ORM\Table(name: 'mission')]
class Mission
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $titlemission = null;
#[ORM\Column(length: 255)]
private ?string $descriptionmission = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private ?\DateTimeInterface $onsetdate = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private ?\DateTimeInterface $deadline = null;
#[ORM\Column]
private ?int $budgetmission = null;
/*#[ORM\Column(length: 255)]
private ?string $codeapemission = null;*/
#[ORM\Column(length: 255)]
private ?string $prioritymission = null;
#[ORM\ManyToMany(targetEntity: Tag::class, inversedBy: 'missions', cascade: ['persist'])]
#[ORM\JoinTable(name: 'mission_tag')]
#[ORM\JoinColumn(name: 'mission_id',referencedColumnName: 'id')]
#[ORM\InverseJoinColumn(name:'tag_id', referencedColumnName: 'id')] //tag_id qui est couplé avec id de tag
private Collection $tags;
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'missions', cascade: ['persist'])]
#[ORM\JoinColumn(nullable: false)]
private User $iduser;
#[ORM\ManyToMany(targetEntity: User::class, inversedBy: 'missionsassign')]
private Collection $idmissionassign;
#[ORM\Column(length: 100)]
private ?string $remote = null;
public function __construct()
{
$this->tags = new ArrayCollection();
$this->idmissionassign = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitlemission(): ?string
{
return $this->titlemission;
}
public function setTitlemission(string $titlemission): self
{
$this->titlemission = $titlemission;
return $this;
}
public function getDescriptionmission(): ?string
{
return $this->descriptionmission;
}
public function setDescriptionmission(string $descriptionmission): self
{
$this->descriptionmission = $descriptionmission;
return $this;
}
public function getOnsetdate(): ?\DateTimeInterface
{
return $this->onsetdate;
}
public function setOnsetdate(\DateTimeInterface $onsetdate): self
{
$this->onsetdate = $onsetdate;
return $this;
}
public function getDeadline(): ?\DateTimeInterface
{
return $this->deadline;
}
public function setDeadline(\DateTimeInterface $deadline): self
{
$this->deadline = $deadline;
return $this;
}
public function getBudgetmission(): ?int
{
return $this->budgetmission;
}
public function setBudgetmission(int $budgetmission): self
{
$this->budgetmission = $budgetmission;
return $this;
}
/*public function getCodeapemission(): ?string
{
return $this->codeapemission;
}
public function setCodeapemission(string $codeapemission): self
{
$this->codeapemission = $codeapemission;
return $this;
}*/
public function getPrioritymission(): ?string
{
return $this->prioritymission;
}
public function setPrioritymission(string $prioritymission): self
{
$this->prioritymission = $prioritymission;
return $this;
}
/**
* #return Collection<int, tag>
*/
public function getIdtagmissionassign(): Collection
{
return $this->tags;
}
public function addIdtagmissionassign(tag $tags): self
{
if (!$this->tags->contains($tags)) {
$this->tags->add($tags);
}
return $this;
}
public function removeIdtagmissionassign(tag $tags): self
{
$this->tags->removeElement($tags);
return $this;
}
public function getIduser(): ?user
{
return $this->iduser;
}
public function setIduser(?user $iduser): self
{
$this->iduser = $iduser;
return $this;
}
/**
* #return Collection<int, user>
*/
public function getIdmissionassign(): Collection
{
return $this->idmissionassign;
}
public function addIdmissionassign(user $idmissionassign): self
{
if (!$this->idmissionassign->contains($idmissionassign)) {
$this->idmissionassign->add($idmissionassign);
}
return $this;
}
public function removeIdmissionassign(user $idmissionassign): self
{
$this->idmissionassign->removeElement($idmissionassign);
return $this;
}
public function getRemote(): ?string
{
return $this->remote;
}
public function setRemote(string $remote): self
{
$this->remote = $remote;
return $this;
}
public function __toString(){
return $this->titlemission;
}
}
This 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\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: 'user')]
#[UniqueEntity(fields: ['email'], message: 'Un compte existe déjà avec cette adresse email')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
private ?string $email = null;
#[ORM\Column]
private array $roles = [];
/**
* #var string The hashed password
*/
#[ORM\Column]
private ?string $password = null;
#[ORM\Column(length: 100)]
private ?string $name = null;
#[ORM\Column(length: 100)]
private ?string $firstname = null;
#[ORM\Column(length: 150)]
private ?string $company = null;
#[ORM\Column(type: 'boolean')]
private $isVerified = false;
#[ORM\Column(length: 255)]
private ?string $companyadress = null;
#[ORM\OneToMany(mappedBy: 'iduser', targetEntity: Mission::class)]
private Collection $missions;
#[ORM\OneToMany(mappedBy: 'iduser', targetEntity: Service::class)]
private Collection $services;
#[ORM\ManyToMany(targetEntity: Service::class, mappedBy: 'idserviceassign')]
private Collection $servicesassign;
#[ORM\ManyToMany(targetEntity: Mission::class, mappedBy: 'idmissionassign')]
private Collection $missionsassign;
public function __construct()
{
$this->missions = new ArrayCollection();
$this->services = new ArrayCollection();
$this->servicesassign = new ArrayCollection();
$this->missionsassign = 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 getUserIdentifier(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'USER_DISCOVER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getCompany(): ?string
{
return $this->company;
}
public function setCompany(string $company): self
{
$this->company = $company;
return $this;
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
public function getCompanyadress(): ?string
{
return $this->companyadress;
}
public function setCompanyadress(string $companyadress): self
{
$this->companyadress = $companyadress;
return $this;
}
public function __toString(){
return $this->name;
}
/**
* #return Collection<int, Mission>
*/
public function getMissions(): Collection
{
return $this->missions;
}
public function addMission(Mission $missions): self
{
if (!$this->missions->contains($missions)) {
$this->missions->add($missions);
$missions->setIduser($this);
}
return $this;
}
public function removeMission(Mission $missions): self
{
if ($this->missions->removeElement($missions)) {
// set the owning side to null (unless already changed)
if ($missions->getIduser() === $this) {
$missions->setIduser(null);
}
}
return $this;
}
/**
* #return Collection<int, Service>
*/
public function getServices(): Collection
{
return $this->services;
}
public function addService(Service $service): self
{
if (!$this->services->contains($service)) {
$this->services->add($service);
$service->setIduser($this);
}
return $this;
}
public function removeService(Service $service): self
{
if ($this->services->removeElement($service)) {
// set the owning side to null (unless already changed)
if ($service->getIduser() === $this) {
$service->setIduser(null);
}
}
return $this;
}
/**
* #return Collection<int, Service>
*/
public function getServicesassign(): Collection
{
return $this->servicesassign;
}
public function addServicesassign(Service $servicesassign): self
{
if (!$this->servicesassign->contains($servicesassign)) {
$this->servicesassign->add($servicesassign);
$servicesassign->addIdserviceassign($this);
}
return $this;
}
public function removeServicesassign(Service $servicesassign): self
{
if ($this->servicesassign->removeElement($servicesassign)) {
$servicesassign->removeIdserviceassign($this);
}
return $this;
}
/**
* #return Collection<int, Mission>
*/
public function getMissionsassign(): Collection
{
return $this->missionsassign;
}
public function addMissionsassign(Mission $missionsassign): self
{
if (!$this->missionsassign->contains($missionsassign)) {
$this->missionsassign->add($missionsassign);
$missionsassign->addIdmissionassign($this);
}
return $this;
}
public function removeMissionsassign(Mission $missionsassign): self
{
if ($this->missionsassign->removeElement($missionsassign)) {
$missionsassign->removeIdmissionassign($this);
}
return $this;
}
}
My goal is to do this :
enter image description here
Try adding the fetch="EAGER" option. This should cause doctrine to fetch/load the entire User whenever the Mission is fetched.
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'missions', cascade: ['persist'], fetch="EAGER")]
#[ORM\JoinColumn(nullable: false)]
private User $iduser;
You can access the current user in your controller with $this->getUser().
Regards,

Resources