I have a problem about the flush on 2 linked entities (ManyToOne, OneToMany).
I'm on Symfony 5.1.
I just want to persist one "UserSavedCard" with many "UserCartSavedProducts" entities.
But I have an error when I flushed my entities and this error come to this file "in vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php (line 3013)"
My function that throw the error :
/**
* Save current user cart in database for later
* #param string|null $title
*/
public function saveCart(?string $title)
{
$cart = $this->getCart();
$cartSaved = new UserCartSaved();
$cartSaved->setUser($this->security->getUser());
$this->em->persist($cartSaved);
foreach ($cart as $item) {
$savedProduct = new UserCartSavedProducts();
$savedProduct->setProduct($item['product']);
$savedProduct->setUserCartSaved($cartSaved);
$this->em->persist($savedProduct);
}
$this->em->flush();
}
When I execute this code above But I have this error :
Notice: Undefined index: 000000007e86ae93000000003f3a2fbb
There is my entites :
UserCartSaved:
<?php
namespace App\Entity;
use App\Repository\UserCartSavedRepository;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\Date;
/**
* #ORM\Entity(repositoryClass=UserCartSavedRepository::class)
*/
class UserCartSaved
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="userCartSaveds")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #ORM\OneToMany(targetEntity=UserCartSavedProducts::class, mappedBy="userCartSaved")
*/
private $userCartSavedProducts;
/**
* #ORM\Column(type="datetime")
*/
private $createdAt;
public function __construct()
{
$this->userCartSavedProducts = new ArrayCollection();
$this->createdAt = new DateTime();
}
public function getId(): ?int
{
return $this->id;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
/**
* #return Collection|UserCartSavedProducts[]
*/
public function getUserCartSavedProducts(): Collection
{
return $this->userCartSavedProducts;
}
public function addUserCartSavedProduct(UserCartSavedProducts $userCartSavedProduct): self
{
if (!$this->userCartSavedProducts->contains($userCartSavedProduct)) {
$this->userCartSavedProducts[] = $userCartSavedProduct;
$userCartSavedProduct->setUserCartSaved($this);
}
return $this;
}
public function removeUserCartSavedProduct(UserCartSavedProducts $userCartSavedProduct): self
{
if ($this->userCartSavedProducts->contains($userCartSavedProduct)) {
$this->userCartSavedProducts->removeElement($userCartSavedProduct);
// set the owning side to null (unless already changed)
if ($userCartSavedProduct->getUserCartSaved() === $this) {
$userCartSavedProduct->setUserCartSaved(null);
}
}
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
}
UserCartSavedProducts :
<?php
namespace App\Entity;
use App\Repository\UserCartSavedProductsRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserCartSavedProductsRepository::class)
*/
class UserCartSavedProducts
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=UserCartSaved::class, inversedBy="userCartSavedProducts")
* #ORM\JoinColumn(nullable=false)
*/
private $userCartSaved;
/**
* #ORM\ManyToOne(targetEntity=Product::class, inversedBy="userCartSavedProducts", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $product;
public function getId(): ?int
{
return $this->id;
}
public function getUserCartSaved(): ?UserCartSaved
{
return $this->userCartSaved;
}
public function setUserCartSaved(?UserCartSaved $userCartSaved): self
{
$this->userCartSaved = $userCartSaved;
return $this;
}
public function getProduct(): ?Product
{
return $this->product;
}
public function setProduct(?Product $product): self
{
$this->product = $product;
return $this;
}
}
Product
<?php
namespace App\Entity;
use App\Repository\ProductRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=ProductRepository::class)
*/
class Product
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity=UserCartSavedProducts::class, mappedBy="product")
*/
private $userCartSavedProducts;
public function __construct()
{
$this->userCartSavedProducts = new ArrayCollection();
}
/**
* #return Collection|UserCartSavedProducts[]
*/
public function getUserCartSavedProducts(): Collection
{
return $this->userCartSavedProducts;
}
public function addUserCartSavedProduct(UserCartSavedProducts $userCartSavedProduct): self
{
if (!$this->userCartSavedProducts->contains($userCartSavedProduct)) {
$this->userCartSavedProducts[] = $userCartSavedProduct;
$userCartSavedProduct->setProduct($this);
}
return $this;
}
public function removeUserCartSavedProduct(UserCartSavedProducts $userCartSavedProduct): self
{
if ($this->userCartSavedProducts->contains($userCartSavedProduct)) {
$this->userCartSavedProducts->removeElement($userCartSavedProduct);
// set the owning side to null (unless already changed)
if ($userCartSavedProduct->getProduct() === $this) {
$userCartSavedProduct->setProduct(null);
}
}
return $this;
}
}
I've run into an issue getting the same error, and in my case is that I was storing the entity object into a session and trying to flush it "as is" after retrieval. Regardless I could retrieve and dump the object and everything seemed fine (until flush), I was told that the EM lost management of the contents. So, to get management back, I had to retrieve every single id of every component of the stored object via its own getter, and then via find, retrieve them all and set them again into a new entity instance.
Related
I have a little problem with Doctrine and Symfony 5.4. I've searched on StackOverflow and on the doc, but every solution seems that is not correctly for me.
I have 3 class: Lang, State, OrderState. Last one is join with Lang and State through id_state and id_lang with a ManyToMany association relation ship.
When i execute the schema validate, i get the classic error. Honestly i don't understand why.
Mapping
-------
[FAIL] The entity-class App\Entity\OrderState mapping is invalid:
* The referenced column name 'id_state' has to be a primary key column on the target entity class 'App\Entity\OrderState'.
* The referenced column name 'id' has to be a primary key column on the target entity class 'App\Entity\Lang'.
Database
--------
In MissingColumnException.php line 15:
Column name "id_state" referenced for relation from App\Entity\OrderState towa
rds App\Entity\State does not exist.
State.php
<?php
namespace App\Entity;
use App\Repository\StateRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=StateRepository::class)
*/
class State
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id_state;
/**
* #ORM\Column(type="string", length=255)
*/
private $label;
public function getIdState(): ?int
{
return $this->id_state;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
}
Lang.php
<?php
namespace App\Entity;
use App\Repository\LangRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=LangRepository::class)
*/
class Lang
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id_lang;
/**
* #ORM\Column(type="string", length=255)
*/
private $lang;
public function getIdLang(): ?int
{
return $this->id_lang;
}
public function setIdLang(int $id_lang): self
{
$this->id_lang = $id_lang;
return $this;
}
public function getLang(): ?string
{
return $this->lang;
}
public function setLang(string $lang): self
{
$this->lang = $lang;
return $this;
}
}
and OrderState.php
<?php
namespace App\Entity;
use App\Repository\OrderStateRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=OrderStateRepository::class)
*/
class OrderState
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToMany(targetEntity=State::class)
* #ORM\JoinColumn(name="id_state", referencedColumnName="id_state")
*/
private $id_state;
/**
* #ORM\ManyToMany(targetEntity=Lang::class)
* #ORM\JoinColumn(name="id_lang", referencedColumnName="id_lang")
*/
private $id_lang;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $state;
public function __construct()
{
$this->id_state = new ArrayCollection();
$this->id_lang = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* #return Collection<int, State>
*/
public function getIdState(): Collection
{
return $this->id_state;
}
public function addIdState(State $idState): self
{
if (!$this->id_state->contains($idState)) {
$this->id_state[] = $idState;
}
return $this;
}
public function removeIdState(State $idState): self
{
$this->id_state->removeElement($idState);
return $this;
}
/**
* #return Collection<int, Lang>
*/
public function getIdLang(): Collection
{
return $this->id_lang;
}
public function addIdLang(Lang $idLang): self
{
if (!$this->id_lang->contains($idLang)) {
$this->id_lang[] = $idLang;
}
return $this;
}
public function removeIdLang(Lang $idLang): self
{
$this->id_lang->removeElement($idLang);
return $this;
}
public function getState(): ?string
{
return $this->state;
}
public function setState(?string $state): self
{
$this->state = $state;
return $this;
}
}
how can i get doctrine in entity to get permission list?
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Role\Role;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="`user`")
*/
class User implements UserInterface
{
private $entityManager;
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $discordId;
/**
* #ORM\Column(type="string", length=180)
*/
private $username;
/**
* #ORM\Column(type="string", length=255, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #ORM\OneToMany(targetEntity=Sites::class, mappedBy="owner", orphanRemoval=true)
*/
private $sites;
/**
* #ORM\PostLoad
* #ORM\PostPersist
*/
public function fetchEntityManager(LifecycleEventArgs $args)
{
$this->entityManager = $args->getEntityManager();
}
public function __construct()
{
$this->sites = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getdiscordId(): ?int
{
return $this->discordId;
}
public function setdiscordId(string $discordId): self
{
$this->discordId = $discordId;
return $this;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
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->username;
}
public function getRoles() :array
{
// get permissions from group
$groupPermissionsRepo = $this->entityManager->getRepository(GroupPermissions::class);
$groupAccessList = $groupPermissionsRepo->getPermissionsForGroup($this->getGroupId());
// create access
$accessList = [];
foreach ($groupAccessList as $access) {
$accessList[] = new Role('ROLE_'.$access);
}
// set default role when group didn't have any access granted
if(count($groupAccessList) == 0)
$accessList[] = new Role('ROLE_USER');
// return access
return $accessList;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
/**
* #return Collection<int, Sites>
*/
public function getSites(): Collection
{
return $this->sites;
}
public function addSite(Sites $site): self
{
if (!$this->sites->contains($site)) {
$this->sites[] = $site;
$site->setOwner($this);
}
return $this;
}
public function removeSite(Sites $site): self
{
if ($this->sites->removeElement($site)) {
// set the owning side to null (unless already changed)
if ($site->getOwner() === $this) {
$site->setOwner(null);
}
}
return $this;
}
}
While using this code i get only error:
App\Entity\User::fetchEntityManager(): Argument #1 ($args) must be of type Doctrine\Common\Persistence\Event\LifecycleEventArgs, Doctrine\ORM\Event\LifecycleEventArgs given, called in C:\xampp\htdocs\dbshop2\vendor\doctrine\orm\lib\Doctrine\ORM\Event\ListenersInvoker.php on line 84
i want to develop a doctrine-powered database application which should portray the following schema.
There are users, companies and relation-roles which describes the relation between a user to a company like [USER X] is [ROLE X] in [COMPANY X].
I'm using the symfony maker-bundle to create the entities I need. I'll attach every code at the end of this post.
To test the code, I persisted a company, a user, a role and a relation between them to the database. I expected that I could get all related users with their roles using a Company-Entity-Object with the generated getter getRelatedUsers() but I get an empty ArrayCollection.
This is how I tested to fetch the data in a TestController
#[Route('/test', name: 'test_page')]
public function index(CompanyRepository $companyRepository): Response
{
$companies = $companyRepository->findAll();
dd($companies[0]->getRelatedUsers());
}
Thanks for your help!
User.php
<?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)
* #ORM\Table(name="`user`")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $fullName;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="user")
*/
private $relatedCompanies;
public function __construct()
{
$this->relatedCompanies = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFullName(): ?string
{
return $this->fullName;
}
public function setFullName(string $fullName): self
{
$this->fullName = $fullName;
return $this;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedCompanies(): Collection
{
return $this->relatedCompanies;
}
public function addRelatedCompany(UserCompanyRelation $relatedCompany): self
{
if (!$this->relatedCompanies->contains($relatedCompany)) {
$this->relatedCompanies[] = $relatedCompany;
$relatedCompany->setUser($this);
}
return $this;
}
public function removeRelatedCompany(UserCompanyRelation $relatedCompany): self
{
if ($this->relatedCompanies->removeElement($relatedCompany)) {
// set the owning side to null (unless already changed)
if ($relatedCompany->getUser() === $this) {
$relatedCompany->setUser(null);
}
}
return $this;
}
}
Company.php
<?php
namespace App\Entity;
use App\Repository\CompanyRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=CompanyRepository::class)
*/
class Company
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="company")
*/
private $relatedUsers;
public function __construct()
{
$this->relatedUsers = 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;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedUsers(): Collection
{
return $this->relatedUsers;
}
public function addRelatedUser(UserCompanyRelation $relatedUser): self
{
if (!$this->relatedUsers->contains($relatedUser)) {
$this->relatedUsers[] = $relatedUser;
$relatedUser->setCompany($this);
}
return $this;
}
public function removeRelatedUser(UserCompanyRelation $relatedUser): self
{
if ($this->relatedUsers->removeElement($relatedUser)) {
// set the owning side to null (unless already changed)
if ($relatedUser->getCompany() === $this) {
$relatedUser->setCompany(null);
}
}
return $this;
}
}
UserCompanyRelation.php
<?php
namespace App\Entity;
use App\Repository\UserCompanyRelationRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserCompanyRelationRepository::class)
*/
class UserCompanyRelation
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=UserCompanyRelationRole::class, inversedBy="userCompanyRelations")
* #ORM\JoinColumn(nullable=false)
*/
private $role;
/**
* #ORM\ManyToOne(targetEntity=Company::class, inversedBy="relatedUsers")
* #ORM\JoinColumn(nullable=false)
*/
private $company;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="relatedCompanies")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
public function __construct()
{
}
public function getId(): ?int
{
return $this->id;
}
public function getRole(): ?UserCompanyRelationRole
{
return $this->role;
}
public function setRole(?UserCompanyRelationRole $role): self
{
$this->role = $role;
return $this;
}
public function getCompany(): ?Company
{
return $this->company;
}
public function setCompany(?Company $company): self
{
$this->company = $company;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
UserCompanyRelationRole.php
<?php
namespace App\Entity;
use App\Repository\UserCompanyRelationRoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserCompanyRelationRoleRepository::class)
*/
class UserCompanyRelationRole
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="role")
*/
private $userCompanyRelations;
public function __construct()
{
$this->userCompanyRelations = 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;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getUserCompanyRelations(): Collection
{
return $this->userCompanyRelations;
}
public function addUserCompanyRelation(UserCompanyRelation $userCompanyRelation): self
{
if (!$this->userCompanyRelations->contains($userCompanyRelation)) {
$this->userCompanyRelations[] = $userCompanyRelation;
$userCompanyRelation->setRole($this);
}
return $this;
}
public function removeUserCompanyRelation(UserCompanyRelation $userCompanyRelation): self
{
if ($this->userCompanyRelations->removeElement($userCompanyRelation)) {
// set the owning side to null (unless already changed)
if ($userCompanyRelation->getRole() === $this) {
$userCompanyRelation->setRole(null);
}
}
return $this;
}
}
I found an solution. I had to modify the fetch-strategy to EAGER in a annotation attribute. I modified the relatedUsers annotation property in company.php
<?php
namespace App\Entity;
use App\Repository\CompanyRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=CompanyRepository::class)
*/
class Company
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="company", fetch="EAGER")
*/
private $relatedUsers;
public function __construct()
{
$this->relatedUsers = 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;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedUsers(): Collection
{
return $this->relatedUsers;
}
public function addRelatedUser(UserCompanyRelation $relatedUser): self
{
if (!$this->relatedUsers->contains($relatedUser)) {
$this->relatedUsers[] = $relatedUser;
$relatedUser->setCompany($this);
}
return $this;
}
public function removeRelatedUser(UserCompanyRelation $relatedUser): self
{
if ($this->relatedUsers->removeElement($relatedUser)) {
// set the owning side to null (unless already changed)
if ($relatedUser->getCompany() === $this) {
$relatedUser->setCompany(null);
}
}
return $this;
}
}
You should use inversed by for bidirectional mapping between entities. See: https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/association-mapping.html#many-to-many-bidirectional
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;
}
// ...
}
I have the One-to-Many bidirectional relationship below.
After generating the crud actions with a symfony2 task, when I try to save the Products associated to a Category in the new/edit Category form, the products are not saved...
namespace Prueba\FrontendBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="category")
*/
class Category
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
/**
* #ORM\Column(name="name")
*/
protected $name;
public function __construct()
{
$this->products = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
public function getProducts()
{
return $this->products;
}
public function setProducts($products)
{
die("fasdf"); //here is not entering
$this->products[] = $products;
}
public function addProduct($product)
{
die("rwerwe"); //here is not entering
$this->products[] = $product;
}
}
namespace Prueba\FrontendBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="product")
*/
class Product
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name;
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getCategory()
{
return $this->category;
}
public function setCategory($category)
{
$this->category = $category;
}
public function __toString()
{
return $this->name;
}
}
As its bidirectional you need to update the association on both sides.
Add this function into the Category Entity (you can call it addChild if you like):
public function addProduct($product)
{
$this->children->add($product);
}
And then update both associations at the same time:
public function setProductCategory($product_category)
{
$this->productCategory = $product_category;
$product_category->addProduct($this);
}
Tip: Dont use $children / $parent to describe Entities. Call it what it is $category / $product, you'll run into issues when you want to add in another "parent" relationship.
Another short solution :
in your category entity , add this line to your addProduct function
public function addProduct($product)
{
$product->setCategory($this); // setting the cateogry of product
$this->products[] = $product;
}