i want to create a user, but the user entity is connected to the entities role, address and personInfo, but i get the error that personInfo_id cannot be null? how do i pass in the id
i tried a value where i would manually pass the id, but that didn't work
This is my User entity
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 30)]
private ?string $password = null;
#[ORM\OneToOne(inversedBy: 'User', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: false)]
private ?Role $roleId = null;
#[ORM\OneToMany(mappedBy: 'UserId', targetEntity: PersonInfo::class, orphanRemoval: true, cascade:['persist'])]
private Collection $PersonInfoId;
#[ORM\ManyToOne(cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: false)]
private ?PersonInfo $personInfoId = null;
#[ORM\ManyToOne(inversedBy: 'UserId')]
#[ORM\JoinColumn(nullable: false)]
private ?Address $AddressId = null;
#[ORM\OneToMany(mappedBy: 'UserId', targetEntity: Address::class, orphanRemoval: true)]
private Collection $UserId;
public function __construct()
{
$this->PersonInfoId = new ArrayCollection();
$this->UserId = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getRoleId(): ?Role
{
return $this->roleId;
}
public function setRoleId(Role $roleId): self
{
$this->roleId = $roleId;
return $this;
}
/**
* #return Collection<int, PersonInfo>
*/
public function getPersonInfoId(): Collection
{
return $this->PersonInfoId;
}
public function addPersonInfoId(PersonInfo $personInfoId): self
{
if (!$this->PersonInfoId->contains($personInfoId)) {
$this->PersonInfoId->add($personInfoId);
$personInfoId->setUserId($this);
}
return $this;
}
public function removePersonInfoId(PersonInfo $personInfoId): self
{
if ($this->PersonInfoId->removeElement($personInfoId)) {
// set the owning side to null (unless already changed)
if ($personInfoId->getUserId() === $this) {
$personInfoId->setUserId(null);
}
}
return $this;
}
public function setPersonInfoId(?PersonInfo $personInfoId): self
{
$this->personInfoId = $personInfoId;
return $this;
}
public function getAddressId(): ?Address
{
return $this->AddressId;
}
public function setAddressId(?Address $AddressId): self
{
$this->AddressId = $AddressId;
return $this;
}
/**
* #return Collection<int, Address>
*/
public function getUserId(): Collection
{
return $this->UserId;
}
public function addUserId(Address $userId): self
{
if (!$this->UserId->contains($userId)) {
$this->UserId->add($userId);
$userId->setUserId($this);
}
return $this;
}
public function removeUserId(Address $userId): self
{
if ($this->UserId->removeElement($userId)) {
// set the owning side to null (unless already changed)
if ($userId->getUserId() === $this) {
$userId->setUserId(null);
}
}
return $this;
}
}
Role Entity
<?php
namespace App\Entity;
use App\Repository\RoleRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: RoleRepository::class)]
class Role
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 30)]
private ?string $name = null;
#[ORM\OneToOne(mappedBy: 'roleId', cascade: ['persist', 'remove'])]
private ?User $User = null;
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 getUser(): ?User
{
return $this->User;
}
public function setUser(User $User): self
{
// set the owning side of the relation if necessary
if ($User->getRoleId() !== $this) {
$User->setRoleId($this);
}
$this->User = $User;
return $this;
}
}
PersonInfo Entity :
<?php
namespace App\Entity;
use App\Repository\PersonInfoRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: PersonInfoRepository::class)]
class PersonInfo
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 30)]
private ?string $name = null;
#[ORM\Column(length: 30)]
private ?string $email = null;
#[ORM\Column]
private ?int $phone_number = null;
#[ORM\ManyToOne(inversedBy: 'PersonInfoId', cascade: ['persist'])]
#[ORM\JoinColumn(nullable: false)]
private ?User $UserId = null;
#[ORM\ManyToOne(inversedBy: 'addressId')]
#[ORM\JoinColumn(nullable: false)]
private ?Address $addressId = null;
#[ORM\OneToMany(mappedBy: 'personInfoId', targetEntity: ContactPersoon::class, orphanRemoval: true)]
private Collection $personInfoId;
public function __construct()
{
$this->personInfoId = 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 getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPhoneNumber(): ?int
{
return $this->phone_number;
}
public function setPhoneNumber(int $phone_number): self
{
$this->phone_number = $phone_number;
return $this;
}
public function getUserId(): ?User
{
return $this->UserId;
}
public function setUserId(?User $UserId): self
{
$this->UserId = $UserId;
return $this;
}
public function getAddressId(): ?Address
{
return $this->addressId;
}
public function setAddressId(?Address $addressId): self
{
$this->addressId = $addressId;
return $this;
}
/**
* #return Collection<int, ContactPersoon>
*/
public function getPersonInfoId(): Collection
{
return $this->personInfoId;
}
public function addPersonInfoId(ContactPersoon $personInfoId): self
{
if (!$this->personInfoId->contains($personInfoId)) {
$this->personInfoId->add($personInfoId);
$personInfoId->setPersonInfoId($this);
}
return $this;
}
public function removePersonInfoId(ContactPersoon $personInfoId): self
{
if ($this->personInfoId->removeElement($personInfoId)) {
// set the owning side to null (unless already changed)
if ($personInfoId->getPersonInfoId() === $this) {
$personInfoId->setPersonInfoId(null);
}
}
return $this;
}
}
This is the erd that i designed if that may help with building the pictureThe ERD
please help
In class User and class PersonInfo both entity has nullable=false field mapping so you must need to pass object when you are creating user. For example:
$user = new User();
$personInfo = new PersonInfo();
$user->addPersonInfoId($personInfo); // Here argument must be object of PersonInfo instead of Id.
$em->persist($user);
$em->flush();
The roles of my user entity aren't save well in database.
I have a basic question but I didn't find the solution so I'm asking it myself here.
When I create an user he he's register with the role ROLE_USER. But in my database he's save as a:0:{}
Do you have an idea of what I can do to store them as [] by default.
Ok here is my user entity:
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`', options:["collate"=>"utf8mb4_unicode_ci", "charset"=>"utf8mb4"])]
#[UniqueEntity(fields: ['mail'], message: 'There is already an account with this mail.')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: Types::ARRAY, nullable: true)]
private array $roles = [];
#[ORM\Column(length: 255)]
private ?string $username = null;
#[ORM\Column(length: 255)]
private ?string $password = null;
#[ORM\Column(length: 255)]
private ?string $group_role = null;
#[ORM\Column(length: 255)]
private ?string $mail = null;
#[ORM\Column(length: 255)]
private ?string $firstname = null;
#[ORM\Column(length: 255)]
private ?string $lastname = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE, options: ['default' => 'CURRENT_TIMESTAMP'])]
private ?\DateTime $create_datetime = null;
#[ORM\Column(length: 255)]
private ?string $notif_rule = null;
#[ORM\OneToMany(mappedBy: 'his_user', targetEntity: Logs::class, orphanRemoval: true)]
private Collection $logs;
#[ORM\OneToMany(mappedBy: 'his_user', targetEntity: Session::class)]
private Collection $sessions;
#[ORM\OneToMany(mappedBy: 'his_user', targetEntity: Access::class, orphanRemoval: true)]
private Collection $accesses;
public function __construct()
{
$this->logs = new ArrayCollection();
$this->sessions = new ArrayCollection();
$this->accesses = new ArrayCollection();
$this->create_datetime = new \DateTime( );
}
public function getId(): ?int
{
return $this->id;
}
/**
* #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;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getGroupRole(): ?string
{
return $this->group_role;
}
public function setGroupRole(string $group_role): self
{
$this->group_role = $group_role;
return $this;
}
public function getMail(): ?string
{
return $this->mail;
}
public function setMail(string $mail): self
{
$this->mail = $mail;
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 getCreateDatetime(): ?\DateTimeInterface
{
return $this->create_datetime;
}
public function setCreateDatetime(\DateTimeInterface $create_datetime): self
{
$this->create_datetime = $create_datetime;
return $this;
}
public function getNotifRule(): ?string
{
return $this->notif_rule;
}
public function setNotifRule(string $notif_rule): self
{
$this->notif_rule = $notif_rule;
return $this;
}
/**
* #return Collection<int, Logs>
*/
public function getLogs(): Collection
{
return $this->logs;
}
public function addLog(Logs $log): self
{
if (!$this->logs->contains($log)) {
$this->logs->add($log);
$log->setHisUser($this);
}
return $this;
}
public function removeLog(Logs $log): self
{
if ($this->logs->removeElement($log)) {
// set the owning side to null (unless already changed)
if ($log->getHisUser() === $this) {
$log->setHisUser(null);
}
}
return $this;
}
/**
* #return Collection<int, Session>
*/
public function getSessions(): Collection
{
return $this->sessions;
}
public function addSession(Session $session): self
{
if (!$this->sessions->contains($session)) {
$this->sessions->add($session);
$session->setHisUser($this);
}
return $this;
}
public function removeSession(Session $session): self
{
if ($this->sessions->removeElement($session)) {
// set the owning side to null (unless already changed)
if ($session->getHisUser() === $this) {
$session->setHisUser(null);
}
}
return $this;
}
/**
* #return Collection<int, Access>
*/
public function getAccesses(): Collection
{
return $this->accesses;
}
public function addAccess(Access $access): self
{
if (!$this->accesses->contains($access)) {
$this->accesses->add($access);
$access->setHisUser($this);
}
return $this;
}
public function removeAccess(Access $access): self
{
if ($this->accesses->removeElement($access)) {
// set the owning side to null (unless already changed)
if ($access->getHisUser() === $this) {
$access->setHisUser(null);
}
}
return $this;
}
/**
* A visual identifier that represents this user
*
* #see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->mail;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
}
And here is my route:
#[Route('/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, UserAuthenticatorInterface $userAuthenticator, UserAuthenticator $authenticator, EntityManagerInterface $entityManager): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
return $userAuthenticator->authenticateUser(
$user,
$authenticator,
$request
);
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
Sorry the code is not properly formated I copy past it and it came that way.
I'm new on Symfony 6 and i've got some questions about this framework.
Recently i got this error but i don't understand why. I created all databases from the command line.
My error is : Case mismatch between loaded and declared class names: "App\Entity\tag" vs "App\Entity\Tag".
In my database all tables are written with lowercase syntaxe.
everything worked between I insert relation with all table.
i tried to insert this code in my entity to use the correct syntaxe but it doesn't work.
Entity\Tag.php
#[ORM\Table(name: 'tag')]
Some people speak about this parameter inside my database (MYSQL) but i don't know if this got an impact :
lower_case_table_names = (0 1 2)
Do you have an idea ?
This is my entity tag
<?php
namespace App\Entity;
use App\Repository\TagRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: TagRepository::class)]
class Tag
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $nomtag = null;
#[ORM\ManyToOne(inversedBy: 'idcatetag')]
#[ORM\JoinColumn(nullable: false)]
private ?catetag $idcatetag = null;
#[ORM\ManyToMany(targetEntity: Mission::class, mappedBy: 'idtagmissionassign')]
private Collection $missions;
#[ORM\ManyToMany(targetEntity: Service::class, mappedBy: 'idtagserviceassign')]
private Collection $services;
public function __construct()
{
$this->missions = new ArrayCollection();
$this->services = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNomtag(): ?string
{
return $this->nomtag;
}
public function setNomtag(string $nomtag): self
{
$this->nomtag = $nomtag;
return $this;
}
public function getIdcatetag(): ?catetag
{
return $this->idcatetag;
}
public function setIdcatetag(?catetag $idcatetag): self
{
$this->idcatetag = $idcatetag;
return $this;
}
/**
* #return Collection<int, Mission>
*/
public function getMissions(): Collection
{
return $this->missions;
}
public function addMission(Mission $mission): self
{
if (!$this->missions->contains($mission)) {
$this->missions->add($mission);
$mission->addIdtagmissionassign($this);
}
return $this;
}
public function removeMission(Mission $mission): self
{
if ($this->missions->removeElement($mission)) {
$mission->removeIdtagmissionassign($this);
}
return $this;
}
/**
* #return Collection<int, Service>
*/
public function getServices(): Collection
{
return $this->services;
}
public function addService(Service $service): self
{
if (!$this->services->contains($service)) {
$this->services->add($service);
$service->addIdtagserviceassign($this);
}
return $this;
}
public function removeService(Service $service): self
{
if ($this->services->removeElement($service)) {
$service->removeIdtagserviceassign($this);
}
return $this;
}
}
This is my repo file :
<?php
namespace App\Repository;
use App\Entity\Tag;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* #extends ServiceEntityRepository<Tag>
*
* #method Tag|null find($id, $lockMode = null, $lockVersion = null)
* #method Tag|null findOneBy(array $criteria, array $orderBy = null)
* #method Tag[] findAll()
* #method Tag[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class TagRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Tag::class);
}
public function save(Tag $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Tag $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
// /**
// * #return Tag[] Returns an array of Tag objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('t')
// ->andWhere('t.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('t.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Tag
// {
// return $this->createQueryBuilder('t')
// ->andWhere('t.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
check file name , it should be Tag.php with T uppercase, symfony create table automatically in lowercase. If everything is ok try to delete you're file and rewrite it properly with make:entity or php bin/console doctrine:schema:update --force after entity's modification
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,
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.