After looking over the internet and here I didn' find something useful for me.
I'm currently creating a CRUD. Every 'Entreprise' having one or multiple 'Site' and I'm currently doing the CRUD for Site. I've made it by doing the make:form command.
Whhen I'm going to create a site the following error appear :
Catchable Fatal Error: Object of class App\Entity\Entreprise could not
be converted to string
I've tried to add the function __toString() as i saw. But maybe i didn't add it crrectly it changes nothing so I removed it.
My controller to create a site looks like this :
/**
* #Route("admin/sites/new", name="admin.sites.new")
* #param Request $request
* #return RedirectResponse|Response
*/
public function new (Request $request)
{
$site = new Site();
$form = $this->createForm(SiteType::class, $site);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$this->em->persist($site);
$this->em->flush();
$this->addFlash('success', 'Site crée avec succès');
return $this->redirectToRoute('admin.sites.index');
}
return $this->render('admin/sites/create.html.twig', [
'site' => $site,
'form' => $form->createView()
]);
}
}
My SiteType generate by the make:form commande :
/**
* #Route("admin/sites/new", name="admin.sites.new")
* #param Request $request
* #return RedirectResponse|Response
*/
public function new (Request $request)
{
$site = new Site();
$form = $this->createForm(SiteType::class, $site);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$this->em->persist($site);
$this->em->flush();
$this->addFlash('success', 'Site crée avec succès');
return $this->redirectToRoute('admin.sites.index');
}
return $this->render('admin/sites/create.html.twig', [
'site' => $site,
'form' => $form->createView()
]);
}
}
So here are my ENTITY
Entreprise
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\EntrepriseRepository")
*/
class Entreprise
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_nom;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_siret;
/**
* #ORM\Column(type="string", length=10)
*/
private $entreprise_telephone;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_salesforce_number;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_compte_client;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_raison_sociale;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_APE;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $entreprise_image_link;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Site", mappedBy="entreprise_id")
*/
private $entreprise_id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Catalogue", mappedBy="entreprise_id")
*/
private $entreprise_catalogue_id;
public function __construct()
{
$this->entreprise_id = new ArrayCollection();
$this->entreprise_catalogue_id = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEntrepriseNom(): ?string
{
return $this->entreprise_nom;
}
public function setEntrepriseNom(string $entreprise_nom): self
{
$this->entreprise_nom = $entreprise_nom;
return $this;
}
public function getEntrepriseSiret(): ?string
{
return $this->entreprise_siret;
}
public function setEntrepriseSiret(string $entreprise_siret): self
{
$this->entreprise_siret = $entreprise_siret;
return $this;
}
public function getEntrepriseTelephone(): ?int
{
return $this->entreprise_telephone;
}
public function setEntrepriseTelephone(int $entreprise_telephone): self
{
$this->entreprise_telephone = $entreprise_telephone;
return $this;
}
public function getEntrepriseSalesforceNumber(): ?string
{
return $this->entreprise_salesforce_number;
}
public function setEntrepriseSalesforceNumber(string $entreprise_salesforce_number): self
{
$this->entreprise_salesforce_number = $entreprise_salesforce_number;
return $this;
}
public function getEntrepriseCompteClient(): ?string
{
return $this->entreprise_compte_client;
}
public function setEntrepriseCompteClient(string $entreprise_compte_client): self
{
$this->entreprise_compte_client = $entreprise_compte_client;
return $this;
}
public function getEntrepriseRaisonSociale(): ?string
{
return $this->entreprise_raison_sociale;
}
public function setEntrepriseRaisonSociale(string $entreprise_raison_sociale): self
{
$this->entreprise_raison_sociale = $entreprise_raison_sociale;
return $this;
}
public function getEntrepriseAPE(): ?string
{
return $this->entreprise_APE;
}
public function setEntrepriseAPE(string $entreprise_APE): self
{
$this->entreprise_APE = $entreprise_APE;
return $this;
}
public function getEntrepriseImageLink(): ?string
{
return $this->entreprise_image_link;
}
public function setEntrepriseImageLink(?string $entreprise_image_link): self
{
$this->entreprise_image_link = $entreprise_image_link;
return $this;
}
/**
* #return Collection|Site[]
*/
public function getEntrepriseId(): Collection
{
return $this->entreprise_id;
}
public function addEntrepriseId(Site $entrepriseId): self
{
if (!$this->entreprise_id->contains($entrepriseId)) {
$this->entreprise_id[] = $entrepriseId;
$entrepriseId->setEntrepriseId($this);
}
return $this;
}
public function removeEntrepriseId(Site $entrepriseId): self
{
if ($this->entreprise_id->contains($entrepriseId)) {
$this->entreprise_id->removeElement($entrepriseId);
// set the owning side to null (unless already changed)
if ($entrepriseId->getEntrepriseId() === $this) {
$entrepriseId->setEntrepriseId(null);
}
}
return $this;
}
}
And here is
Site
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\SiteRepository")
*/
class Site
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_nom;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_raison_sociale;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_APE;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Client", mappedBy="site_id")
*/
private $site_id;
/**
* #ORM\OneToOne(targetEntity="App\Entity\Adresse", cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $adresse_id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="entreprise_id")
* #ORM\JoinColumn(nullable=false)
*/
private $entreprise_id;
public function __construct()
{
$this->site_id = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getSiteNom(): ?string
{
return $this->site_nom;
}
public function setSiteNom(string $site_nom): self
{
$this->site_nom = $site_nom;
return $this;
}
public function getSiteRaisonSociale(): ?string
{
return $this->site_raison_sociale;
}
public function setSiteRaisonSociale(string $site_raison_sociale): self
{
$this->site_raison_sociale = $site_raison_sociale;
return $this;
}
public function getSiteAPE(): ?string
{
return $this->site_APE;
}
public function setSiteAPE(string $site_APE): self
{
$this->site_APE = $site_APE;
return $this;
}
/**
* #return Collection|Client[]
*/
public function getSiteId(): Collection
{
return $this->site_id;
}
public function addSiteId(Client $siteId): self
{
if (!$this->site_id->contains($siteId)) {
$this->site_id[] = $siteId;
$siteId->addSiteId($this);
}
return $this;
}
public function removeSiteId(Client $siteId): self
{
if ($this->site_id->contains($siteId)) {
$this->site_id->removeElement($siteId);
$siteId->removeSiteId($this);
}
return $this;
}
public function getAdresseId(): ?Adresse
{
return $this->adresse_id;
}
public function setAdresseId(Adresse $adresse_id): self
{
$this->adresse_id = $adresse_id;
return $this;
}
public function getEntrepriseId(): ?Entreprise
{
return $this->entreprise_id;
}
public function setEntrepriseId(?Entreprise $entreprise_id): self
{
$this->entreprise_id = $entreprise_id;
return $this;
}
public function __toString()
{
return $this->getSiteNom();
}
}
I didn't know what's wrong. Maybe the __toString I didn't write correclty !
I've wrote :
public function __toString()
{
return $this->getSiteNom();
}
}
Catchable Fatal Error: Object of class App\Entity\Entreprise
You need to implement the __toString() method in the Entreprise entity
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\EntrepriseRepository")
*/
class Entreprise
{
//...
public function __toString()
{
return $this->entreprise_nom;
}
// ...
}
Related
I'm having trouble with DQL queries on a project I'm working on. What the DQL is supposed to do is find in the DB all the datas that are related to a productLine variable; that a user would type and search for into a form.
My issue is when I run a test with a product Line; I get an "Error 500" thrown; and I know the error origins from the Repository file; since the controller works fine (I've added some var_dumps in the controller after the query's line to check and I'm not reaching it when testing with the faulty function, whereas with another working function I can reach it).
I know that the data typed in by the user is collected (the product Line entered by the user), there seems to be an issue with DQL processing the query that I can't seem to find an answer for anywhere.
Without further ado; here's the code.
Working fine query
public function findByLotNumber($lotNumber){
return $this->createQueryBuilder('u')
->distinct()
->where('u.lotNumber LIKE :lotNumberS')
->setParameter('lotNumberS', $lotNumber . '%')
->getQuery()
->getResult();
}
faulty query
public function findByCriteriaIdentification($criteriaIdentification){
$givenLotNumber = $_POST['lotNumber'];
if(empty($_POST['lotNumber'])){
$givenLotNumber = '%';
}
$givenProductLine = $_POST['productLine'];
if(empty($_POST['productLine'])){
$givenProductLine = '%';
}
$varTest = $this->createQueryBuilder('u')
->distinct()
->where('u.lotNumber LIKE :lotNumberS')
->orWhere('u.productLine LIKE :productLineS')
->setParameter('lotNumberS', $givenLotNumber)
->setParameter('productLineS', $givenProductLine);
$queryTest = $varTest->getQuery();
return $queryTest->execute();
}
Does anyone have an insight regarding what I'm coding wrong ?
PS: this being a corporate project I don't have the possibility of upgrading to Symfo 6 or Doctrine3 at the moment.
EDIT: Here's the class of the entity i'm querying:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\WafRepository")
*/
class Waf extends Sil
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
* #ORM\OneToOne(targetEntity="App\Entity\Sil")
*/
private $id;
/**
* #ORM\Column(type="integer")
*/
private $rankId;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $size;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $thickness;
/*public function getId(): ?int
{
return $this->id;
}*/
public function getRankId(): ?int
{
return $this->rankId;
}
public function setRankId(int $rankId): self
{
$this->rankId = $rankId;
return $this;
}
public function getSize(): ?int
{
return $this->size;
}
public function setSize(int $size): self
{
$this->size = $size;
return $this;
}
public function getThickness(): ?int
{
return $this->thickness;
}
public function setThickness(?int $thickness): self
{
$this->thickness = $thickness;
return $this;
}
}
In case its useful, I'm adding as well the class "sili" that waf is an extent from:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\SiliconRepository")
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="silType", type="string")
*/
class Sil
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=20)
*/
private $lotNumber;
/**
* #ORM\Column(type="string", length=80, nullable=true)
*/
private $productLine;
/**
* #ORM\Column(type="string", length=20, nullable=true)
*/
private $productCode;
/**
* #ORM\Column(type="string", length=20, nullable=true)
*/
private $productLineCode;
/**
* #ORM\Column(type="string", length=20, nullable=true)
*/
private $sourceLot;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $division;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
//private $comment;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $testStatus;
/**
* #ORM\Column(type="integer", nullable=true)
*/
//private $lastUpdate;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $maturity;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Operations", mappedBy="silicon")
*/
private $operations;
/**
* #ORM\OneToMany(targetEntity="App\Entity\State", mappedBy="silicon")
*/
private $states;
/**
* #ORM\Column(type="string", length=20, nullable=true)
*/
private $fatherLotNumber;
public function __construct()
{
$this->operations = new ArrayCollection();
$this->states = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getLotNumber(): ?string
{
return $this->lotNumber;
}
public function setLotNumber(string $lotNumber): self
{
$this->lotNumber = $lotNumber;
return $this;
}
public function getProductLine(): ?string
{
return $this->productLine;
}
public function setProductLine(?string $productLine): self
{
$this->productLine = $productLine;
return $this;
}
public function getProductCode(): ?string
{
return $this->productCode;
}
public function setProductCode(?string $productCode): self
{
$this->productCode = $productCode;
return $this;
}
public function getProductLineCode(): ?string
{
return $this->productLineCode;
}
public function setProductLineCode(?string $productLineCode): self
{
$this->productLineCode = $productLineCode;
return $this;
}
public function getSourceLot(): ?string
{
return $this->sourceLot;
}
public function setSourceLot(?string $sourceLot): self
{
$this->sourceLot = $sourceLot;
return $this;
}
public function getDivision(): ?int
{
return $this->division;
}
public function setDivision(?int $division): self
{
$this->division = $division;
return $this;
}
/*public function getComment(): ?string
{
return $this->comment;
}
public function setComment(?string $comment): self
{
$this->comment = $comment;
return $this;
}*/
public function getTestStatus(): ?string
{
return $this->testStatus;
}
public function setTestStatus(?string $testStatus): self
{
$this->testStatus = $testStatus;
return $this;
}
/*public function getLastUpdate(): ?int
{
return $this->lastUpdate;
}
public function setLastUpdate(int $lastUpdate): self
{
$this->lastUpdate = $lastUpdate;
return $this;
}*/
public function getMaturity(): ?int
{
return $this->maturity;
}
public function setMaturity(?int $maturity): self
{
$this->maturity = $maturity;
return $this;
}
/**
* #return Collection|Operations[]
*/
public function getOperations(): Collection
{
return $this->operations;
}
public function addOperation(Operations $operation): self
{
while (!($this)->operations->contains($operation)) {
$this->operations[] = $operation;
$operation->setSilicon($this);
}
return $this;
}
public function removeOperation(Operations $operation): self
{
if ($this->operations->contains($operation)) {
$this->operations->removeElement($operation);
//$this->reformatTab($this->operations);
// set the owning side to null (unless already changed)
if ($operation->getSilicon() === $this) {
$operation->setSilicon(null);
}
}
return $this;
}
/**
* #return Collection|State[]
*/
public function getStates(): Collection
{
return $this->states;
}
public function addState(State $state): self
{
if (!$this->states->contains($state)) {
$this->states[] = $state;
$state->setSilicon($this);
}
return $this;
}
public function removeState(State $state): self
{
if ($this->states->contains($state)) {
$this->states->removeElement($state);
// set the owning side to null (unless already changed)
if ($state->getSilicon() === $this) {
$state->setSilicon(null);
}
}
return $this;
}
public function getFatherLotNumber(): ?string
{
return $this->fatherLotNumber;
}
public function setFatherLotNumber(?string $fatherLotNumber): self
{
$this->fatherLotNumber = $fatherLotNumber;
return $this;
}
}
Thanks in advance !
beginner here i'm trying to do an API with Api-platform and Symfony. Actually i want to create my database schema and start testing it but when using php bin/console doctrine:schema:validate, i got this error and i cant figure out how to fix it : The table with name 'mydb.appartment_user' already exists
Unfortunately i didnt found an answer on google to my problem :'(
Here is my appartement entity :
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\AppartmentRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ApiResource()
* #ORM\Entity(repositoryClass=AppartmentRepository::class)
*/
class Appartment
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $adress;
/**
* #ORM\Column(type="string", length=255)
*/
private $latitude;
/**
* #ORM\Column(type="string", length=255)
*/
private $longitude;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="occupied_appartments")
*/
private $current_tenant;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="rented_appartments")
*/
private $landlord;
/**
* #ORM\OneToOne(targetEntity=Lock::class, cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $lock_id;
public function __construct()
{
$this->current_tenant = new ArrayCollection();
$this->landlord = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getAdress(): ?string
{
return $this->adress;
}
public function setAdress(string $adress): self
{
$this->adress = $adress;
return $this;
}
public function getLatitude(): ?string
{
return $this->latitude;
}
public function setLatitude(string $latitude): self
{
$this->latitude = $latitude;
return $this;
}
public function getLongitude(): ?string
{
return $this->longitude;
}
public function setLongitude(string $longitude): self
{
$this->longitude = $longitude;
return $this;
}
/**
* #return Collection|User[]
*/
public function getCurrentTenant(): Collection
{
return $this->current_tenant;
}
public function addCurrentTenant(User $currentTenant): self
{
if (!$this->current_tenant->contains($currentTenant)) {
$this->current_tenant[] = $currentTenant;
}
return $this;
}
public function removeCurrentTenant(User $currentTenant): self
{
$this->current_tenant->removeElement($currentTenant);
return $this;
}
/**
* #return Collection|User[]
*/
public function getLandlord(): Collection
{
return $this->landlord;
}
public function addLandlord(User $landlord): self
{
if (!$this->landlord->contains($landlord)) {
$this->landlord[] = $landlord;
}
return $this;
}
public function removeLandlord(User $landlord): self
{
$this->landlord->removeElement($landlord);
return $this;
}
public function getLockId(): ?Lock
{
return $this->lock_id;
}
public function setLockId(Lock $lock_id): self
{
$this->lock_id = $lock_id;
return $this;
}
}
and my user entity :
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\Table(name="`user`")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
/**
* #ORM\Column(type="string", length=255)
*/
private $firstname;
/**
* #ORM\Column(type="string", length=255)
*/
private $lastname;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $profile_picture;
/**
* #ORM\ManyToMany(targetEntity=Appartment::class, mappedBy="current_tenant")
*/
private $occupied_appartments;
/**
* #ORM\ManyToMany(targetEntity=Appartment::class, mappedBy="landlord")
*/
private $rented_appartments;
/**
* #ORM\ManyToMany(targetEntity=Rental::class, mappedBy="tenant_id")
*/
private $tenant_rentals;
/**
* #ORM\ManyToMany(targetEntity=Rental::class, mappedBy="landlord_id")
*/
private $landlord_rentals;
public function __construct()
{
$this->occupied_appartments = new ArrayCollection();
$this->rented_appartments = new ArrayCollection();
$this->tenant_rentals = new ArrayCollection();
$this->landlord_rentals = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
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 getProfilePicture(): ?string
{
return $this->profile_picture;
}
public function setProfilePicture(?string $profile_picture): self
{
$this->profile_picture = $profile_picture;
return $this;
}
/**
* #return Collection|Appartment[]
*/
public function getOccupiedAppartments(): Collection
{
return $this->occupied_appartments;
}
public function addOccupiedAppartment(Appartment $occupied_appartments): self
{
if (!$this->occupied_appartments->contains($occupied_appartments)) {
$this->occupied_appartments[] = $occupied_appartments;
$occupied_appartments->addCurrentTenant($this);
}
return $this;
}
public function removeOccupiedAppartment(Appartment $occupied_appartments): self
{
if ($this->occupied_appartments->removeElement($occupied_appartments)) {
$occupied_appartments->removeCurrentTenant($this);
}
return $this;
}
/**
* #return Collection|Appartment[]
*/
public function getRentedAppartments(): Collection
{
return $this->rented_appartments;
}
public function addRentedAppartment(Appartment $rentedAppartment): self
{
if (!$this->rented_appartments->contains($rentedAppartment)) {
$this->rented_appartments[] = $rentedAppartment;
$rentedAppartment->addLandlord($this);
}
return $this;
}
public function removeRentedAppartment(Appartment $rentedAppartment): self
{
if ($this->rented_appartments->removeElement($rentedAppartment)) {
$rentedAppartment->removeLandlord($this);
}
return $this;
}
/**
* #return Collection|Rental[]
*/
public function getTenantRentals(): Collection
{
return $this->tenant_rentals;
}
public function addTenantRental(Rental $tenantRental): self
{
if (!$this->tenant_rentals->contains($tenantRental)) {
$this->tenant_rentals[] = $tenantRental;
$tenantRental->addTenantId($this);
}
return $this;
}
public function removeTenantRental(Rental $tenantRental): self
{
if ($this->tenant_rentals->removeElement($tenantRental)) {
$tenantRental->removeTenantId($this);
}
return $this;
}
/**
* #return Collection|Rental[]
*/
public function getLandlordRentals(): Collection
{
return $this->landlord_rentals;
}
public function addLandlordRental(Rental $landlordRental): self
{
if (!$this->landlord_rentals->contains($landlordRental)) {
$this->landlord_rentals[] = $landlordRental;
$landlordRental->addLandlordId($this);
}
return $this;
}
public function removeLandlordRental(Rental $landlordRental): self
{
if ($this->landlord_rentals->removeElement($landlordRental)) {
$landlordRental->removeLandlordId($this);
}
return $this;
}
}
I tried to clear-cache and to force but it didnt work.
Thank's in advance for help and ask me if I forget any details !
add a JoinTable annotation for properties which have ManyToMany relation in Appartment entity
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="occupied_appartments")
* #ORM\JoinTable(name="appartment_current_tenant")
*/
private $current_tenant;
/**
* #ORM\ManyToMany(targetEntity=User::class, inversedBy="rented_appartments")
* #ORM\JoinTable(name="appartment_landlord")
*/
private $landlord;
I have a user entity that has a many-to-many relationship with another entity Roles.
I have a form that allows me to create a new user and for that, I use an EntityType for the manyToMany relationship 'roles'.
Here is my form
$builder
->add('username',null,['label' => 'Email'])
->add('password',null,['label'=>'Password'])
->add('roles',EntityType::class, [
'multiple' => true,
'class' => Role::class,
'choice_label' => 'role_name',
]
)
;
Everything works fine but when I submit the form I got this error:
Expected argument of type "App\Entity\Role", "string" given at
property path "roles".
EDIT:
here is my User entity :
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $username;
/**
* #ORM\Column(type="string", length=255)
*/
private $password;
/**
* #ORM\ManyToMany(targetEntity=Role::class, inversedBy="users")
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
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 getRoles()
{
return ['ROLE_ADMIN'];
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function addRole(Role $role): self
{
if (!$this->roles->contains($role)) {
$this->roles[] = $role;
$role->addUser($this);
}
return $this;
}
public function removeRole(Role $role): self
{
if ($this->roles->contains($role)) {
$this->roles->removeElement($role);
$role->removeUser($this);
}
return $this;
}
}
Here is my Role entity :
<?php
namespace App\Entity;
use App\Repository\RoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=RoleRepository::class)
*/
class Role
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $role_name;
/**
* #ORM\ManyToMany(targetEntity=User::class, mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRoleName(): ?string
{
return $this->role_name;
}
public function setRoleName(string $role_name): self
{
$this->role_name = $role_name;
return $this;
}
/**
* #return Collection|User[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->contains($user)) {
$this->users->removeElement($user);
}
return $this;
}
}
I guess the problem is here
public function getRoles()
{
return ['ROLE_ADMIN'];
}
you should return an array or Role entity not string, it should be something like this
public function getRoles()
{
return $this->roles;
}
what if i'm using ArrayCollection in User entity?
/**
* #var Collection|Role[]
* #ORM\ManyToMany(targetEntity="App\Entity\Role")
* #ORM\JoinTable(
* name="user_roles",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getRoles()
{
return $this->roles;
}
Hello I have several problems with the easyadmin multiple image uploads. Please help. Strangely I was having problems mostly with cakes and cakephotos. In easyadmin I add several images in Cakes, they get converted to array and stored in the db. After they get outputed when showed. Atleast that what I was planning to do...
Here is the Cakes.php entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Vich\UploaderBundle\Entity\File as EmbeddedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity(repositoryClass="App\Repository\CakesRepository")
* #Vich\Uploadable
*/
class Cakes
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $CakeName;
/**
* #ORM\Column(type="integer")
*/
private $CakePrice;
/**
* #ORM\Column(type="string", length=255)
*/
private $Description;
/**
* #ORM\Column(type="json")
*/
private $CakeCategory = [];
/**
* #ORM\ManyToMany(targetEntity="Location", mappedBy="Cakes", cascade={"persist"})
*/
private $AvailableLocation = [];
/**
* #ORM\OneToMany(targetEntity="CakePhotos", mappedBy="Cake", cascade={"persist"})
*/
private $CakePhotos;
public function __construct()
{
$this->AvailableLocation = new ArrayCollection();
$this->CakePhotos = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getCakeName(): ?string
{
return $this->CakeName;
}
public function setCakeName(string $CakeName): self
{
$this->CakeName = $CakeName;
return $this;
}
public function getCakePrice(): ?int
{
return $this->CakePrice;
}
public function setCakePrice(int $CakePrice): self
{
$this->CakePrice = $CakePrice;
return $this;
}
public function getDescription(): ?string
{
return $this->Description;
}
public function setDescription(string $Description): self
{
$this->Description = $Description;
return $this;
}
public function getCakeCategory(): ?array
{
return $this->CakeCategory;
}
public function setCakeCategory(array $CakeCategory): self
{
$this->CakeCategory = $CakeCategory;
return $this;
}
/**
* #return Collection|Location[]
*/
public function getAvailableLocation(): Collection
{
return $this->AvailableLocation;
}
public function addAvailableLocation(Location $location): self
{
if (!$this->AvailableLocation->contains($location)) {
$this->AvailableLocation[] = $location;
$location->addCake($this);
}
return $this;
}
public function removeAvailableLocation(Location $location): self
{
if ($this->AvailableLocation->contains($location)) {
$this->AvailableLocation->removeElement($location);
$location->removeCake($this);
}
return $this;
}
/**
* #return Collection|CakePhoto[]
*/
public function getCakePhotos(): Collection
{
return $this->CakePhotos;
}
public function addCakePhoto(CakePhotos $CakePhotos): self
{
if (!$this->CakePhotos->contains($CakePhotos)) {
$this->CakePhoto[] = $CakePhotos;
$CakePhotos->setCake($this);
}
return $this;
}
public function removeCakePhoto(CakePhotos $CakePhotos): self
{
if ($this->CakePhotos->contains($CakePhotos)) {
$this->CakePhotos->removeElement($CakePhotos);
}
return $this;
}
public function getImageURL(): ?string
{
return $this->ImageURL;
}
public function setImageURL(string $ImageURL): self
{
$this->ImageURL = $ImageURL;
return $this;
}
}
Here is the CakePhotos.php entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity(repositoryClass="App\Repository\CakePhotosRepository")
* #Vich\Uploadable
*/
class CakePhotos
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $Image;
/**
* #Vich\UploadableField(mapping="cakephotos", fileNameProperty="Image")
*/
private $ImageFile;
/**
* #ORM\ManyToOne(targetEntity="Cakes", inversedBy="CakePhotos")
*/
private $Cake;
public function getId(): ?int
{
return $this->id;
}
public function getImage(): ?string
{
return $this->Image;
}
public function setImage(?string $Image)
{
$this->Image = $Image;
return $this;
}
public function getCake(): ?Cakes
{
return $this->Cake;
}
public function setCake(?Cake $cake): self
{
$this->Cake = $cake;
return $this;
}
public function __toString()
{
return $this->Image;
}
/**
* #return mixed
*/
public function getImageFile()
{
return $this->ImageFile;
}
/**
* #param mixed $imageFile
* #throws \Exception
*/
public function setImageFile(?File $ImageFile): void
{
$this->ImageFile = $ImageFile;
}
}
Here is my Form for converting
<?php
namespace App\Form;
use App\Entity\CakePhotos;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichFileType;
class ImageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ImageFile', VichFileType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => CakePhotos::class,
]);
}
}
All around the code I have different problems such as:
Argument 1 passed to App\Entity\CakePhotos::setCake() must be an instance of App\Entity\Cake or null, instance of App\Entity\Cakes given, called in /home/kumaskano1/Desktop/Learning/Symfony/Shirin/src/Entity/Cakes.php
you can solve your problem by doing this
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ImageFile', VichFileType::class,array('data_class' =>null))
;
}
I try to make a form for an entity called Product with an embedded form from an entity Barcode. When I try to go to the form to add one product, I have the message "Return value of App\Entity\Product::getBarcodes() must implement interface Doctrine\Common\Collections\Collection, null returned".
I say in __construct to initialize the barcodes to implement the Collection but still the same..
My Barcode Entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\BarcodeRepository")
*/
class Barcode
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $code;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Product", inversedBy="barcodes")
* #ORM\JoinColumn(nullable=false)
*/
private $product;
public function __construct(Product $product = null)
{
$this->product = $product;
}
public function getId(): ?int
{
return $this->id;
}
public function getCode(): ?string
{
return $this->code;
}
public function setCode(string $code): self
{
$this->code = $code;
return $this;
}
public function getProduct(): ?Product
{
return $this->product;
}
public function setProduct(?Product $product): self
{
$this->product = $product;
return $this;
}
}
My Product Entity :
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity()
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="type", type="string")
* #UniqueEntity("slug")
*/
class Product
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*/
protected $name;
/**
* #ORM\Column(type="string", length=255)
* #Assert\Regex(pattern="/\.(svg|png)$/")
*/
protected $picture;
/**
* #ORM\Column(type="boolean")
*/
protected $is_activated;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $comments;
/**
* #ORM\Column(type="datetime")
*/
protected $created_at;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Barcode", mappedBy="product", orphanRemoval=true, cascade={"all"})
*/
protected $barcodes;
public function __construct()
{
$this->allergens = new ArrayCollection();
$this->barcodes = 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 getPicture(): ?string
{
return $this->picture;
}
public function setPicture(string $picture): self
{
$this->picture = $picture;
return $this;
}
public function getIsActivated(): ?bool
{
return $this->is_activated;
}
public function setIsActivated(bool $is_activated): self
{
$this->is_activated = $is_activated;
return $this;
}
public function getComments(): ?string
{
return $this->comments;
}
public function setComments(?string $comments): self
{
$this->comments = $comments;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
/**
* #return Collection|Barcode[]
*/
public function getBarcodes(): Collection
{
return $this->barcodes;
}
public function addBarcode(Barcode $barcode): self
{
if (!$this->barcodes->contains($barcode)) {
$this->barcodes[] = $barcode;
$barcode->setProduct($this);
}
return $this;
}
public function removeBarcode(Barcode $barcode): self
{
if ($this->barcodes->contains($barcode)) {
$this->barcodes->removeElement($barcode);
// set the owning side to null (unless already changed)
if ($barcode->getProduct() === $this) {
$barcode->setProduct(null);
}
}
return $this;
}
}
and my ProductType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('slug')
->add('picture')
->add('barcodes', CollectionType::class, [
'entry_type' => BarcodeType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false
])
->add('is_activated')
->add('comments')
;
}
In your Product entity, allow the possibility of a null return type by changing Collection to ?Collection:
/**
* #return Collection|Barcode[]|null
*/
public function getBarcodes(): ?Collection
{
return $this->barcodes;
}