Missing value for primary key id on Entity - php

i'm trying return my entity but i get this error when I make a request and i don't know what i'm doing wrong with this relations
(1/2) OutOfBoundsException
Missing value for primary key id on \ApiBundle\Entity\Type
My Session entity:
<?php
namespace Primepass\ApiBundle\Entity;
use Ramsey\Uuid\UuidInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Session
*
* #ORM\Table(name="session", uniqueConstraints={#ORM\UniqueConstraint(name="session_id_uindex", columns={"id"})})
* #ORM\Entity(repositoryClass="Primepass\ApiBundle\Repository\SessionRepository")
*/
class Session
{
/**
* #var UuidInterface
*
* #ORM\Id
* #ORM\Column(type="uuid", unique=true)
* #ORM\GeneratedValue(strategy="CUSTOM")
* #ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
*/
private $id;
/**
* #var Theater
*
* #ORM\OneToOne(targetEntity="Theater")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="theater_id", referencedColumnName="id")
* })
*/
private $theater;
/**
* #var Movie
*
* #ORM\OneToOne(targetEntity="Movie")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="movie_id", referencedColumnName="id")
* })
*/
private $movie;
/**
* #var Type
*
* #ORM\OneToOne(targetEntity="Type")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="audio_type", referencedColumnName="type_name")
* })
*/
private $audioType;
/**
* #var Type
*
* #ORM\OneToOne(targetEntity="Type")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="screen_type", referencedColumnName="type_name")
* })
*/
private $screenType;
/**
* #var Type
*
* #ORM\OneToOne(targetEntity="Type")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="room_type", referencedColumnName="type_name")
* })
*/
private $roomType;
/**
* #var string
*
* #ORM\Column(name="room_name",type="string")
*/
private $roomName;
/**
* #var int
*
* #ORM\Column(name="price", type="integer", nullable=false)
*/
private $price;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime", nullable=false)
*/
private $date;
/**
* #var \Time
*
* #ORM\Column(name="hour", type="time", nullable=false)
*/
private $hour;
/**
* #var bool
*
* #ORM\Column(name="is_active", type="boolean", nullable=false)
*/
private $isActive;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=false, options={"default"="2001-01-01 00:00:00"})
*/
private $createdAt = '2001-01-01 00:00:00';
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime", nullable=false, options={"default"="2001-01-01 00:00:00"})
*/
private $updatedAt = '2001-01-01 00:00:00';
public function getId(): UuidInterface
{
return $this->id;
}
public function getTheater(): ?Theater
{
return $this->theater;
}
public function setTheater(?Theater $theater): self
{
$this->theater = $theater;
return $this;
}
public function getMovie(): ?Movie
{
return $this->movie;
}
public function setMovie(?Movie $movie): self
{
$this->movie = $movie;
return $this;
}
public function getAudioType(): ?Type
{
return $this->audioType;
}
public function setAudioType(?Type $audioType): self
{
$this->audioType = $audioType;
return $this;
}
public function getScreenType(): ?Type
{
return $this->screenType;
}
public function setScreenType(?Type $screenType): self
{
$this->screenType = $screenType;
return $this;
}
public function getRoomType(): ?Type
{
return $this->roomType;
}
public function setRoomType(?Type $roomType): self
{
$this->roomType = $roomType;
return $this;
}
public function getRoomName(): ?string
{
return $this->roomName;
}
public function setRoomName($roomName): self
{
$this->roomName = $roomName;
return $this;
}
public function getPrice(): ?int
{
return $this->price;
}
public function setPrice(?int $price): self
{
$this->price = $price;
return $this;
}
public function getDate(): ?\DateTimeInterface
{
return $this->date;
}
public function setDate(\DateTimeInterface $date): self
{
$this->date = $date;
return $this;
}
public function getHour(): ?\Time
{
return $this->hour;
}
public function setHour(\Time $hour): self
{
$this->hour = $hour;
return $this;
}
public function getIsActive(): bool
{
return $this->isActive;
}
public function setIsActive(bool $isActive): self
{
$this->isActive = $isActive;
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;
}
}
Type Entity:
<?php
namespace Primepass\ApiBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Ramsey\Uuid\UuidInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Type
*
* #ORM\Table(name="type")
* #ORM\Entity(repositoryClass="Primepass\ApiBundle\Repository\TypeRepository")
*/
class Type
{
/**
* #var UuidInterface
*
* #ORM\Id
* #ORM\Column(type="uuid", unique=true)
* #ORM\GeneratedValue(strategy="CUSTOM")
* #ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="type_name", type="string", length=100, nullable=false)
*/
private $typeName;
/**
* #var string
*
* #ORM\Column(name="type_info", type="string", length=100, nullable=false)
*/
private $typeInfo;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=false, options={"default"="2001-01-01 00:00:00"})
*/
private $createdAt = '2001-01-01 00:00:00';
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime", nullable=false, options={"default"="2001-01-01 00:00:00"})
*/
private $updatedAt = '2001-01-01 00:00:00';
/**
* #ORM\ManyToMany(targetEntity="TicketRules", mappedBy="types")
* #ORM\JoinTable(name="ticket_rules_type")
*/
private $ticketRuleScreens;
public function __construct()
{
$this->ticketRuleScreens = new ArrayCollection();
}
public function getId(): UuidInterface
{
return $this->id;
}
public function getTypeName(): string
{
return $this->typeName;
}
public function setTypeName(string $typeName): self
{
$this->typeName = $typeName;
return $this;
}
public function getTypeInfo(): string
{
return $this->typeInfo;
}
public function setTypeInfo(string $typeInfo): self
{
$this->typeInfo = $typeInfo;
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 getTicketRuleScreens()
{
return $this->ticketRuleScreens;
}
public function setTicketRuleScreens($ticketRuleScreens): self
{
$this->ticketRuleScreens = $ticketRuleScreens;
return $this;
}
}
I expected a json return with a paginator but has something wrong with Session model

Related

API Platform Many to One not expecting IRI

I am using API Platform with Symfony for my backend.
I have 2 entities linked with a ManyToOne relationship, Booking and User.
A user can have one or many bookings.
I also have another entity Service, with a OneToMany relationship with Booking.
When I try to test the POST for Bookings on the Swagger interface I get an error on the IRI format for services but not for the others.
Nothing works as input for the fields related to User (provider, client).
I don't understand why it doesn't work. I only get a 400 error.
Here are my entities :
Booking:
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\BookingRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* #ApiResource(
* normalizationContext={"groups"={"booking:read"}},
* denormalizationContext={"groups"={"booking:write"}},
* collectionOperations={
* "get",
* "post"={"security"="is_granted('ROLE_USER')"}
* },
* itemOperations={
* "get",
* "put"={"security"="is_granted('edit', object)"},
* "patch"={"security"="is_granted('edit', object)"},
* "delete"={"security"="is_granted('delete', object)"}
* }
* )
* #ORM\Entity(repositoryClass=BookingRepository::class)
*/
class Booking
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*
* #Groups("booking:read")
*/
private $id;
/**
* #ORM\Column(type="date")
*
* #Groups({"booking:read","booking:write"})
*/
private $bookingDate;
/**
* #ORM\Column(type="datetime_immutable")
*
* #Groups("booking:read")
*/
private $reservedAt;
/**
* #ORM\Column(type="string", length=255)
*
* #Groups({"booking:read","booking:write"})
*/
private $location;
/**
* #ORM\Column(type="time")
*
* #Groups({"booking:read","booking:write"})
*/
private $startTime;
/**
* #ORM\Column(type="time")
*
* #Groups({"booking:read","booking:write"})
*/
private $endTime;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="bookingsAsProvider")
* #ORM\JoinColumn(nullable=false)
*
* #Groups({"booking:read","booking:write"})
*/
private $provider;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="bookingsAsClient")
* #ORM\JoinColumn(nullable=false)
*
* #Groups({"booking:read","booking:write"})
*/
private $client;
/**
* #ORM\ManyToOne(targetEntity=Service::class, inversedBy="bookings")
* #ORM\JoinColumn(nullable=false)
* #Groups({"booking:read","booking:write"})
*/
private $service;
/**
* #ORM\Column(type="integer")
* #Groups({"booking:read","booking:write"})
*/
private $state;
/**
* #ORM\Column(type="boolean")
* #Groups({"booking:read","booking:write"})
*/
private $read;
public function getId(): ?int
{
return $this->id;
}
public function getBookingDate(): ?\DateTimeInterface
{
return $this->bookingDate;
}
public function setBookingDate(\DateTimeInterface $bookingDate): self
{
$this->bookingDate = $bookingDate;
return $this;
}
public function getReservedAt(): ?\DateTimeImmutable
{
return $this->reservedAt;
}
public function setReservedAt(\DateTimeImmutable $reservedAt): self
{
$this->reservedAt = $reservedAt;
return $this;
}
public function getLocation(): ?string
{
return $this->location;
}
public function setLocation(string $location): self
{
$this->location = $location;
return $this;
}
public function getStartTime(): ?\DateTimeInterface
{
return $this->startTime;
}
public function setStartTime(\DateTimeInterface $startTime): self
{
$this->startTime = $startTime;
return $this;
}
public function getEndTime(): ?\DateTimeInterface
{
return $this->endTime;
}
public function setEndTime(\DateTimeInterface $endTime): self
{
$this->endTime = $endTime;
return $this;
}
public function getProvider(): ?User
{
return $this->provider;
}
public function setProvider(?User $provider): self
{
$this->provider = $provider;
return $this;
}
public function getClient(): ?User
{
return $this->client;
}
public function setClient(?User $client): self
{
$this->client = $client;
return $this;
}
public function getService(): ?Service
{
return $this->service;
}
public function setService(?Service $service): self
{
$this->service = $service;
return $this;
}
public function getState(): ?int
{
return $this->state;
}
public function setState(int $state): self
{
$this->state = $state;
return $this;
}
public function getRead(): ?bool
{
return $this->read;
}
public function setRead(bool $read): self
{
$this->read = $read;
return $this;
}
}
User:
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
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\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\SerializedName;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
*
* #ApiResource(
* normalizationContext={"groups"={"user:read"}},
* denormalizationContext={"groups"={"user:write"}},
* collectionOperations={
* "get"={"security"="is_granted('ROLE_ADMIN') or object == user"},
* "post"={"security"="is_granted('ROLE_ADMIN_FRONTEND')"}
* },
* itemOperations={
* "get",
* "put"={"security"="is_granted('ROLE_ADMIN') or object == user"},
* "patch"={"security"="is_granted('ROLE_ADMIN') or object == user"},
* "delete"={"security"="is_granted('ROLE_ADMIN')"},
* "get_by_role" = {
* "method" = "GET",
* "path" = "/user/{role}",
* "controller" = User::class,
* "read"=false,
* "openapi_context" = {
* "parameters" = {
* {
* "name" = "role",
* "in" = "path",
* "description" = "The role of a user",
* "type" = "string",
* "required" = true,
* "example"= "ROLE_PARENT",
* },
* },
* },
* },
* },
* )
*
* #ORM\Table(name="`user`")
*/
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*
* #Groups({"user:read","service:read","booking:read"})
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $email;
/**
* #ORM\Column(type="json")
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $roles = [];
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
/**
* #Groups("user:write")
*
* #SerializedName("password")
*/
private $plainPassword;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read","booking:read"})
*/
private $name;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read","booking:read"})
*/
private $firstname;
/**
* #ORM\Column(type="string", length=255, unique=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $username;
/**
* #ORM\Column(type="string", length=50, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $phone;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $facebook;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $instagram;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $linkedin;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $twitter;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $pinterest;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $website;
/**
* #ORM\Column(type="text", nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $tagline;
/**
* #ORM\Column(type="text", nullable=true)
*
* #Groups({"user:read", "user:write","businessRelationship:read","service:read"})
*/
private $description;
/**
* #ORM\OneToMany(targetEntity=Address::class, mappedBy="client",cascade={"persist"})
*
* #Groups({"user:read", "user:write"})
* #ApiSubresource
*/
private $addresses;
/**
* #ORM\ManyToMany(targetEntity=Service::class, mappedBy="performer")
* #ApiSubresource
*/
private $servicesAsPerformer;
/**
* #ORM\OneToMany(targetEntity=Service::class, mappedBy="owner")
* #ApiSubresource
*/
private $servicesAsOwner;
/**
* #ORM\OneToMany(targetEntity=BusinessRelationship::class, mappedBy="partnerA")
* #ApiSubresource
*/
private $businessRelationshipsPartnerA;
/**
* #ORM\OneToMany(targetEntity=BusinessRelationship::class, mappedBy="partnerB")
* #ApiSubresource
*/
private $businessRelationshipsPartnerB;
/**
* #ORM\OneToMany(targetEntity=Booking::class, mappedBy="provider")
* #ApiSubresource
*/
private $bookingsAsProvider;
/**
* #ORM\OneToMany(targetEntity=Booking::class, mappedBy="client")
* #ApiSubresource
*/
private $bookingsAsClient;
/**
* #ORM\OneToMany(targetEntity=Schedule::class, mappedBy="provider")
* #ApiSubresource
*/
private $schedules;
/**
* #ORM\OneToMany(targetEntity=UserCategory::class, mappedBy="provider")
* #ApiSubresource
*
* #Groups({"user:read", "user:write"})
*/
private $userCategories;
/**
* #ORM\Column(type="text", nullable=true)
* #Groups({"user:read", "user:write"})
*/
private $profilePicture;
/**
* #ORM\Column(type="text", length=16777215, nullable=true)
* #Groups({"user:read", "user:write"})
*/
private $gallery;
/**
* #ORM\OneToMany(targetEntity=Notification::class, mappedBy="userOrigin")
* #ApiSubresource
*
* #Groups({"user:read", "user:write"})
*/
private $notificationsUserOrigin;
/**
* #ORM\OneToMany(targetEntity=Notification::class, mappedBy="userTarget")
* #ApiSubresource
*
* #Groups({"user:read", "user:write"})
*/
private $notificationsUserTarget;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $resetToken;
public function __construct()
{
$this->addresses = new ArrayCollection();
$this->servicesAsPerformer = new ArrayCollection();
$this->servicesAsOwner = new ArrayCollection();
$this->businessRelationshipsPartnerA = new ArrayCollection();
$this->businessRelationshipsPartnerB = new ArrayCollection();
$this->bookingsAsProvider = new ArrayCollection();
$this->bookingsAsClient = new ArrayCollection();
$this->schedules = new ArrayCollection();
$this->userCategories = new ArrayCollection();
$this->notificationsUserOrigin = new ArrayCollection();
$this->notificationsUserTarget = 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;
}
/**
* #deprecated since Symfony 5.3, use getUserIdentifier instead
*/
// 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 PasswordAuthenticatedUserInterface
*/
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 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 getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(?string $phone): self
{
$this->phone = $phone;
return $this;
}
public function getFacebook(): ?string
{
return $this->facebook;
}
public function setFacebook(?string $facebook): self
{
$this->facebook = $facebook;
return $this;
}
public function getInstagram(): ?string
{
return $this->instagram;
}
public function setInstagram(?string $instagram): self
{
$this->instagram = $instagram;
return $this;
}
public function getLinkedin(): ?string
{
return $this->linkedin;
}
public function setLinkedin(?string $linkedin): self
{
$this->linkedin = $linkedin;
return $this;
}
public function getTwitter(): ?string
{
return $this->twitter;
}
public function setTwitter(?string $twitter): self
{
$this->twitter = $twitter;
return $this;
}
public function getPinterest(): ?string
{
return $this->pinterest;
}
public function setPinterest(?string $pinterest): self
{
$this->pinterest = $pinterest;
return $this;
}
public function getWebsite(): ?string
{
return $this->website;
}
public function setWebsite(?string $website): self
{
$this->website = $website;
return $this;
}
public function getTagline(): ?string
{
return $this->tagline;
}
public function setTagline(?string $tagline): self
{
$this->tagline = $tagline;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
public function setPlainPassword(?string $plainPassword): self
{
$this->plainPassword = $plainPassword;
return $this;
}
/**
* #return Collection|Address[]
*/
public function getAddresses(): Collection
{
return $this->addresses;
}
public function addAddress(Address $address): self
{
if (!$this->addresses->contains($address)) {
$this->addresses[] = $address;
$address->setClient($this);
}
return $this;
}
public function removeAddress(Address $address): self
{
if ($this->addresses->removeElement($address)) {
// set the owning side to null (unless already changed)
if ($address->getClient() === $this) {
$address->setClient(null);
}
}
return $this;
}
public function hasRoles(string $roles): bool
{
return in_array($roles, $this->roles);
}
/**
* #return Collection|Service[]
*/
public function getServicesAsPerformer(): Collection
{
return $this->servicesAsPerformer;
}
public function addServicesAsPerformer(Service $servicesAsPerformer): self
{
if (!$this->servicesAsPerformer->contains($servicesAsPerformer)) {
$this->servicesAsPerformer[] = $servicesAsPerformer;
$servicesAsPerformer->addPerformer($this);
}
return $this;
}
public function removeServicesAsPerformer(Service $servicesAsPerformer): self
{
if ($this->servicesAsPerformer->removeElement($servicesAsPerformer)) {
$servicesAsPerformer->removePerformer($this);
}
return $this;
}
/**
* #return Collection|Service[]
*/
public function getServicesAsOwner(): Collection
{
return $this->servicesAsOwner;
}
public function addServicesAsOwner(Service $servicesAsOwner): self
{
if (!$this->servicesAsOwner->contains($servicesAsOwner)) {
$this->servicesAsOwner[] = $servicesAsOwner;
$servicesAsOwner->setOwner($this);
}
return $this;
}
public function removeServicesAsOwner(Service $servicesAsOwner): self
{
if ($this->servicesAsOwner->removeElement($servicesAsOwner)) {
// set the owning side to null (unless already changed)
if ($servicesAsOwner->getOwner() === $this) {
$servicesAsOwner->setOwner(null);
}
}
return $this;
}
/**
* #return Collection|BusinessRelationship[]
*/
public function getBusinessRelationshipsPartnerA(): Collection
{
return $this->businessRelationshipsPartnerA;
}
public function addBusinessRelationshipsPartnerA(BusinessRelationship $businessRelationshipsPartnerA): self
{
if (!$this->businessRelationshipsPartnerA->contains($businessRelationshipsPartnerA)) {
$this->businessRelationshipsPartnerA[] = $businessRelationshipsPartnerA;
$businessRelationshipsPartnerA->setPartnerA($this);
}
return $this;
}
public function removeBusinessRelationshipsPartnerA(BusinessRelationship $businessRelationshipsPartnerA): self
{
if ($this->businessRelationshipsPartnerA->removeElement($businessRelationshipsPartnerA)) {
// set the owning side to null (unless already changed)
if ($businessRelationshipsPartnerA->getPartnerA() === $this) {
$businessRelationshipsPartnerA->setPartnerA(null);
}
}
return $this;
}
/**
* #return Collection|BusinessRelationship[]
*/
public function getBusinessRelationshipsPartnerB(): Collection
{
return $this->businessRelationshipsPartnerB;
}
public function addBusinessRelationshipsPartnerB(BusinessRelationship $businessRelationshipsPartnerB): self
{
if (!$this->businessRelationshipsPartnerB->contains($businessRelationshipsPartnerB)) {
$this->businessRelationshipsPartnerB[] = $businessRelationshipsPartnerB;
$businessRelationshipsPartnerB->setPartnerB($this);
}
return $this;
}
public function removeBusinessRelationshipsPartnerB(BusinessRelationship $businessRelationshipsPartnerB): self
{
if ($this->businessRelationshipsPartnerB->removeElement($businessRelationshipsPartnerB)) {
// set the owning side to null (unless already changed)
if ($businessRelationshipsPartnerB->getPartnerB() === $this) {
$businessRelationshipsPartnerB->setPartnerB(null);
}
}
return $this;
}
/**
* #return Collection|Booking[]
*/
public function getBookingsAsProvider(): Collection
{
return $this->bookingsAsProvider;
}
public function addBookingsAsProvider(Booking $bookingsAsProvider): self
{
if (!$this->bookingsAsProvider->contains($bookingsAsProvider)) {
$this->bookingsAsProvider[] = $bookingsAsProvider;
$bookingsAsProvider->setProvider($this);
}
return $this;
}
public function removeBookingsAsProvider(Booking $bookingsAsProvider): self
{
if ($this->bookingsAsProvider->removeElement($bookingsAsProvider)) {
// set the owning side to null (unless already changed)
if ($bookingsAsProvider->getProvider() === $this) {
$bookingsAsProvider->setProvider(null);
}
}
return $this;
}
/**
* #return Collection|Booking[]
*/
public function getBookingsAsClient(): Collection
{
return $this->bookingsAsClient;
}
public function addBookingsAsClient(Booking $bookingsAsClient): self
{
if (!$this->bookingsAsClient->contains($bookingsAsClient)) {
$this->bookingsAsClient[] = $bookingsAsClient;
$bookingsAsClient->setClient($this);
}
return $this;
}
public function removeBookingsAsClient(Booking $bookingsAsClient): self
{
if ($this->bookingsAsClient->removeElement($bookingsAsClient)) {
// set the owning side to null (unless already changed)
if ($bookingsAsClient->getClient() === $this) {
$bookingsAsClient->setClient(null);
}
}
return $this;
}
[...]
}
Service:
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
use App\Repository\ServiceRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* #ApiResource(
* normalizationContext={"groups"={"service:read"}},
* denormalizationContext={"groups"={"service:write"}},
* collectionOperations={
* "get",
* "post"={"security"="is_granted('ROLE_USER')"}
* },
* itemOperations={
* "get",
* "put"={"security"="is_granted('edit', object)"},
* "patch"={"security"="is_granted('edit', object)"},
* "delete"={"security"="is_granted('delete', object)"}
* }
* )
* #ORM\Entity(repositoryClass=ServiceRepository::class)
*/
class Service
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*
* #Groups({"service:read","schedule:read"})
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Groups({"service:read", "service:write","schedule:read"})
*/
private $name;
/**
* #ORM\Column(type="float")
*
* #Groups({"service:read", "service:write","schedule:read"})
*/
private $price;
/**
* #ORM\Column(type="text", nullable=true)
*
* #Groups({"service:read", "service:write","schedule:read"})
*/
private $description;
/**
* #ORM\ManyToMany(targetEntity=Address::class, inversedBy="services")
*
* #Groups({"service:read", "service:write"})
* #ApiSubresource
*/
private $addresses;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="servicesAsPerformer")
* #Groups({"service:read", "service:write","schedule:read"})
*/
private $performer;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="servicesAsOwner")
* #Groups({"service:read", "service:write","schedule:read"})
*/
private $owner;
/**
* #ORM\ManyToMany(targetEntity=Schedule::class, mappedBy="services")
* #Groups({"service:read", "service:write"})
* #ApiSubresource
*/
private $schedules;
/**
* #ORM\OneToMany(targetEntity=Booking::class, mappedBy="service")
*/
private $bookings;
public function __construct()
{
$this->addresses = new ArrayCollection();
$this->performer = new ArrayCollection();
$this->schedules = new ArrayCollection();
$this->bookings = new ArrayCollection();
}
[...]
}
Here are the JSON inputs I tried with the response I get :
Error 400 "Syntax Error"
{
"bookingDate": "2022-11-14T14:59:49.322Z",
"location": "string",
"startTime": "2022-11-14T14:59:49.322Z",
"endTime": "2022-11-14T14:59:49.322Z",
"provider": "string",
"client": "string",
"service": "\api\services\725",
"state": 0,
"read": true
}
Error 400 "Invalid IRI "string"."
{
"bookingDate": "2022-11-14T14:59:49.322Z",
"location": "string",
"startTime": "2022-11-14T14:59:49.322Z",
"endTime": "2022-11-14T14:59:49.322Z",
"provider": "string",
"client": "string",
"service": "string",
"state": 0,
"read": true
}
I really don't see why for service it expects an IRI format, while not for client and provider.

Symfony Maybe you forget to persist it in the entity manager?

i need select username of entity " user "on my form, but i get this fail:
Entity of type "Doctrine\ORM\PersistentCollection" passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?
i try add public function __toString() on my entity user, but dont work
form
class AsignarEventoFormType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options){
$builder->add('users', EntityType::class, [
'class' => User::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.nombre', 'ASC');
},
'choice_label' => 'nombre',
]);
}
}
entity of user :
<?php
declare(strict_types=1);
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 Doctrine\ORM\PersistentCollection;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="nombre", type="string", length=255, nullable=false)
*/
private $nombre;
/**
* #ORM\Column(name="apellido", type="string", length=255, nullable=false)
*/
private $apellido;
/**
* #var string|null
*
* #ORM\Column(name="email", type="string", length=255, nullable=true)
* #Assert\NotBlank
* #Assert\Email(
* message = "El email '{{ value }}' no es valido"
*
* )
*/
private $email;
/**
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* #ORM\Column(name="role", type="string", length=255, nullable=false)
*/
private $role;
/**
* #var \DateTime|null
*
* #ORM\Column(name="fecha", type="datetime", nullable=true)
*/
private $fecha;
/**
* #ORM\Column(name="foto", type="string", length=255, nullable=false)
*/
private $foto;
/**
* #ORM\ManyToMany(targetEntity="Evento", inversedBy="users", cascade={"persist"})
* #ORM\JoinTable(
* name="user_evento",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="evento_id", referencedColumnName="id")
* }
* )
*/
private $eventos;
/**
* #ORM\ManyToMany(targetEntity="Sala", inversedBy="users", cascade={"persist"})
* #ORM\JoinTable(
* name="user_sala",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="sala_id", referencedColumnName="id")
* }
* )
*/
private $salas;
public function __construct()
{
$this->eventos = new ArrayCollection();
$this->salas = new ArrayCollection();
}
public function getId(): int
{
return $this->id;
}
public function setNombre(string $nombre): self
{
$this->nombre = $nombre;
return $this;
}
public function getNombre(): string
{
return $this->nombre;
}
public function setApellido(string $apellido): self
{
$this->apellido = $apellido;
return $this;
}
public function getApellido(): string
{
return $this->apellido;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getEmail(): string
{
return $this->email;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getPassword(): string
{
return $this->password;
}
public function setRole(string $role): self
{
$this->role = $role;
return $this;
}
public function getRole(): string
{
return $this->role;
}
public function setFoto(string $foto): self
{
$this->foto = $foto;
return $this;
}
public function getFoto(): string
{
return $this->foto;
}
public function getFecha()
{
return $this->fecha;
}
public function setFecha($fecha): self
{
$this->fecha = $fecha;
return $this;
}
public function addEvento(Evento $evento): self
{
$this->eventos[] = $evento;
return $this;
}
public function removeEvento(Evento $evento): bool
{
return $this->eventos->removeElement($evento);
}
public function getEventos(): Collection
{
return $this->eventos;
}
public function addSala(Sala $sala): self
{
$this->salas[] = $salas;
return $this;
}
public function removeSala(Sala $sala): bool
{
return $this->salas->removeElement($sala);
}
public function getSalas(): Collection
{
return $this->salas;
}
public function getUsername(){
return $this->email;
}
public function getSalt(){
return null;
}
public function getRoles(){
return array('ROLE_USER');
}
public function eraseCredentials(){}
public function __toString() {
return $this->id;
}
}
capture 1
capture2
You should add multiple => true to your users form field options.

Api plateform denormalization custom operation with relation

I have 2 entities Voucher and Client (which extend User entity) with a OneToOne relation, I have a custom operation in the voucher entity, I want to denormalize the the client entity in this operation ( to be able to validate the properties later) but it won't show in the swagger documentation
Voucher Entity :
<?php
/**
* #ApiResource(
* collectionOperations={
* "add_voucher"={
* "access_control"="is_granted('ROLE_COMMERCIAL')",
* "method"="POST",
* "path"="/vouchers/add-new",
* "controller"=AddVoucherAction::class,
* "security_post_denormalize_message"="Sorry, Only Commercials can Generate Vouchers",
* "denormalization_context"={
* "groups"={"add_new_voucher"}
* },
* "validation_groups"={"Default", "add_voucher_validation"}
* },
* }
* )
* #ORM\Entity(repositoryClass="App\Repository\VoucherRepository", repositoryClass=VoucherRepository::class)
*/
class Voucher
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #Groups("add_new_voucher")
* #ORM\Column(type="string", length=255, unique=true)
*/
private $code;
/**
* #Groups("add_new_voucher")
* #ORM\Column(type="integer")
*/
private $discount;
/**
* #Groups("add_new_voucher")
* #OneToOne(targetEntity="App\Entity\Client")
* #JoinColumn(name="client_id", referencedColumnName="id")
*/
private $client;
public function getDiscount()
{
return $this->discount;
}
public function setDiscount($discount): void
{
$this->discount = $discount;
}
public function getClient()
{
return $this->client;
}
public function setClient($client): void
{
$this->client = $client;
}
public function getId(): ?int
{
return $this->id;
}
public function getCode(): ?string
{
return $this->code;
}
public function setCode(string $code): self
{
$this->code = $code;
return $this;
}
}
Client Entity :
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\ClientRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use App\Entity\Language;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ApiResource(
* collectionOperations={
* "post"={
* "method"="POST",
* "validation_groups"={"registerValidation"},
* }
* },
* denormalizationContext={"groups"={"register"}}
* )
* #ORM\Entity(repositoryClass=ClientRepository::class)
*/
class Client extends User
{
/**
* #Groups("register")
* #ORM\ManyToOne(targetEntity=Language::class, inversedBy="client")
*/
private $language;
/**
* #Groups({"register","add_new_voucher"})
* #Assert\NotBlank(groups="registerValidation")
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $country;
/**
* #Groups("register")
* #Assert\NotBlank(groups="registerValidation")
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $currency;
/**
* #Groups("register")
* #Assert\NotBlank(groups="registerValidation")
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $timezone;
/**
* #Groups("register")
* #Assert\NotBlank(groups="registerValidation")
* #ORM\Column(type="integer", nullable=true)
*/
private $phone;
/**
* Client constructor.
* #param $language
* #param $country
* #param $currency
* #param $timezone
* #param $phone
*/
public function __construct($language, $country, $currency, $timezone, $phone)
{
parent:: __construct();
$this->language = $language;
$this->country = $country;
$this->currency = $currency;
$this->timezone = $timezone;
$this->phone = $phone;
}
public function getLanguage()
{
return $this->language;
}
public function setLanguage($language): void
{
$this->language = $language;
}
public function getCountry(): ?string
{
return $this->country;
}
public function setCountry(?string $country): self
{
$this->country = $country;
return $this;
}
public function getCurrency(): ?string
{
return $this->currency;
}
public function setCurrency(?string $currency): self
{
$this->currency = $currency;
return $this;
}
public function getTimezone(): ?string
{
return $this->timezone;
}
public function setTimezone(?string $timezone): self
{
$this->timezone = $timezone;
return $this;
}
public function getPhone(): ?int
{
return $this->phone;
}
public function setPhone(?int $phone): self
{
$this->phone = $phone;
return $this;
}
}
I tried to add the denormalization group to the client relation and to the country property in client entity but in swagger the operation show only the code and discount property

Symfony 4 Add ManyToMany Entity trough FORM

I am heavily stuck on problem with inserting data trough html.twig when passing one Entity to the other. I am able to add or edit single entities but i cant figure out how to handle adding relations.
Tournament Entity class - unimportant stuff deleted
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Tournament.
*
* #ORM\Table(name="tournament")
* #ORM\Entity(repositoryClass="App\Repository\TournamentRepository")
*/
class Tournament
{
/**
* #var int
*
* #ORM\Column(name="id_tournament", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idTournament;
/**
* #var string
*
* #ORM\Column(name="name_of_event", type="string", length=128, nullable=false)
*/
private $nameOfEvent;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=16, nullable=false)
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="prizepool", type="string", length=32, nullable=false)
*/
private $prizepool;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=128, nullable=false)
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=32, nullable=false)
*/
private $country;
/**
* #var \DateTime
*
* #ORM\Column(name="start_date", type="date", nullable=false)
*/
private $startDate;
/**
* #var \DateTime
*
* #ORM\Column(name="end_date", type="date", nullable=false)
*/
private $endDate;
/**
* #var string|null
*
* #ORM\Column(name="tournament_Img", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $tournamentImg = 'NULL';
/**
* #ORM\OneToMany(targetEntity="App\Entity\Eventstandings", mappedBy="tourn")
*/
private $events;
/**
* #ORM\OneToMany(targetEntity=Comment::class, mappedBy="tourn_id")
*/
private $comments;
/**
* #ORM\ManyToMany(targetEntity=Team::class, inversedBy="tournaments")
* #ORM\JoinTable(name="playedAt", joinColumns={#ORM\JoinColumn(name="tourn_id", referencedColumnName="id_tournament")},
* inverseJoinColumns={#ORM\JoinColumn(name="team_id", referencedColumnName="ID_Team")})
*/
private $teams;
/**
* #return ArrayCollection
*/
public function getEvents(): Collection
{
return $this->events;
}
/**
* #param ArrayCollection $events
*/
public function setEvents(Collection $events): void
{
$this->events = $events;
}
public function __construct()
{
$this->teams = new ArrayCollection();
$this->events = new ArrayCollection();
$this->comments = new ArrayCollection();
}
public function getIdTournament(): ?int
{
return $this->idTournament;
}
public function addTeam(Team $team): self
{
if (!$this->teams->contains($team)) {
$this->teams[] = $team;
}
return $this;
}
public function removeTeam(Team $team): self
{
if ($this->teams->contains($team)) {
$this->teams->removeElement($team);
}
return $this;
}
}
Team Entity class
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
/**
* Team.
*
* #ORM\Table(name="team")
* #ORM\Entity(repositoryClass="App\Repository\TeamRepository")
*/
class Team
{
/**
* #var int
*
* #ORM\Column(name="ID_Team", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idTeam;
/**
* #var string
*
* #ORM\Column(name="Name", type="string", length=128, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="Region", type="text", length=65535, nullable=false)
*/
private $region;
/**
* #var string
*
* #ORM\Column(name="Coach", type="string", length=64, nullable=false)
*/
private $coach;
/**
* #var string
*
* #ORM\Column(name="Total_Earnings", type="string", length=64, nullable=false)
*/
private $totalEarnings;
/**
* #var string|null
*
* #ORM\Column(name="img_Path", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $imgPath = 'NULL';
/**
* #ORM\OneToMany(targetEntity=Player::class, mappedBy="team", cascade={"persist","remove"})
*/
private $ownedPlayers;
/**
* #var string|null
*
* #ORM\Column(name="player_Img", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $playerImg = 'NULL';
/**
* #ORM\OneToMany(targetEntity="App\Entity\Eventstandings", mappedBy="team")
*/
private $playedEventAsoc;
/**
* #ORM\ManyToMany(targetEntity=Tournament::class, mappedBy="teams")
*/
private $tournaments;
public function getIdTeam(): ?int
{
return $this->idTeam;
}
public function __construct()
{
$this->tournaments = new ArrayCollection();
$this->playedEventAsoc = new ArrayCollection();
$this->ownedPlayers = new ArrayCollection();
}
public function getPlayedEventAsoc(): Collection
{
return $this->playedEventAsoc;
}
public function setPlayedEventAsoc(Collection $playedEventAsoc): void
{
$this->playedEventAsoc = $playedEventAsoc;
}
public function getStandings(): void
{
$standings = getPlayedEventAsoc().$this->getStandings();
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getRegion(): ?string
{
return $this->region;
}
public function setRegion(string $region): self
{
$this->region = $region;
return $this;
}
public function getCoach(): ?string
{
return $this->coach;
}
public function setCoach(string $coach): self
{
$this->coach = $coach;
return $this;
}
public function getTotalEarnings(): ?string
{
return $this->totalEarnings;
}
public function setTotalEarnings(string $totalEarnings): self
{
$this->totalEarnings = $totalEarnings;
return $this;
}
public function getImgPath(): ?string
{
return $this->imgPath;
}
public function setImgPath(?string $imgPath): self
{
$this->imgPath = $imgPath;
return $this;
}
public function getPlayerImg(): ?string
{
return $this->playerImg;
}
public function setPlayerImg(?string $playerImg): self
{
$this->playerImg = $playerImg;
return $this;
}
public function addPlayer(Player $player): self
{
if (!$this->ownedPlayers->contains($player)) {
$this->ownedPlayers[] = $player;
$player->setTeam($this);
}
return $this;
}
public function removePlayer(Player $player): self
{
if ($this->ownedPlayers->contains($player)) {
$this->ownedPlayers->removeElement($player);
// set the owning side to null (unless already changed)
if ($player->getTeam() === $this) {
$player->setTeam(null);
}
}
return $this;
}
/**
* #return Collection|Player[]
*/
public function getOwnedPlayers(): Collection
{
return $this->ownedPlayers;
}
public function addOwnedPlayer(Player $ownedPlayer): self
{
if (!$this->ownedPlayers->contains($ownedPlayer)) {
$this->ownedPlayers[] = $ownedPlayer;
$ownedPlayer->setTeam($this);
}
return $this;
}
public function removeOwnedPlayer(Player $ownedPlayer): self
{
if ($this->ownedPlayers->contains($ownedPlayer)) {
$this->ownedPlayers->removeElement($ownedPlayer);
// set the owning side to null (unless already changed)
if ($ownedPlayer->getTeam() === $this) {
$ownedPlayer->setTeam(null);
}
}
return $this;
}
public function addEvents(Eventstandings $event): self
{
if (!$this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc[] = $event;
$event->setTeam($this);
}
return $this;
}
public function removeEvents(Eventstandings $event): self
{
if ($this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc->removeElement($event);
// set the owning side to null (unless already changed)
if ($event->getTeam() === $this) {
$event->setTeam(null);
}
}
return $this;
}
public function addEvent(Eventstandings $event): self
{
if (!$this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc[] = $event;
$event->setTeam($this);
}
return $this;
}
public function removeEvent(Eventstandings $event): self
{
if ($this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc->removeElement($event);
// set the owning side to null (unless already changed)
if ($event->getTeam() === $this) {
$event->setTeam(null);
}
}
return $this;
}
public function getEventData(PersistentCollection $playedEvents): array
{
$eventdata = $playedEvents->getValues();
return $eventdata;
}
public function addPlayedEventAsoc(Eventstandings $playedEventAsoc): self
{
if (!$this->playedEventAsoc->contains($playedEventAsoc)) {
$this->playedEventAsoc[] = $playedEventAsoc;
$playedEventAsoc->setTeam($this);
}
return $this;
}
public function removePlayedEventAsoc(Eventstandings $playedEventAsoc): self
{
if ($this->playedEventAsoc->contains($playedEventAsoc)) {
$this->playedEventAsoc->removeElement($playedEventAsoc);
// set the owning side to null (unless already changed)
if ($playedEventAsoc->getTeam() === $this) {
$playedEventAsoc->setTeam(null);
}
}
return $this;
}
/**
* #return Collection|Tournament[]
*/
public function getTournaments(): Collection
{
return $this->tournaments;
}
public function addTournament(Tournament $tournament): self
{
if (!$this->tournaments->contains($tournament)) {
$this->tournaments[] = $tournament;
$tournament->addTeam($this);
}
return $this;
}
public function removeTournament(Tournament $tournament): self
{
if ($this->tournaments->contains($tournament)) {
$this->tournaments->removeElement($tournament);
$tournament->removeTeam($this);
}
return $this;
}
}
I am able to edit tournament or team data trough forms and save it to database.
What I am not able is to add data into this relation.
Form Class for this
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('team', EntityType::class, array(
'class' => Team::class,
'multiple' => true,
'expanded' => true,
))
->add('Add Team', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Tournament::class
]);
}
Tournament Controller method addTeam - should add Team Entity into Trounament teams collection
/**
* #param Team $team
* #param Request $request
* #Route("/addTeamToEvent/{idTournament}",name="addTeamToEvent")
* #return RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function addTeam(Tournament $tournament, Request $request)
{
$form = $this->createForm(TeamToEvent::class, $tournament);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->persist($tournament);
$this->entityManager->flush();
return new RedirectResponse($this->router->generate('welcome'));
}
return $this->render('welcome/addTeamToEvent.html.twig', ['form' => $form->createView()]);
}
What should be the right aproach? I am totaly lost and i don't know how to do this.

Select one Secteur and then get all groupements belong to the Secteur in Symfony 4

The line $groupement[] = null === $secteurs ? null : $secteurs->getSecteurid();
in the Eleveurtype.php is not working Please i need Some help
The work i wanted to do is to select one Secteur and then i want to get all groupements belong to the Secteur
This is The EleveurType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('secteurid',EntityType::class, [
'label'=>'Nom du secteur :',
'class' => Secteurs::class,
'choice_label' => 'secteurfr',
'attr'=>[
'class'=>'form-control',
]
])
;
$formModifier = function (FormInterface $form, Secteurs $secteurs = null) {
//$secteurs = null === $secteurs ? [] : $secteurs->getSecteurid();
$groupement[] = null === $secteurs ? null : $secteurs->getSecteurid();
$form->add('groupementid', EntityType::class, [
'class' => Groupements::class,
'placeholder' => '',
'choices' => $groupement,
'attr'=>[
'class'=>'form-control',
]
]);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
$formModifier($event->getForm(), $data->getSecteurid());
}
);
$builder->get('secteurid')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$secteur = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $secteur);
}
);
}
This is The _form.html.twig Eleveur
{{ form_start(form, {'attr': {'id': 'newform', 'nam': nam } }) }}
{{ form_widget(form) }}
<button type="button" class="{{ classBtnAddEdit|default('btn btnAED btn-success waves-effect waves-light m-1') }} " id="btnAddEdit"><i class="fa fa-check-square-o"></i> Enregistrer</button>
{{ form_end(form) }}
<script>
var $secteur = $('#eleveurs_secteurid');
// When sport gets selected ...
$secteur.change(function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected sport value.
var data = {};
data[$secteur.attr('name')] = $secteur.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('nam'), //= $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#eleveurs_groupementid').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#eleveurs_groupementid')
);
// Position field now displays the appropriate positions.
}
});
});
</script>
** this is the Eleveur Class Eleveur **
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Eleveurs
*
* #ORM\Table(name="eleveurs", indexes={#ORM\Index(name="fk_relationship_47", columns={"groupementid"}), #ORM\Index(name="fk_relationship_53", columns={"douarid"}), #ORM\Index(name="fk_relationship_16", columns={"secteurid"}), #ORM\Index(name="fk_relationship_49", columns={"villeid"})})
* #ORM\Entity
*/
class Eleveurs
{
/**
* #var int
*
* #ORM\Column(name="eleveurid", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $eleveurid;
/**
* #var string|null
*
* #ORM\Column(name="codeeleveur", type="text", length=65535, nullable=true)
*/
private $codeeleveur;
/**
* #var string|null
*
* #ORM\Column(name="numcin", type="text", length=65535, nullable=true)
*/
private $numcin;
/**
* #var \DateTime|null
*
* #ORM\Column(name="datecin", type="date", nullable=true)
*/
private $datecin;
/**
* #var \DateTime|null
*
* #ORM\Column(name="validitecin", type="date", nullable=true)
*/
private $validitecin;
/**
* #var string|null
*
* #ORM\Column(name="nomfr", type="text", length=65535, nullable=true)
*/
private $nomfr;
/**
* #var string|null
*
* #ORM\Column(name="prenomfr", type="text", length=65535, nullable=true)
*/
private $prenomfr;
/**
* #var string|null
*
* #ORM\Column(name="nomar", type="text", length=65535, nullable=true)
*/
private $nomar;
/**
* #var string|null
*
* #ORM\Column(name="prenomar", type="text", length=65535, nullable=true)
*/
private $prenomar;
/**
* #var \DateTime|null
*
* #ORM\Column(name="dateadhesion", type="date", nullable=true)
*/
private $dateadhesion;
/**
* #var string|null
*
* #ORM\Column(name="adressefr", type="text", length=65535, nullable=true)
*/
private $adressefr;
/**
* #var string|null
*
* #ORM\Column(name="adressear", type="text", length=65535, nullable=true)
*/
private $adressear;
/**
* #var int|null
*
* #ORM\Column(name="effectifovin", type="integer", nullable=true)
*/
private $effectifovin;
/**
* #var int|null
*
* #ORM\Column(name="effectifcaprin", type="integer", nullable=true)
*/
private $effectifcaprin;
/**
* #var \Secteurs
*
* #ORM\ManyToOne(targetEntity="Secteurs")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="secteurid", referencedColumnName="secteurid")
* })
*/
private $secteurid;
/**
* #var \Groupements
*
* #ORM\ManyToOne(targetEntity="Groupements")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="groupementid", referencedColumnName="groupementid")
* })
*/
private $groupementid;
/**
* #var \Villes
*
* #ORM\ManyToOne(targetEntity="Villes")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="villeid", referencedColumnName="villeid")
* })
*/
private $villeid;
/**
* #var \Douars
*
* #ORM\ManyToOne(targetEntity="Douars")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="douarid", referencedColumnName="douarid")
* })
*/
private $douarid;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Conseilgroupement", mappedBy="eleveurid")
*/
private $conseilgroupementid;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Droitfonctionement", inversedBy="eleveurid")
* #ORM\JoinTable(name="relationship_32",
* joinColumns={
* #ORM\JoinColumn(name="eleveurid", referencedColumnName="eleveurid")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="droitfonctionementid", referencedColumnName="droitfonctionementid")
* }
* )
*/
private $droitfonctionementid;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Conseilanoc", mappedBy="eleveurid")
*/
private $conseilanocid;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Superviseurs", mappedBy="eleveurid")
*/
private $histosuperviseurid;
/**
* Constructor
*/
public function __construct()
{
$this->conseilgroupementid = new \Doctrine\Common\Collections\ArrayCollection();
$this->droitfonctionementid = new \Doctrine\Common\Collections\ArrayCollection();
$this->conseilanocid = new \Doctrine\Common\Collections\ArrayCollection();
$this->histosuperviseurid = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getEleveurid(): ?int
{
return $this->eleveurid;
}
public function getCodeeleveur(): ?string
{
return $this->codeeleveur;
}
public function setCodeeleveur(?string $codeeleveur): self
{
$this->codeeleveur = $codeeleveur;
return $this;
}
public function getNumcin(): ?string
{
return $this->numcin;
}
public function setNumcin(?string $numcin): self
{
$this->numcin = $numcin;
return $this;
}
public function getDatecin(): ?\DateTimeInterface
{
return $this->datecin;
}
public function setDatecin(?\DateTimeInterface $datecin): self
{
$this->datecin = $datecin;
return $this;
}
public function getValiditecin(): ?\DateTimeInterface
{
return $this->validitecin;
}
public function setValiditecin(?\DateTimeInterface $validitecin): self
{
$this->validitecin = $validitecin;
return $this;
}
public function getNomfr(): ?string
{
return $this->nomfr;
}
public function setNomfr(?string $nomfr): self
{
$this->nomfr = $nomfr;
return $this;
}
public function getPrenomfr(): ?string
{
return $this->prenomfr;
}
public function setPrenomfr(?string $prenomfr): self
{
$this->prenomfr = $prenomfr;
return $this;
}
public function getNomar(): ?string
{
return $this->nomar;
}
public function setNomar(?string $nomar): self
{
$this->nomar = $nomar;
return $this;
}
public function getPrenomar(): ?string
{
return $this->prenomar;
}
public function setPrenomar(?string $prenomar): self
{
$this->prenomar = $prenomar;
return $this;
}
public function getDateadhesion(): ?\DateTimeInterface
{
return $this->dateadhesion;
}
public function setDateadhesion(?\DateTimeInterface $dateadhesion): self
{
$this->dateadhesion = $dateadhesion;
return $this;
}
public function getAdressefr(): ?string
{
return $this->adressefr;
}
public function setAdressefr(?string $adressefr): self
{
$this->adressefr = $adressefr;
return $this;
}
public function getAdressear(): ?string
{
return $this->adressear;
}
public function setAdressear(?string $adressear): self
{
$this->adressear = $adressear;
return $this;
}
public function getEffectifovin(): ?int
{
return $this->effectifovin;
}
public function setEffectifovin(?int $effectifovin): self
{
$this->effectifovin = $effectifovin;
return $this;
}
public function getEffectifcaprin(): ?int
{
return $this->effectifcaprin;
}
public function setEffectifcaprin(?int $effectifcaprin): self
{
$this->effectifcaprin = $effectifcaprin;
return $this;
}
public function getSecteurid(): ?Secteurs
{
return $this->secteurid;
}
public function setSecteurid(?Secteurs $secteurid): self
{
$this->secteurid = $secteurid;
return $this;
}
public function getGroupementid(): ?Groupements
{
return $this->groupementid;
}
public function setGroupementid(?Groupements $groupementid): self
{
$this->groupementid = $groupementid;
return $this;
}
public function getVilleid(): ?Villes
{
return $this->villeid;
}
public function setVilleid(?Villes $villeid): self
{
$this->villeid = $villeid;
return $this;
}
public function getDouarid(): ?Douars
{
return $this->douarid;
}
public function setDouarid(?Douars $douarid): self
{
$this->douarid = $douarid;
return $this;
}
/**
* #return Collection|Conseilgroupement[]
*/
public function getConseilgroupementid(): Collection
{
return $this->conseilgroupementid;
}
public function addConseilgroupementid(Conseilgroupement $conseilgroupementid): self
{
if (!$this->conseilgroupementid->contains($conseilgroupementid)) {
$this->conseilgroupementid[] = $conseilgroupementid;
$conseilgroupementid->addEleveurid($this);
}
return $this;
}
public function removeConseilgroupementid(Conseilgroupement $conseilgroupementid): self
{
if ($this->conseilgroupementid->contains($conseilgroupementid)) {
$this->conseilgroupementid->removeElement($conseilgroupementid);
$conseilgroupementid->removeEleveurid($this);
<
** This is the Secteur class **
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Secteurs
*
* #ORM\Table(name="secteurs")
* #ORM\Entity
*/
class Secteurs
{
/**
* #var int
*
* #ORM\Column(name="secteurid", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $secteurid;
/**
* #var string|null
*
* #ORM\Column(name="secteurfr", type="text", length=65535, nullable=true)
*/
private $secteurfr;
/**
* #var string|null
*
* #ORM\Column(name="secteurar", type="text", length=65535, nullable=true)
*/
private $secteurar;
/**
* #var string|null
*
* #ORM\Column(name="codesecteur", type="text", length=65535, nullable=true)
*/
private $codesecteur;
public function getSecteurid(): ?int
{
return $this->secteurid;
}
public function getSecteurfr(): ?string
{
return $this->secteurfr;
}
public function setSecteurfr(?string $secteurfr): self
{
$this->secteurfr = ucfirst($secteurfr);
return $this;
}
public function getSecteurar(): ?string
{
return $this->secteurar;
}
public function setSecteurar(?string $secteurar): self
{
$this->secteurar = $secteurar;
return $this;
}
public function getCodesecteur(): ?string
{
return $this->codesecteur;
}
public function setCodesecteur(?string $codesecteur): self
{
$this->codesecteur = strtoupper($codesecteur);
return $this;
}
}
** this is the groupement class **
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Groupements
*
* #ORM\Table(name="groupements", indexes={#ORM\Index(name="fk_relationship_54", columns={"secteurid"})})
* #ORM\Entity
*/
class Groupements
{
/**
* #var int
*
* #ORM\Column(name="groupementid", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $groupementid;
/**
* #var string|null
*
* #ORM\Column(name="groupementmereid", type="decimal", precision=8, scale=0, nullable=true)
*/
private $groupementmereid;
/**
* #var string|null
*
* #ORM\Column(name="codegroupement", type="text", length=65535, nullable=true)
*/
private $codegroupement;
/**
* #var string|null
*
* #ORM\Column(name="nomgroupementfr", type="text", length=65535, nullable=true)
*/
private $nomgroupementfr;
/**
* #var string|null
*
* #ORM\Column(name="nomgroupementar", type="text", length=65535, nullable=true)
*/
private $nomgroupementar;
/**
* #var string|null
*
* #ORM\Column(name="adressepostale", type="text", length=65535, nullable=true)
*/
private $adressepostale;
/**
* #var \DateTime|null
*
* #ORM\Column(name="datecreation", type="date", nullable=true)
*/
private $datecreation;
/**
* #var string|null
*
* #ORM\Column(name="pvcreation", type="text", length=65535, nullable=true)
*/
private $pvcreation;
/**
* #var float|null
*
* #ORM\Column(name="droitfonctionement", type="float", precision=10, scale=0, nullable=true)
*/
private $droitfonctionement;
/**
* #var float|null
*
* #ORM\Column(name="autrecotisations", type="float", precision=10, scale=0, nullable=true)
*/
private $autrecotisations;
/**
* #var string|null
*
* #ORM\Column(name="effectifovinencadre", type="decimal", precision=8, scale=0, nullable=true)
*/
private $effectifovinencadre;
/**
* #var string|null
*
* #ORM\Column(name="effectifcaprinencadre", type="decimal", precision=8, scale=0, nullable=true)
*/
private $effectifcaprinencadre;
/**
* #var string|null
*
* #ORM\Column(name="lieupvcreation", type="text", length=65535, nullable=true)
*/
private $lieupvcreation;
/**
* #var \DateTime|null
*
* #ORM\Column(name="datepvcreation", type="date", nullable=true)
*/
private $datepvcreation;
/**
* #var \Secteurs
*
* #ORM\ManyToOne(targetEntity="Secteurs")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="secteurid", referencedColumnName="secteurid")
* })
*/
private $secteurid;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Droitfonctionement", inversedBy="groupementid")
* #ORM\JoinTable(name="relationship_31",
* joinColumns={
* #ORM\JoinColumn(name="groupementid", referencedColumnName="groupementid")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="droitfonctionementid", referencedColumnName="droitfonctionementid")
* }
* )
*/
private $droitfonctionementid;
/**
* Constructor
*/
public function __construct()
{
$this->droitfonctionementid = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getGroupementid(): ?int
{
return $this->groupementid;
}
public function getGroupementmereid(): ?string
{
return $this->groupementmereid;
}
public function setGroupementmereid(?string $groupementmereid): self
{
$this->groupementmereid = $groupementmereid;
return $this;
}
public function getCodegroupement(): ?string
{
return $this->codegroupement;
}
public function setCodegroupement(?string $codegroupement): self
{
$this->codegroupement = $codegroupement;
return $this;
}
public function getNomgroupementfr(): ?string
{
return $this->nomgroupementfr;
}
public function setNomgroupementfr(?string $nomgroupementfr): self
{
$this->nomgroupementfr = $nomgroupementfr;
return $this;
}
public function getNomgroupementar(): ?string
{
return $this->nomgroupementar;
}
public function setNomgroupementar(?string $nomgroupementar): self
{
$this->nomgroupementar = $nomgroupementar;
return $this;
}
public function getAdressepostale(): ?string
{
return $this->adressepostale;
}
public function setAdressepostale(?string $adressepostale): self
{
$this->adressepostale = $adressepostale;
return $this;
}
public function getDatecreation(): ?\DateTimeInterface
{
return $this->datecreation;
}
public function setDatecreation(?\DateTimeInterface $datecreation): self
{
$this->datecreation = $datecreation;
return $this;
}
public function getPvcreation(): ?string
{
return $this->pvcreation;
}
public function setPvcreation(?string $pvcreation): self
{
$this->pvcreation = $pvcreation;
return $this;
}
public function getDroitfonctionement(): ?float
{
return $this->droitfonctionement;
}
public function setDroitfonctionement(?float $droitfonctionement): self
{
$this->droitfonctionement = $droitfonctionement;
return $this;
}
public function getAutrecotisations(): ?float
{
return $this->autrecotisations;
}
public function setAutrecotisations(?float $autrecotisations): self
{
$this->autrecotisations = $autrecotisations;
return $this;
}
public function getEffectifovinencadre(): ?string
{
return $this->effectifovinencadre;
}
public function setEffectifovinencadre(?string $effectifovinencadre): self
{
$this->effectifovinencadre = $effectifovinencadre;
return $this;
}
public function getEffectifcaprinencadre(): ?string
{
return $this->effectifcaprinencadre;
}
public function setEffectifcaprinencadre(?string $effectifcaprinencadre): self
{
$this->effectifcaprinencadre = $effectifcaprinencadre;
return $this;
}
public function getLieupvcreation(): ?string
{
return $this->lieupvcreation;
}
public function setLieupvcreation(?string $lieupvcreation): self
{
$this->lieupvcreation = $lieupvcreation;
return $this;
}
public function getDatepvcreation(): ?\DateTimeInterface
{
return $this->datepvcreation;
}
public function setDatepvcreation(?\DateTimeInterface $datepvcreation): self
{
$this->datepvcreation = $datepvcreation;
return $this;
}
public function getSecteurid(): ?Secteurs
{
return $this->secteurid;
}
public function setSecteurid(?Secteurs $secteurid): self
{
$this->secteurid = $secteurid;
return $this;
}
/**
* #return Collection|Droitfonctionement[]
*/
public function getDroitfonctionementid(): Collection
{
return $this->droitfonctionementid;
}
public function addDroitfonctionementid(Droitfonctionement $droitfonctionementid): self
{
if (!$this->droitfonctionementid->contains($droitfonctionementid)) {
$this->droitfonctionementid[] = $droitfonctionementid;
}
return $this;
}
public function removeDroitfonctionementid(Droitfonctionement $droitfonctionementid): self
{
if ($this->droitfonctionementid->contains($droitfonctionementid)) {
$this->droitfonctionementid->removeElement($droitfonctionementid);
}
return $this;
}
}

Categories