How to get a single column from a Doctrine Array Collection? - php

i have a entity called "AreasProfesionales"
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping\InverseJoinColumn;
use ApiPlatform\Doctrine\Orm\Filter\OrderFilter;
use App\Repository\AreasProfesionalesRepository;
use Doctrine\Common\Collections\ArrayCollection;
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
#[ORM\Entity(repositoryClass: AreasProfesionalesRepository::class)]
#[UniqueEntity(fields: ['Codigo'], message: 'Ya existe un area profesional registrada con ese mismo código')]
#[ApiFilter(SearchFilter::class, properties: ['Denominacion' => 'partial', 'Codigo' => 'partial', 'familiasProfesionales'=> 'exact'])]
#[ApiFilter(OrderFilter::class, properties: ['id'], arguments: ['orderParameterName' => 'order'])]
#[ApiResource(paginationEnabled: false,formats: ['json' => ['application/json']],
normalizationContext: ['groups' => ['read']],
denormalizationContext: ['groups' => ['write']])]
class AreasProfesionales
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['read','write'])]
#[ApiProperty(writable:true)]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Groups(['read','write'])]
private ?string $Denominacion = null;
#[ORM\Column(length: 20, unique:true)]
#[Groups(['read', 'write'])]
private ?string $Codigo = null;
#[ORM\ManyToOne(inversedBy: 'Familiasprofesionales_areasprofesionales')]
#[Groups(['read','write'])]
#[InverseJoinColumn(name: "familias_profesionales_id", referencedColumnName: "id")]
#[ApiProperty(readableLink: true, writableLink: true)]
private ?FamiliasProfesionales $familiasProfesionales = null;
#[ORM\OneToMany(mappedBy: 'areasProfesionales', targetEntity: CertificadosProfesionalidad::class)]
private Collection $Areasprofesionales_certificadosprofesionalidad;
#[ORM\OneToMany(mappedBy: 'areasProfesionales', targetEntity: AreasProfesionalesDocentes::class)]
private Collection $Areasprofesionales_areasprofesionalesdocentes;
#[ORM\OneToMany(mappedBy: 'areasProfesionales', targetEntity: AreasProfesionalesItinerariosFormativos::class)]
private Collection $Areasprofesionales_areasprofesionalesitinerariosformativos;
public function __construct()
{
$this->Areasprofesionales_certificadosprofesionalidad = new ArrayCollection();
$this->Areasprofesionales_areasprofesionalesdocentes = new ArrayCollection();
$this->Areasprofesionales_areasprofesionalesitinerariosformativos = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getDenominacion(): ?string
{
return $this->Denominacion;
}
public function setDenominacion(string $Denominacion): self
{
$this->Denominacion = $Denominacion;
return $this;
}
public function getCodigo(): ?string
{
return $this->Codigo;
}
public function setCodigo(string $Codigo): self
{
$this->Codigo = $Codigo;
return $this;
}
public function getFamiliasProfesionales(): ?FamiliasProfesionales
{
return $this->familiasProfesionales;
}
public function setFamiliasProfesionales(?FamiliasProfesionales $familiasProfesionales): self
{
$this->familiasProfesionales = $familiasProfesionales;
return $this;
}
/**
* #return Collection<int, CertificadosProfesionalidad>
*/
/*public function getAreasprofesionalesCertificadosprofesionalidad(): Collection
{
return $this->Areasprofesionales_certificadosprofesionalidad;
}
public function addAreasprofesionalesCertificadosprofesionalidad(CertificadosProfesionalidad $areasprofesionalesCertificadosprofesionalidad): self
{
if (!$this->Areasprofesionales_certificadosprofesionalidad->contains($areasprofesionalesCertificadosprofesionalidad)) {
$this->Areasprofesionales_certificadosprofesionalidad->add($areasprofesionalesCertificadosprofesionalidad);
$areasprofesionalesCertificadosprofesionalidad->setAreasProfesionales($this);
}
return $this;
}
public function removeAreasprofesionalesCertificadosprofesionalidad(CertificadosProfesionalidad $areasprofesionalesCertificadosprofesionalidad): self
{
if ($this->Areasprofesionales_certificadosprofesionalidad->removeElement($areasprofesionalesCertificadosprofesionalidad)) {
// set the owning side to null (unless already changed)
if ($areasprofesionalesCertificadosprofesionalidad->getAreasProfesionales() === $this) {
$areasprofesionalesCertificadosprofesionalidad->setAreasProfesionales(null);
}
}
return $this;
}*/
/**
* #return Collection<int, AreasProfesionalesDocentes>
*/
/public function getAreasprofesionalesAreasprofesionalesdocentes(): Collection
{
return $this->Areasprofesionales_areasprofesionalesdocentes;
}
public function addAreasprofesionalesAreasprofesionalesdocente(AreasProfesionalesDocentes $areasprofesionalesAreasprofesionalesdocente): self
{
if (!$this->Areasprofesionales_areasprofesionalesdocentes->contains($areasprofesionalesAreasprofesionalesdocente)) {
$this->Areasprofesionales_areasprofesionalesdocentes->add($areasprofesionalesAreasprofesionalesdocente);
$areasprofesionalesAreasprofesionalesdocente->setAreasProfesionales($this);
}
return $this;
}
public function removeAreasprofesionalesAreasprofesionalesdocente(AreasProfesionalesDocentes $areasprofesionalesAreasprofesionalesdocente): self
{
if ($this->Areasprofesionales_areasprofesionalesdocentes->removeElement($areasprofesionalesAreasprofesionalesdocente)) {
// set the owning side to null (unless already changed)
if ($areasprofesionalesAreasprofesionalesdocente->getAreasProfesionales() === $this) {
$areasprofesionalesAreasprofesionalesdocente->setAreasProfesionales(null);
}
}
return $this;
}*/
/**
* #return Collection<int, AreasProfesionalesItinerariosFormativos>
*/
public function getAreasprofesionalesAreasprofesionalesitinerariosformativos(): Collection
{
return $this->Areasprofesionales_areasprofesionalesitinerariosformativos;
}
public function addAreasprofesionalesAreasprofesionalesitinerariosformativo(AreasProfesionalesItinerariosFormativos $areasprofesionalesAreasprofesionalesitinerariosformativo): self
{
if (!$this->Areasprofesionales_areasprofesionalesitinerariosformativos->contains($areasprofesionalesAreasprofesionalesitinerariosformativo)) {
$this->Areasprofesionales_areasprofesionalesitinerariosformativos->add($areasprofesionalesAreasprofesionalesitinerariosformativo);
$areasprofesionalesAreasprofesionalesitinerariosformativo->setAreasProfesionales($this);
}
return $this;
}
public function removeAreasprofesionalesAreasprofesionalesitinerariosformativo(AreasProfesionalesItinerariosFormativos $areasprofesionalesAreasprofesionalesitinerariosformativo): self
{
if ($this->Areasprofesionales_areasprofesionalesitinerariosformativos->removeElement($areasprofesionalesAreasprofesionalesitinerariosformativo)) {
// set the owning side to null (unless already changed)
if ($areasprofesionalesAreasprofesionalesitinerariosformativo->getAreasProfesionales() === $this) {
$areasprofesionalesAreasprofesionalesitinerariosformativo->setAreasProfesionales(null);
}
}
return $this;
}
public function __toString()
{
return $this->id;
}
I have another entity called "FamiliasProfesionales"
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use Doctrine\Common\Collections\Collection;
use ApiPlatform\Doctrine\Orm\Filter\OrderFilter;
use Doctrine\Common\Collections\ArrayCollection;
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
use App\Repository\FamiliasProfesionalesRepository;
use Symfony\Component\Serializer\Annotation\Groups;
#[ORM\Entity(repositoryClass: FamiliasProfesionalesRepository::class)]
#[ApiFilter(SearchFilter::class, properties: ['Denominacion' => 'partial'])]
#[ApiFilter(OrderFilter::class, properties: ['id', 'Denominacion'], arguments: ['orderParameterName' => 'order'])]
#[ApiResource(paginationEnabled: false,formats: ['json' => ['application/json']],
normalizationContext: ['groups' => ['read']],
denormalizationContext: ['groups' => ['write']])]
class FamiliasProfesionales
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['read','write'])]
#[ApiProperty(writable:true)]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Groups(['read','write'])]
private ?string $Denominacion = null;
#[ORM\OneToMany(mappedBy: 'familiasProfesionales', targetEntity: AreasProfesionales::class)]
#[ORM\JoinColumn()]
private Collection $Familiasprofesionales_areasprofesionales;
public function __construct()
{
$this->Familiasprofesionales_areasprofesionales = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getDenominacion(): ?string
{
return $this->Denominacion;
}
public function setDenominacion(string $Denominacion): self
{
$this->Denominacion = $Denominacion;
return $this;
}
/**
* #return Collection<int, AreasProfesionales>
*/
public function getFamiliasprofesionalesAreasprofesionales(): Collection
{
return $this->Familiasprofesionales_areasprofesionales;
}
public function addFamiliasprofesionalesAreasprofesionale(AreasProfesionales $familiasprofesionalesAreasprofesionale): self
{
if (!$this->Familiasprofesionales_areasprofesionales->contains($familiasprofesionalesAreasprofesionale)) {
$this->Familiasprofesionales_areasprofesionales->add($familiasprofesionalesAreasprofesionale);
$familiasprofesionalesAreasprofesionale->setFamiliasProfesionales($this);
}
return $this;
}
public function removeFamiliasprofesionalesAreasprofesionale(AreasProfesionales $familiasprofesionalesAreasprofesionale): self
{
if ($this->Familiasprofesionales_areasprofesionales->removeElement($familiasprofesionalesAreasprofesionale)) {
// set the owning side to null (unless already changed)
if ($familiasprofesionalesAreasprofesionale->getFamiliasProfesionales() === $this) {
$familiasprofesionalesAreasprofesionale->setFamiliasProfesionales(null);
}
}
return $this;
}
public function __toString()
{
return $this->id;
}
}
I´m using API PLATFORM in my proyect to show all the operations and services.
Is there a way to get only a single field from the Collection? I want the entity "AreasProfesionales" to only appear, for example, the id from "FamiliasProfesionales"
if I need to create a new professional area in the POST method, I only have to enter the id of the professional family to which it belongs and not have to enter all the other data, however, it returns all its fields.Thank you in advance.
I have been trying using the read and write methods of API Platform, but I don't get the result I want, I think the problem is that Api Platform works with IRI and not with id (but i need work with this one).

Yes you can :
<?php
// api/src/Entity/Book.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;
#[ApiResource(normalizationContext: ['groups' => ['book']])]
class Book
{
#[Groups('book')]
public $name;
#[Groups('book')]
public $author;
// ...
}
you can follow this documentation : https://api-platform.com/docs/core/serialization/
Regards,

Related

Call to a member function get...() on null

Hello guys I need help.
I'm trying to build a forum for my website in symfony.
I have an entity Theme who regroup the entity Slug who regroup the entity Post.
When I navigate to the slug route to see the posts, I have the error "Call to a member function getSlug() on null".
But this function is called in another route.
Here is my different entity.
Theme
<?php
namespace App\Entity;
use App\Repository\ThemeRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ThemeRepository::class)]
class Theme
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string', length: 255)]
private $name;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private $imageName;
#[ORM\OneToMany(mappedBy: 'theme', targetEntity: Slug::class, orphanRemoval: true)]
private $slug;
public function __construct()
{
$this->slug = 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 getImageName(): ?string
{
return $this->imageName;
}
public function setImageName(?string $imageName): self
{
$this->imageName = $imageName;
return $this;
}
/**
* #return Collection<int, Slug>
*/
public function getSlug(): Collection
{
return $this->slug;
}
public function addSlug(Slug $slug): self
{
if (!$this->slug->contains($slug)) {
$this->slug[] = $slug;
$slug->setTheme($this);
}
return $this;
}
public function removeSlug(Slug $slug): self
{
if ($this->slug->removeElement($slug)) {
// set the owning side to null (unless already changed)
if ($slug->getTheme() === $this) {
$slug->setTheme(null);
}
}
return $this;
}
}
Slug
<?php
namespace App\Entity;
use App\Repository\SlugRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: SlugRepository::class)]
class Slug
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string', length: 255)]
private $slugName;
#[ORM\OneToMany(mappedBy: 'slug', targetEntity: Post::class, orphanRemoval: true)]
private $posts;
#[ORM\ManyToOne(targetEntity: Theme::class, inversedBy: 'slug')]
#[ORM\JoinColumn(nullable: false)]
private $theme;
public function __construct()
{
$this->posts = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getSlugName(): ?string
{
return $this->slugName;
}
public function setSlugName(string $slugName): self
{
$this->slugName = $slugName;
return $this;
}
/**
* #return Collection<int, Post>
*/
public function getPosts(): Collection
{
return $this->posts;
}
public function addPost(Post $post): self
{
if (!$this->posts->contains($post)) {
$this->posts[] = $post;
$post->setSlug($this);
}
return $this;
}
public function removePost(Post $post): self
{
if ($this->posts->removeElement($post)) {
// set the owning side to null (unless already changed)
if ($post->getSlug() === $this) {
$post->setSlug(null);
}
}
return $this;
}
public function getTheme(): ?Theme
{
return $this->theme;
}
public function setTheme(?Theme $theme): self
{
$this->theme = $theme;
return $this;
}
}
Post
<?php
namespace App\Entity;
use App\Repository\PostRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: PostRepository::class)]
class Post
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'text')]
private $content;
#[ORM\Column(type: 'datetime_immutable')]
private $createdAt;
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
private $updatedAt;
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'posts')]
#[ORM\JoinColumn(nullable: false)]
private $user;
#[ORM\ManyToOne(targetEntity: Slug::class, inversedBy: 'posts')]
#[ORM\JoinColumn(nullable: false)]
private $slug;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private $imageName;
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTimeImmutable $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getSlug(): ?Slug
{
return $this->slug;
}
public function setSlug(?Slug $slug): self
{
$this->slug = $slug;
return $this;
}
public function getImageName(): ?string
{
return $this->imageName;
}
public function setImageName(?string $imageName): self
{
$this->imageName = $imageName;
return $this;
}
}
And here is my controller
<?php
namespace App\Controller;
use App\Repository\SlugRepository;
use App\Repository\ThemeRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ForumController extends AbstractController
{
#[Route('/forum', name: 'forum')]
public function index(SlugRepository $slugRepository, ThemeRepository $themeRepository ): Response
{
$themes = $themeRepository->findAll();
return $this->render('forum/index.html.twig', [
'themes' => $themes,
]);
}
#[Route('/forum/{name}/{id}', name: 'theme')]
public function theme(string $name, $id, ThemeRepository $themeRepository ): Response
{
$themesId = $themeRepository->find($id);
$themes = $themeRepository->find($name);
$slugs = $themesId->getSlug();
$allThemes = $themeRepository->findAll();
return $this->render('forum/theme.html.twig', [
'themes' => $themesId,
'slugs' => $slugs,
'allThemes' => $allThemes,
]);
}
#[Route('/forum/{name}/{slugName}', name: 'slug')]
public function slug(string $name, string $slugName, $id,SlugRepository $slugRepository, ThemeRepository $themeRepository ): Response
{
$slugName = $slugRepository->find($slugName);
$slugsId = $slugRepository->find($id);
$themesId = $slugsId->getTheme()->getName($name);
$allThemes = $themeRepository->findAll();
return $this->render('forum/slug.html.twig', [
'themes' => $themesId,
'slugs' => $slugsId,
'allThemes' => $allThemes,
]);
}
}
I'm working on symfony 5.0.8
Thanks for your help.
In your method ForumController::theme the method $themeRepository->find() does not return a Theme object but null and $themes is unused.
$themesId = $themeRepository->find($id); // <- returns null
Solution: query by id and name explicitly.
$theme = $themeRepository->findOneBy([
'id' => $id,
'name' => $name
]);
if (!$theme) {
// log id and name, return a 404
}
$slug = $theme->getSlug();

Doctrine 2 Query returns class description?

I have a small simple symfony 6.1.4 application and wanted to write a API for a few Entities, but when i fetch the data from the database (mysql) i get something what looks like a class description.
$test = $this->audienceRepository->createQueryBuilder('s')->getQuery()->getResult();
var_dump($test);
Entity
<?php
namespace App\Entity;
use App\Repository\AudienceRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: AudienceRepository::class)]
class Audience
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column]
private ?bool $is_department = null;
#[ORM\Column]
private ?bool $is_company = null;
#[ORM\OneToMany(mappedBy: 'department', targetEntity: User::class)]
private Collection $users;
#[ORM\ManyToMany(targetEntity: Seminar::class, mappedBy: 'audience')]
private Collection $seminars;
public function __construct()
{
$this->users = new ArrayCollection();
$this->seminars = 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 isIsDepartment(): ?bool
{
return $this->is_department;
}
public function setIsDepartment(bool $is_department): self
{
$this->is_department = $is_department;
return $this;
}
public function isIsCompany(): ?bool
{
return $this->is_company;
}
public function setIsCompany(bool $is_company): self
{
$this->is_company = $is_company;
return $this;
}
/**
* #return Collection<int, User>
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users->add($user);
$user->setDepartment($this);
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->removeElement($user)) {
// set the owning side to null (unless already changed)
if ($user->getDepartment() === $this) {
$user->setDepartment(null);
}
}
return $this;
}
/**
* #return Collection<int, Seminar>
*/
public function getSeminars(): Collection
{
return $this->seminars;
}
public function addSeminar(Seminar $seminar): self
{
if (!$this->seminars->contains($seminar)) {
$this->seminars->add($seminar);
$seminar->addAudience($this);
}
return $this;
}
public function removeSeminar(Seminar $seminar): self
{
if ($this->seminars->removeElement($seminar)) {
$seminar->removeAudience($this);
}
return $this;
}
}
Repository
namespace App\Repository;
use App\Entity\Audience;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* #extends ServiceEntityRepository<Audience>
*
* #method Audience|null find($id, $lockMode = null, $lockVersion = null)
* #method Audience|null findOneBy(array $criteria, array $orderBy = null)
* #method Audience[] findAll()
* #method Audience[] findBy(array $criteria, array $orderBy = null, $limit =null, $offset = null)
*/
class AudienceRepository extends ServiceEntityRepository {
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Audience::class);
}
public function add(Audience $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Audience $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
result of var_dumb
I couldnt find why doctrine is behaving this way. Does someone know why and how to prevent that?
Everything is correct as the doctrine returns to you Objects of your ENTITY filled with data from the DB
You get Each row as a separate class and can use it as follows
<?php
foreach($results as $audience) {
$audience->getId();
}
Doctrine return to you list object with set data in Entity: Example
<?php
class Audience
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = 12;
#[ORM\Column(length: 255)]
private ?string $name = "You name from DB";
#[ORM\Column]
private ?bool $is_department = true;
#[ORM\Column]
private ?bool $is_company = true;
#[ORM\OneToMany(mappedBy: 'department', targetEntity: User::class)]
private Collection $users = new Collection(<With Users objects>);;
#[ORM\ManyToMany(targetEntity: Seminar::class, mappedBy: 'audience')]
private Collection $seminars = new Collection(<With Seminars objects>);

Symfony, when i delete a "deliver" it delete "user" too. How to only delete the "deliver"

i have a problem with my code and maybe with with my relations into my database. I will expose you my code next. I want to delete only a deliver, but it delete me the user too. If you can help me because I don't uderstand why it does this. Thank you
My database view
Deliverer.php
<?php
namespace App\Entity;
use App\Repository\DelivererRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: DelivererRepository::class)]
class Deliverer
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: Types::DECIMAL, precision: 3, scale: 1, nullable: true)]
private ?string $rate = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $info = null;
#[ORM\OneToMany(mappedBy: 'deliverer', targetEntity: Order::class)]
private Collection $orders;
#[ORM\ManyToOne(inversedBy: 'deliverers')]
private ?Vehicle $vehicle = null;
#[ORM\Column]
private ?int $nbRate = 0;
#[ORM\OneToOne(inversedBy: 'deliverer', cascade: ['persist', 'remove'])]
private ?User $user = null;
public function __construct()
{
$this->orders = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRate(): ?string
{
return $this->rate;
}
public function setRate(?string $rate): self
{
$this->rate = $rate;
return $this;
}
public function getInfo(): ?string
{
return $this->info;
}
public function setInfo(?string $info): self
{
$this->info = $info;
return $this;
}
/**
* #return Collection<int, Order>
*/
public function getOrders(): Collection
{
return $this->orders;
}
public function addOrder(Order $order): self
{
if (!$this->orders->contains($order)) {
$this->orders->add($order);
$order->setDeliverer($this);
}
return $this;
}
public function removeOrder(Order $order): self
{
if ($this->orders->removeElement($order)) {
// set the owning side to null (unless already changed)
if ($order->getDeliverer() === $this) {
$order->setDeliverer(null);
}
}
return $this;
}
public function getVehicle(): ?Vehicle
{
return $this->vehicle;
}
public function setVehicle(?Vehicle $vehicle): self
{
$this->vehicle = $vehicle;
return $this;
}
public function getNbRate(): ?int
{
return $this->nbRate;
}
public function setNbRate(int $nbRate): self
{
$this->nbRate += 1;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
User.php
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
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: 255)]
private ?string $address = null;
#[ORM\ManyToMany(targetEntity: Promotion::class, inversedBy: 'users')]
private Collection $promotion;
#[ORM\OneToOne(mappedBy: 'user', cascade: ['persist', 'remove'])]
private ?RestaurantInfo $restaurantInfo = null;
#[ORM\OneToMany(mappedBy: 'user', targetEntity: Order::class)]
private Collection $orders;
#[ORM\Column(length: 255)]
private ?string $firstName = null;
#[ORM\Column(length: 255)]
private ?string $lastName = null;
#[ORM\Column(length: 255)]
private ?string $phoneNumber = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private ?\DateTimeInterface $birthDate = null;
#[ORM\ManyToMany(targetEntity: Restaurant::class, inversedBy: 'users')]
private Collection $favorites;
#[ORM\OneToOne(mappedBy: 'user', cascade: ['persist', 'remove'])]
private ?Deliverer $deliverer = null;
public function __construct()
{
$this->promotion = new ArrayCollection();
$this->orders = new ArrayCollection();
$this->favorites = 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
if($roles == null)
$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 getAddress(): ?string
{
return $this->address;
}
public function setAddress(string $address): self
{
$this->address = $address;
return $this;
}
/**
* #return Collection<int, Promotion>
*/
public function getPromotion(): Collection
{
return $this->promotion;
}
public function addPromotion(Promotion $promotion): self
{
if (!$this->promotion->contains($promotion)) {
$this->promotion->add($promotion);
}
return $this;
}
public function removePromotion(Promotion $promotion): self
{
$this->promotion->removeElement($promotion);
return $this;
}
public function getRestaurantInfo(): ?RestaurantInfo
{
return $this->restaurantInfo;
}
public function setRestaurantInfo(?RestaurantInfo $restaurantInfo): self
{
// unset the owning side of the relation if necessary
if ($restaurantInfo === null && $this->restaurantInfo !== null) {
$this->restaurantInfo->setUser(null);
}
// set the owning side of the relation if necessary
if ($restaurantInfo !== null && $restaurantInfo->getUser() !== $this) {
$restaurantInfo->setUser($this);
}
$this->restaurantInfo = $restaurantInfo;
return $this;
}
/**
* #return Collection<int, Order>
*/
public function getOrders(): Collection
{
return $this->orders;
}
public function addOrder(Order $order): self
{
if (!$this->orders->contains($order)) {
$this->orders->add($order);
$order->setUser($this);
}
return $this;
}
public function removeOrder(Order $order): self
{
if ($this->orders->removeElement($order)) {
// set the owning side to null (unless already changed)
if ($order->getUser() === $this) {
$order->setUser(null);
}
}
return $this;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
public function getPhoneNumber(): ?string
{
return $this->phoneNumber;
}
public function setPhoneNumber(string $phoneNumber): self
{
$this->phoneNumber = $phoneNumber;
return $this;
}
public function getBirthDate(): ?\DateTimeInterface
{
return $this->birthDate;
}
public function setBirthDate(\DateTimeInterface $birthDate): self
{
$this->birthDate = $birthDate;
return $this;
}
public function __toString()
{
return (string) $this->getId();
}
/**
* #return Collection<int, Restaurant>
*/
public function getFavorites(): Collection
{
return $this->favorites;
}
public function addFavorite(Restaurant $favorite): self
{
if (!$this->favorites->contains($favorite)) {
$this->favorites->add($favorite);
}
return $this;
}
public function removeFavorite(Restaurant $favorite): self
{
$this->favorites->removeElement($favorite);
return $this;
}
public function getDeliverer(): ?Deliverer
{
return $this->deliverer;
}
public function setDeliverer(?Deliverer $deliverer): self
{
// unset the owning side of the relation if necessary
if ($deliverer === null && $this->deliverer !== null) {
$this->deliverer->setUser(null);
}
// set the owning side of the relation if necessary
if ($deliverer !== null && $deliverer->getUser() !== $this) {
$deliverer->setUser($this);
}
$this->deliverer = $deliverer;
return $this;
}
}
UserController.php
<?php
namespace App\Controller;
use App\Entity\Deliverer;
use App\Entity\User;
use App\Form\UserType;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* #Route("/user")
*/
class UserController extends AbstractController
{
/**
* #Route("/", name="app_user_index", methods={"GET"})
*/
public function index(UserRepository $userRepository): Response
{
// $user = $this->getUser();
// return $this->render('user/index.html.twig', [
// 'user' => $user,
// ]);
return $this->render('user/index.html.twig', [
'users' => $userRepository->findAll(),
]);
}
/**
* #Route("/new", name="app_user_new", methods={"GET", "POST"})
*/
public function new(Request $request, UserRepository $userRepository): Response
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$userRepository->add($user, true);
return $this->redirectToRoute('app_user_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('user/new.html.twig', [
'user' => $user,
'form' => $form,
]);
}
/**
* #Route("/{id}", name="app_user_show", methods={"GET"})
*/
public function show(User $user, $id): Response
{
$vehicle = 1;
$vehicle = 1;
$user_session = $this->getUser();
$deliverer = $user->getDeliverer();
if ($deliverer) {
$vehicle = $deliverer->getVehicle();
$orders = $deliverer->getOrders();
}
$favorites = $user->getFavorites();
// Profil utilisateur seulement accessible à celui qui est connecté. Si url modifier avec un id d'un autre user on en peut pas voir le profil de l'autre
if ($user_session->getId() == intval($id)) {
return $this->render('user/show.html.twig', [
'user' => $user,
'deliverer' => $deliverer,
'vehicle' => $vehicle,
'orders' => $orders,
'favorites' => $favorites,
]);
}
$id = 1000;
return $this->render('user/show.html.twig', [
'user' => $user_session,
'deliverer' => $deliverer,
'vehicle' => $vehicle,
'orders' => $orders,
'favorites' => $favorites,
]);
}
/**
* #Route("/{id}/edit", name="app_user_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, User $user, UserRepository $userRepository): Response
{
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$userRepository->add($user, true);
return $this->redirectToRoute('app_user_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('user/edit.html.twig', [
'user' => $user,
'form' => $form,
]);
}
/**
* #Route("/{id}", name="app_user_delete", methods={"POST"})
*/
public function delete(Request $request, User $user, UserRepository $userRepository): Response
{
if ($this->isCsrfTokenValid('delete' . $user->getId(), $request->request->get('_token')))
{
$userRepository->remove($user, true);
}
return $this->redirectToRoute('app_user_index', [], Response::HTTP_SEE_OTHER);
}
}
DelivererController.php
<?php
namespace App\Controller;
use App\Entity\Deliverer;
use App\Form\DelivererType;
use App\Repository\DelivererRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
/**
* #Route("/deliverer")
*/
class DelivererController extends AbstractController
{
/**
* #Route("/", name="app_deliverer_index", methods={"GET"})
*/
public function index(DelivererRepository $delivererRepository): Response
{
$user = $this->getUser();
return $this->render('deliverer/index.html.twig', [
'deliverers' => $delivererRepository->findAll(),
'user' => $user,
]);
}
/**
* #Route("/new", name="app_deliverer_new", methods={"GET", "POST"})
*/
public function new(Request $request, DelivererRepository $delivererRepository, EntityManagerInterface $entityManager): Response
{
$user = $this->getUser();
$user_id = $user->getId();
$user_roles = $user->getRoles();
// Si l'utilisateur est déjà un livreur impossible de le devenir, retourne à sa page profil
if (in_array('ROLE_LIVREUR', $user_roles)) {
return $this->redirectToRoute('app_user_show', ['id' => $user_id]);
}
$deliverer = new Deliverer();
$form = $this->createForm(DelivererType::class, $deliverer);
$form->handleRequest($request);
$id = 1326580;
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($deliverer);
$id = 1000;
$user->setRoles(array('ROLE_USER', 'ROLE_LIVREUR'));
$user->setDeliverer($deliverer);
$entityManager->persist($user);
$entityManager->flush();
// Reload user authentification with new roles. If not error to resdirection because user entity is null
$token = new UsernamePasswordToken($this->getUser(), null, 'main', $this->getUser()->getRoles());
$this->get('security.token_storage')->setToken($token);
$user_id = $this->get('security.token_storage')->getToken()->getUser()->getId();
$user = $this->getUser();
return $this->redirectToRoute('app_user_show', ['id' => $user_id]);
}
return $this->renderForm('deliverer/new.html.twig', [
'deliverer' => $deliverer,
'form' => $form,
'user' => $user,
'id' => $id,
]);
}
/**
* #Route("/{id}", name="app_deliverer_show", methods={"GET"})
*/
public function show(Deliverer $deliverer): Response
{
$user = $this->getUser();
return $this->render('deliverer/show.html.twig', [
'deliverer' => $deliverer,
'user' => $user,
]);
}
/**
* #Route("/{id}/edit", name="app_deliverer_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, Deliverer $deliverer, DelivererRepository $delivererRepository): Response
{
$form = $this->createForm(DelivererType::class, $deliverer);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$delivererRepository->add($deliverer, true);
$user_id = $this->get('security.token_storage')->getToken()->getUser()->getId();
return $this->redirectToRoute('app_user_show', ['id' => $user_id]);
// return $this->redirectToRoute('app_deliverer_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('deliverer/edit.html.twig', [
'deliverer' => $deliverer,
'form' => $form,
]);
}
/**
* #Route("/{id}", name="app_deliverer_delete", methods={"POST"})
*/
public function delete(Request $request, Deliverer $deliverer, DelivererRepository $delivererRepository): Response
{
if ($this->isCsrfTokenValid('delete'.$deliverer->getId(), $request->request->get('_token'))) {
$delivererRepository->remove($deliverer, true);
}
return $this->redirectToRoute('app_deliverer_index', [], Response::HTTP_SEE_OTHER);
}
}
Deliverer.php
remplace
[ORM\OneToOne(inversedBy: 'deliverer', cascade: ['persist', 'remove'])]
by
[ORM\OneToOne(inversedBy: 'deliverer', cascade: ['persist'])]
<?php
namespace App\Entity;
use App\Repository\DelivererRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: DelivererRepository::class)]
class Deliverer
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: Types::DECIMAL, precision: 3, scale: 1, nullable: true)]
private ?string $rate = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $info = null;
#[ORM\OneToMany(mappedBy: 'deliverer', targetEntity: Order::class)]
private Collection $orders;
#[ORM\ManyToOne(inversedBy: 'deliverers')]
private ?Vehicle $vehicle = null;
#[ORM\Column]
private ?int $nbRate = 0;
#[ORM\OneToOne(inversedBy: 'deliverer', cascade: ['persist'])]
private ?User $user = null;
...
to complete #Yusuf answer:
Thanks to cascade: remove, you can easily delete a user and all linked comments without having to loop through them:
https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#transitive-persistence-cascade-operations
In your annotation, you just need to remove the option "remove" in the cascade option.

Symfony 6 - How to access properties of object of specific ID

I have two entities - one is Product, second - Order. I've created controllers to navigate between page of ProductController that lists the whole ProductRepository to the page of OrderController, which should:
take a Product ID to show its properties on the Order page (name and price)
have a form with quantity and "customer's" email to be added to the Order
calculate the price x quantity and add to the Order
I can't figure how to access the passed project's properties. I am able to access it via addProduct method of the Order entity, but cannot reach them to show them in twig nor manipulate them on variables as described above.
I'm sure it's a simple stuff but I am not sure even how to ask google the right way on this.
we click on a product from ProductRepository with
<a href="{{ path('app_order', {id: product.id}) }}">
and we go to OrderController
OrderController:
<?php
namespace App\Controller;
class OrderController extends AbstractController
{
#[Route('/order', name: 'app_order')]
public function addToOrder(ManagerRegistry $doctrine, Request $request, EntityManagerInterface $em): Response
{
$orderedProductId = (int) ($request->query->get('id'));
$pPrice = 1;
$order = new Order();
$order->addProduct($doctrine->getRepository(Product::class)->find($orderedProductId));
$form = $this->createFormBuilder($order)
->add('clientEmail', TextType::class)
->add('quantity', IntegerType::class)
->add('makeOrder', SubmitType::class, ['label' => 'Make Order'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//$data = $form->getData();
$order->setStatus("Pending");
$order->setTotalSum(1);
$em->persist($order);
$em->flush();
}
return $this->render('order/index.html.twig', [
'form'=> $form->createView(),
'order'=> $order
]);
}
}
The entities look like this:
Product
<?php
namespace App\Entity;
use App\Repository\ProductRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ProductRepository::class)]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string')]
private $name;
#[ORM\Column(type: 'integer')]
private $price;
#[ORM\Column(type: 'boolean')]
private $visible;
#[ORM\ManyToOne(targetEntity: Order::class, inversedBy: 'product')]
private $orderIds;
public function getId(): ?int
{
return $this->id;
}
public function getPrice(): ?int
{
return $this->price;
}
public function setPrice(int $price): self
{
$this->price = $price;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function isVisible(): ?bool
{
return $this->visible;
}
public function setVisible(bool $visible): self
{
$this->visible = $visible;
return $this;
}
public function getOrderIds(): ?Order
{
return $this->orderIds;
}
public function setOrderIds(?Order $orderIds): self
{
$this->orderIds = $orderIds;
return $this;
}
}
Order:
<?php
namespace App\Entity;
use App\Repository\OrderRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: OrderRepository::class)]
#[ORM\Table(name: '`order`')]
class Order
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'integer')]
private $totalSum;
#[ORM\Column(type: 'string', length: 255)]
private $status;
#[ORM\Column(type: 'integer')]
private $quantity;
#[ORM\OneToMany(mappedBy: 'orderIds', targetEntity: Product::class)]
private $product;
#[ORM\Column(type: 'string', length: 255)]
private $clientEmail;
public function __construct()
{
$this->product = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTotalSum(): ?int
{
return $this->totalSum;
}
public function setTotalSum(int $totalSum): self
{
$this->totalSum = $totalSum;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
public function getQuantity(): ?int
{
return $this->quantity;
}
public function setQuantity(int $quantity): self
{
$this->quantity = $quantity;
return $this;
}
/**
* #return Collection<int, Product>
*/
public function getProduct(): Collection
{
return $this->product;
}
public function addProduct(Product $product): self
{
if (!$this->product->contains($product)) {
$this->product[] = $product;
$product->setOrderIds($this);
}
return $this;
}
public function removeProduct(Product $product): self
{
if ($this->product->removeElement($product)) {
// set the owning side to null (unless already changed)
if ($product->getOrderIds() === $this) {
$product->setOrderIds(null);
}
}
return $this;
}
public function getClientEmail(): ?string
{
return $this->clientEmail;
}
public function setClientEmail(string $clientEmail): self
{
$this->clientEmail = $clientEmail;
return $this;
}
}
OK I got this.
Changed a property taken by OrderController from EntityManager to ProductRepository, then
$product= $productRepository->find($orderedProductId);
also: this is helpful: Getting only ID from entity relations without fetching whole object in Doctrine
solved!

Symfony 6 data access and transmission between multiple tables with format error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
The project is a website written in symfony. The problem there is that
there is a user and a consultant which is a separate table, but a user
becomes the consultant, and when this consultant wants to give up his
free time and I want to store it in a third table that listens for
the interval name I have to fill in the consultant ID.
user_table:
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string', length: 180, unique: true)]
private $email;
#[ORM\Column(type: 'json')]
private $roles = [];
#[ORM\Column(type: 'string')]
private $password;
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[] = '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;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
}
cons table:
<?php
namespace App\Entity;
use App\Repository\ConsRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ConsRepository::class)]
class Cons
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\OneToOne(targetEntity: User::class, cascade: ['persist', 'remove'])]
private $user;
#[ORM\OneToMany(mappedBy: 'cons_id', targetEntity: Intervall::class)]
private $intervalls;
public function __construct()
{
$this->intervalls = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getUserId(): ?User
{
return $this->user;
}
public function setUserId(?User $user): self
{
$this->user = $user;
return $this;
}
/**
* #return Collection|Intervall[]
*/
public function getIntervalls(): Collection
{
return $this->intervalls;
}
public function addIntervall(Intervall $intervall): self
{
if (!$this->intervalls->contains($intervall)) {
$this->intervalls[] = $intervall;
$intervall->setConsId($this);
}
return $this;
}
public function removeIntervall(Intervall $intervall): self
{
if ($this->intervalls->removeElement($intervall)) {
// set the owning side to null (unless already changed)
if ($intervall->getConsId() === $this) {
$intervall->setConsId(null);
}
}
return $this;
}
}
intervall table:
<?php
namespace App\Entity;
use App\Repository\IntervallRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: IntervallRepository::class)]
class Intervall
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'datetime')]
private $start;
#[ORM\Column(type: 'datetime')]
private $end;
#[ORM\Column(type: 'boolean')]
private $more;
#[ORM\Column(type: 'time')]
private $cons_time;
#[ORM\Column(type: 'time')]
private $free_time;
#[ORM\ManyToOne(targetEntity: Cons::class, inversedBy: 'intervalls')]
private $cons;
public function __construct()
{
$this->cons = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getStart(): ?\DateTimeInterface
{
return $this->start;
}
public function setStart(\DateTimeInterface $start): self
{
$this->start = $start;
return $this;
}
public function getEnd(): ?\DateTimeInterface
{
return $this->end;
}
public function setEnd(\DateTimeInterface $end): self
{
$this->end = $end;
return $this;
}
public function getMore(): ?bool
{
return $this->more;
}
public function setMore(bool $more): self
{
$this->more = $more;
return $this;
}
public function getConsTime(): ?\DateTimeInterface
{
return $this->cons_time;
}
public function setConsTime(\DateTimeInterface $cons_time): self
{
$this->cons_time = $cons_time;
return $this;
}
public function getFreeTime(): ?\DateTimeInterface
{
return $this->free_time;
}
public function setFreeTime(\DateTimeInterface $free_time): self
{
$this->free_time = $free_time;
return $this;
}
public function getConsId(): ?Cons
{
return $this->cons;
}
public function setConsId(?Cons $cons): self
{
$this->cons = $cons;
return $this;
}
}
intervall wrong code slise:
#[Route('/new', name: 'intervall_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$user_id = $this->getUser()->getId();
$cnsuseridrepo = $entityManager->getRepository(Cons::class);
$cnsuserid = $cnsuseridrepo->findOneBy(["user"=>$user_id]);
$intervall = new Intervall();
$intervall->setConsId(($cnsuserid->getId());
$form = $this->createForm(IntervallType::class, $intervall);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($intervall);
$entityManager->flush();
return $this->redirectToRoute('intervall_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('intervall/new.html.twig', [
'intervall' => $intervall,
'form' => $form,
]);
}
that would be the mistake I see:
Seems like setter method allows only object of Cons or null value, so you have to set it as object.
$intervall = new Intervall();
$intervall->setConsId($cnsuserid);
$form = $this->createForm(IntervallType::class, $intervall);
$form->handleRequest($request);

Categories