I have a Evaluation entity which has one Product and Product which can have several Evaluations. I'm trying to fetch one Product and to get the list of Evaluations associated with my entity
Produit.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use phpDocumentor\Reflection\Types\This;
/**
* Produit
*
* #ORM\Table(name="produit", indexes={#ORM\Index(name="fk_idcatedel", columns={"idCategorie"})})
* #ORM\Entity
*/
class Produit
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string|null
*
* #ORM\Column(name="libelle", type="string", length=20, nullable=true)
*/
private $libelle;
/**
* #var float|null
*
* #ORM\Column(name="prix", type="float", precision=10, scale=0, nullable=true)
*/
private $prix;
/**
* #var string|null
*
* #ORM\Column(name="description", type="string", length=50, nullable=true)
*/
private $description;
/**
* #var int
*
* #ORM\Column(name="qt", type="integer", nullable=false)
*/
private $qt;
/**
* #var string|null
*
* #ORM\Column(name="img", type="string", length=255, nullable=true)
*/
private $img;
/**
* #var \Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idCategorie", referencedColumnName="id")
* })
*/
private $idcategorie;
/**
* #ORM\OneToMany(targetEntity="Evaluation", mappedBy="idProduit")
*/
private $rates;
public function __construct()
{
$this->rates = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getLibelle(): ?string
{
return $this->libelle;
}
public function setLibelle(?string $libelle): self
{
$this->libelle = $libelle;
return $this;
}
public function getPrix(): ?float
{
return $this->prix;
}
public function setPrix(?float $prix): self
{
$this->prix = $prix;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getQt(): ?int
{
return $this->qt;
}
public function setQt(int $qt): self
{
$this->qt = $qt;
return $this;
}
public function getImg(): ?string
{
return $this->img;
}
public function setImg(?string $img): self
{
$this->img = $img;
return $this;
}
public function getIdcategorie(): ?Categorie
{
return $this->idcategorie;
}
public function setIdcategorie(?Categorie $idcategorie): self
{
$this->idcategorie = $idcategorie;
return $this;
}
/**
* #return Collection|Evaluation[]
*/
public function getRates(): Collection
{
return $this->rates;
}
}
Evaluation.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Evaluation
*
* #ORM\Table(name="evaluation", indexes={#ORM\Index(name="fk_idprodevaldel", columns={"id_produit"}), #ORM\Index(name="fk_iduser", columns={"id_user"})})
* #ORM\Entity
*/
class Evaluation
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="note", type="integer", nullable=false)
*/
private $note;
/**
* #var \Produit
*
* #ORM\ManyToOne(targetEntity="Produit", inversedBy="rates")
* #ORM\JoinColumn(name="id_produit", referencedColumnName="id")
*/
private $idProduit;
/**
* #var \Compte
*
* #ORM\ManyToOne(targetEntity="Compte")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_user", referencedColumnName="email")
* })
*/
private $idUser;
public function getId(): ?int
{
return $this->id;
}
public function getNote(): ?int
{
return $this->note;
}
public function setNote(int $note): self
{
$this->note = $note;
return $this;
}
public function getIdProduit(): ?Produit
{
return $this->idProduit;
}
public function setIdProduit(?Produit $idProduit): self
{
$this->idProduit = $idProduit;
return $this;
}
public function getIdUser(): ?Compte
{
return $this->idUser;
}
public function setIdUser(?Compte $idUser): self
{
$this->idUser = $idUser;
return $this;
}
}
The database
In my controller I succeed to get informations from the products but rates are empty
$produits = $this->getDoctrine()
->getRepository(Produit::class)
->find(1);
dump($produits);
$rates = $produits->getRates();
dump($rates); // #collection: ArrayCollection is empty
The Output :
The collection is not yet initialized due to lazy loading, and rightfully so. If you don't access at least to an element in the collection, it's pointless to load the whole collection because doctrine can safely assume you'll "discard" it. As soon as you access an element (either by looping onto collection or getting a specific element), the collection will be initialized and you have all items.
Another way is to use an EAGER fetch that will load the whole collection in the hydration phase. I would not reccomend it however, unless you're sure that everytime you load a Produit, you need this collection "ready". Even in the latter case, I would handle the collection "manually" as I recommend not to lose control on it (let's pretend you have A LOT of element inside it).
Read more about proxies and association, here
Related
I am trying to implement sorting in my Symfony 6 project.
Here is the entity I am trying to sort :
<?php
namespace App\Entity;
use App\Entity\Workflow\Status;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Plant;
use App\Entity\DetailedCause;
/**
* #ORM\Entity(repositoryClass=\App\Repository\RequestRepository::class)
*/
class Request
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $requesterName;
/**
* #ORM\Column(type="string")
*/
private $requesterService;
/**
* #ORM\Column(type="string")
*/
private $requesterMatricule;
/**
* #ORM\Column(type="integer")
*/
private $priority;
/**
* #ORM\Column(type="integer")
*/
private $type;
/**
* #ORM\Column(type="boolean")
*/
private $flagSupp;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $estimatedLoad;
/**
* #ORM\Column(type="text")
*/
private $reason;
/**
* #ORM\Column(type="datetime", nullable=false)
*/
private $date;
/**
* #ORM\ManyToOne(targetEntity=Workflow\Status::class)
* #ORM\JoinColumn(nullable=false)
*/
private Status $state;
/**
* #ORM\Column(type="string", length=50, nullable=true)
*/
private $product;
/**
* #ORM\Column(type="string", length=50, nullable=true)
*/
private $program;
/**
* #ORM\ManyToOne(targetEntity=DetailedCause::class)
* #ORM\JoinColumn(nullable=false)
*/
private DetailedCause $detailedCause;
/**
* #ORM\ManyToOne(targetEntity=Cause::class)
*/
private $cause;
/**
* #ORM\ManyToOne(targetEntity=Plant::class)
* #ORM\JoinColumn(nullable=false)
*/
private Plant $impactedPlant;
/**
* #ORM\OneToMany(targetEntity=Action::class, mappedBy="request")
*/
private $actions;
/**
* #ORM\ManyToOne(targetEntity=Plant::class)
* #ORM\JoinColumn(nullable=false)
*/
private Plant $requesterPlant;
public function __construct()
{
$this->actions = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRequesterPlant(): ?Plant
{
return $this->requesterPlant;
}
public function setRequesterPlant(?Plant $requesterPlant): self
{
$this->requesterPlant = $requesterPlant;
return $this;
}
//the rest of getters and setters
}
and the repository :
<?php
namespace App\Repository;
use App\Entity\Request;
use App\Entity\RequestFilter;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Plant;
/**
* #method Request|null find($id, $lockMode = null, $lockVersion = null)
* #method Request|null findOneBy(array $criteria, array $orderBy = null)
* #method Request[] findAll()
* #method Request[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
* #method Paginator getRequestPaginator(int $offset = 0, string $order = 'id')
*/
class RequestRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Request::class);
}
/**
* #var int $offset
* #param RequestFilter
* #return Paginator Returns a paginator of requests using filters
*/
public function getRequestPaginator($offset = 0, RequestFilter $filter = null)
{
if ($filter == null) {
$filter = new RequestFilter();
}
#adds filter parameters to the query
$query = $this->createQueryBuilder('r');
if ($filter->getStates() != null){
$query
->andWhere('r.state IN (:states)')
->setParameter('states', $filter->getStates());//;
}
#adds the rest of the params
$query = $query
//this orderBy clause is triggering the error
->orderBy('r.' . $filter->getOrder(), $filter->getOrderDirection())
->setFirstResult($offset)
->setMaxResults($filter->getRequestsPerPage())
->getQuery();
return new Paginator($query);
}
}
this works fine for most attributes. I can sort by date, requester name, etc.
But when I try to sort by requesterPlant, which is a doctrine Entity, I get the following error :
("An exception occurred while executing a query: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'r0_.requester_plant_id' in 'field list'").
This column does exist in the database just like other columns. I do not understand why doctrine is stuck on this. Migrations are up to date, I've cleared cache, and I've been stuck on this problem for days.
I would really appreciate if anyone had a clue about what is happening there.
As additional info, here is my Plant entity :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=\App\Repository\PlantRepository::class)
*/
class Plant
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #ORM\OneToMany(targetEntity="App\Entity\Request", mappedBy="requesterPlant")
*/
private int $id;
/**
* #ORM\Column(type="string", length=255)
*/
private string $designation;
/**
* #ORM\Column(type="string", length=50)
*/
private string $plantString;
/**
* #ORM\Column(type="string", length=50)
*/
private string $company;
public function getId(): ?int
{
return $this->id;
}
public function setID(int $id): self
{
$this->id = $id;
return $this;
}
public function getDesignation(): ?string
{
return $this->designation;
}
public function setDesignation(string $designation): self
{
$this->designation = $designation;
return $this;
}
public function getPlantString(): ?string
{
return $this->plantString;
}
public function setPLantString(string $plantString): self
{
$this->plantString = $plantString;
return $this;
}
public function getCompany(): ?string
{
return $this->company;
}
public function setCompany(string $company): self
{
$this->company = $company;
return $this;
}
}
I'm a beginner in Symfony and here is my problem.
More precisely, I have two table in my DB. The first one is called 'post' and the other is called 'article'. The post table is the parent entity of article which mean that the article entity inherite from the post entity. What I would like to is to join this two table to get data from my database.
However, after reading the doctrine and symfony docs about mapping inheritance, I still cannot solve my problem.
Could you help me to solve this problem please ?
N.B : here is my code
Article class :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Articles
*
* #ORM\Table(name="articles")
* #ORM\Entity(repositoryClass="App\Repository\ArticlesRepository")
*/
class Articles
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="post", type="integer", nullable=false )
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $post;
/**
* #ORM\Column(type="string", length=255)
*/
private $themes;
/**
* Articles constructor.
* #param int $post
*/
public static $themeAvailable = [
0 => "Environnement",
1 => "Economie",
2 => "Science et technologie",
3 => "Loisir",
4 => "Culture générale",
5 => "Art",
6 => "Sport"
];
public function getId(): ?int
{
return $this->id;
}
public function getPost(): ?int
{
return $this->post;
}
public function getThemes(): ?string
{
return $this->themes;
}
public function setThemes(string $themes): self
{
$this->themes = $themes;
return $this;
}
public function setPost(int $post)
{
$this->post = $post;
}
}
Post class :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Posts
*
* #ORM\Table(name="posts")
* #ORM\Entity(repositoryClass="App\Repository\PostsRepository")
*/
class Posts
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="author", type="integer", nullable=false)
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $author;
/**
* #var string
* #Assert\NotBlank()
* #ORM\Column(name="title", type="string", length=255, nullable=false)
*/
private $title;
/**
* #var string
* #Assert\NotBlank()
* #ORM\Column(name="content", type="text", length=65535, nullable=false)
*/
private $content;
/**
* #var string
* #Assert\File(
* maxSize = "20M",
* maxSizeMessage = "La taille du fichier trop importante. Minimum autorisé : 20 Mo.",
* mimeTypes = {"image/svg","image/png", "image/jpg", "image/jpeg", "image/gif" },
* mimeTypesMessage = "Format du fichier incorrecte. Formats autorisés : svg, png, jpg, jpeg, gif.",
* disallowEmptyMessage = "Veuillez importer une image supérieur à 0 Mo."
* )
* #ORM\Column(name="image", type="blob", length=65535, nullable=false)
*/
private $image;
/**
* #var \DateTime
*
* #ORM\Column(name="creation_date", type="datetime", nullable=false, options={"default"="CURRENT_TIMESTAMP"})
*/
private $creationDate;
/**
* Posts constructor.
*/
public function __construct()
{
$this->creationDate = new \DateTime();
}
public function getId(): ?int
{
return $this->id;
}
public function getAuthor(): ?int
{
return $this->author;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getImage(): string
{
return $this->image;
}
public function setImage($image): self
{
$this->image = $image;
return $this;
}
public function getCreationDate(): ?\DateTimeInterface
{
return $this->creationDate;
}
public function setCreationDate(\DateTimeInterface $creationDate): self
{
$this->creationDate = $creationDate;
return $this;
}
public function setAuthor(int $author)
{
$this->author = $author;
}
}
My Repository :
public function findAllArticle()
{
return $this->createQueryBuilder('a')
->join('a.post',
'p')
->addSelect('p')
->getQuery()
->getResult();
}
And here is my controller :
<?php
namespace App\Controller;
use App\Entity\Articles;
use App\Entity\Posts;
use App\Form\PostsArticleType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class PostArticleController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
/**
* #var EntityManagerInterface
*/
private $em;
/**
* ArticleController constructor.
* #param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* #Route("/post/create", name="index")
* #return Response
*/
public function index(): Response
{
return $this->render('post/index.html.twig');
}
/**
* #Route("/post/article/show", name="showArticle")
* #return Response
*/
public function show(): Response
{
$articles = $this->getDoctrine()
->getManager()
->getRepository(Articles::class)
->findAllArticle();
return $this->render('post/showArticle.html.twig', array('article' => $articles));
}
/**
* #Route("/post/article/new", name="newArticle")
* #param Request $request
* #return Response
*/
public function new(Request $request): Response
{
$post = new Posts();
$article = new Articles();
$post->setAuthor(1);
$form = $this->createForm(PostsArticleType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$this->em->persist($post);
$this->em->flush();
$article->setPost($post->getId());
$themes = $form->get('themes')->getData();
$article->setThemes(implode(',', $themes));
$this->em->persist($article);
$this->em->flush();
return $this->redirectToRoute('home.html.twig');
}
return $this->render('post/CreateArticle.html.twig', ['form' => $form->createView()]);
}
}
As you have two tables posts and articles, you can use "JOINED" inheritance:
The Posts class should look like:
/*...*/
/**
* Posts
*
* #ORM\Table(name="posts")
* #ORM\Entity(repositoryClass="App\Repository\PostsRepository")
*
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({"posts" = "Posts", "articles" = "Articles"})
*/
class Posts
{
/*...*/
}
For Articles class:
/*...*/
/**
* Articles
*
* #ORM\Table(name="articles")
* #ORM\Entity(repositoryClass="App\Repository\ArticlesRepository")
*/
class Articles extends Posts
{
/*...*/
}
For the posts table, you will have the Posts class properties, and a column called 'discr' configured in DiscriminatorColumn parameter (see Posts class).
For the articles table, you will have the Articles class properties, and 'posts_id' column, which is a foreign key (it references 'id' column of 'posts' table).
There are some helpful links :
Doctrine : Class Table Inheritance
About Doctrine inheritance - Section: Class Table Inheritance
I have a problem with my Doctrine Entity.
In my module, I have a history to list actions performed by users.
During the process, I use a ManyToOne relation of my Entity towards herself.
When I update an item in my database, I use "setGain()" to refer this result to another, but if I want to cancel an action from user I need to set as null the value of setGain(), but Doctrine doesn't accept it and return :
PHP Catchable fatal error: Argument 1 passed to Paris\Entity\Historique::setGain() must be an instance of Paris\Entity\Historique, null given
My Entity is :
<?php
namespace Paris\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Historique
*
* #ORM\Table(name="paris__historique")
* #ORM\Entity
*/
class Historique {
/**
* #var integer
*
* #ORM\Column(name="id_historique", type="integer", precision=0, scale=0, nullable=false, unique=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id_historique;
/**
* #var integer
*
* #ORM\Column(name="id_jol", type="integer", length=11, precision=0, scale=0, nullable=true, unique=false)
*/
private $id_jol;
/**
* #var string
*
* #ORM\Column(name="action", type="string", length=50, precision=0, scale=0, nullable=false, unique=false)
*/
private $action;
/**
* #var string
*
* #ORM\Column(name="detail", type="text", precision=0, scale=0, nullable=true, unique=false)
*/
private $detail;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="\Paris\Entity\Historique")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_gain", referencedColumnName="id_historique", nullable=true)
* })
*/
private $id_gain;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="\Paris\Entity\Parieur")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_participant", referencedColumnName="id_participant", nullable=true)
* })
*/
private $id_participant;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="\Paris\Entity\Concours")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_concours", referencedColumnName="id_concours", nullable=true)
* })
*/
private $id_concours;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="\Paris\Entity\Periode")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_periode", referencedColumnName="id_periode", nullable=true)
* })
*/
private $id_periode;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="\Paris\Entity\Paris")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_paris", referencedColumnName="id_paris", nullable=true)
* })
*/
private $id_paris;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="\Paris\Entity\Mise")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_mise", referencedColumnName="id_mise", nullable=true)
* })
*/
private $id_mise;
/**
* #var integer
*
* #ORM\Column(name="date_historique", type="integer", length=11, precision=0, scale=0, nullable=false, unique=false)
*/
private $date_historique;
public function getIdHistorique() {
return $this->id_historique;
}
public function setIdJol($idJol) {
$this->id_jol = $idJol;
return $this;
}
public function getIdJol() {
return $this->id_jol;
}
public function setAction($action) {
$this->action = $action;
return $this;
}
public function getAction() {
return $this->action;
}
public function getGain() {
return $this->id_gain;
}
public function setGain(\Paris\Entity\Historique $id_gain) {
$this->id_gain = $id_gain;
return $this;
}
public function setDetail($detail) {
$this->detail = $detail;
return $this;
}
public function getDetail() {
return $this->detail;
}
public function setParieur(\Paris\Entity\Parieur $id_participant) {
$this->id_participant = $id_participant;
return $this;
}
public function getParieur() {
return $this->id_participant;
}
public function setConcours(\Paris\Entity\Concours $id_concours) {
$this->id_concours = $id_concours;
return $this;
}
public function getConcours() {
return $this->id_concours;
}
public function setPeriode(\Paris\Entity\Periode $id_periode) {
$this->id_periode = $id_periode;
return $this;
}
public function getPeriode() {
return $this->id_periode;
}
public function setPari(\Paris\Entity\Paris $id_paris) {
$this->id_paris = $id_paris;
return $this;
}
public function getPari() {
return $this->id_paris;
}
public function setmise(\Paris\Entity\Mise $id_mise) {
$this->id_mise = $id_mise;
return $this;
}
public function getMise() {
return $this->id_mise;
}
public function setDate($dateHistorique) {
$this->date_historique = $dateHistorique;
return $this;
}
public function getDate() {
return $this->date_historique;
}
}
In my database, the associated field is correctly set to Null by default and Nullable.
Can you help me ? ^^
Thank you in advance for your answer.
Define setGain as:
public function setGain(?\Paris\Entity\Historique $id_gain) {
$this->id_gain = $id_gain;
return $this;
}
? in front of class typehint allows to pass null as an argument.
Another option is:
public function setGain(\Paris\Entity\Historique $id_gain = null) {
$this->id_gain = $id_gain;
return $this;
}
I have the following inventory entity object for Doctrine that I created for use in Symfony 3.0.
Simply put how do I get access to the information that I put in the entity via annotations?
For example, companyID, has a ManyToOne annotation that references inversedBy="location". This particular information is very useful to me so I can tell if its a child relationship by foreign key or parent relationship.
If I can get the information about the entity that I described via annotations somehow in an array with Doctrine that would be great. Is this possible to do? Essentially I'm looking for introspection functions on the entity.
<?php
namespace AppBundle\Entity;
use Gedmo\Translatable\Translatable;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Inventory
*
* #ORM\Table(name="distribution_inventory")
* #ORM\Entity(repositoryClass="AppBundle\Repository\InventoryRepository")
*/
class Inventory implements Translatable {
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
/**
* #var string
* #Gedmo\Slug(fields={"name","id"},suffix=".html")
* #ORM\Column(name="inventoryslug", type="string", length=255, nullable=false, nullable=true)
*/
private $inventoryslug;
/**
* #var string
*
* #ORM\Column(name="barcode", type="string", length=255, nullable=true)
*/
private $barcode;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var string
* #ORM\Column(name="imagename", type="string", nullable=true)
*/
private $imagename;
/**
* #Gedmo\Locale
* Used locale to override Translation listener`s locale
* this is not a mapped field of entity metadata, just a simple property
*/
private $locale;
/**
* #var \AppBundle\Entity\InventoryCategory
*
* #ORM\ManyToOne(targetEntity="\AppBundle\Entity\InventoryCategory")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="categoryid", referencedColumnName="id")
* })
*/
private $category;
/**
* #var \AppBundle\Entity\Company
* #Assert\Type(type="\AppBundle\Entity\Company")
* #Assert\Valid()
* #ORM\ManyToOne(targetEntity="\AppBundle\Entity\Company", inversedBy="Location")
* #ORM\JoinColumn(name="companyid", referencedColumnName="id", onDelete="CASCADE")
*/
protected $companyId;
/**
* #var \DateTime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* #var string
* #ORM\Column(name="defaultsellprice",precision=14, scale=2, nullable=true)
*/
private $defaultsellprice;
/**
* #var boolean
*
* #ORM\Column(name="onwaycount", type="integer", nullable=false)
*/
private $onwaycount;
/**
* #var boolean
*
* #ORM\Column(name="instorecount", type="integer", nullable=false)
*/
private $instorecount;
/**
* #var boolean
*
* #ORM\Column(name="wayoutcount", type="integer", nullable=false)
*/
private $wayoutcount;
/**
* #var boolean
*
* #ORM\Column(name="instore", type="string", length=10, nullable=false)
*/
private $instore;
/**
* #var string
*
* #ORM\Column(name="isarchived", type="string", length=5, nullable=false,options={"default":false})
*/
private $isarchived;
/**
* #var string
*
* #ORM\Column(name="archivestatus", type="string", length=5, nullable=false,options={"default":true})
*/
private $archivestatus;
function __construct() {
$this->onwaycount=0;
$this->instore=FALSE;
$this->instorecount=0;
$this->wayoutcount=0;
}
/**
* Get id
*
* #return int
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Inventory
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set barcode
*
* #param string $barcode
*
* #return Inventory
*/
public function setBarcode($barcode) {
$this->barcode = $barcode;
return $this;
}
/**
* Get barcode
*
* #return string
*/
public function getBarcode() {
return $this->barcode;
}
/**
* Set description
*
* #param string $description
*
* #return Inventory
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
public function getImagename() {
return $this->imagename;
}
public function getCategory() {
return $this->category;
}
public function getCompanyId() {
return $this->companyId;
}
public function getCreated() {
return $this->created;
}
public function getUpdated() {
return $this->updated;
}
public function getOnwaycount() {
return $this->onwaycount;
}
public function getInstorecount() {
return $this->instorecount;
}
public function getWayoutcount() {
return $this->wayoutcount;
}
public function getInstore() {
return $this->instore;
}
public function setImagename($imagename) {
$this->imagename = $imagename;
return $this;
}
public function setCategory(\AppBundle\Entity\InventoryCategory $category) {
$this->category = $category;
return $this;
}
public function setCompanyId(\AppBundle\Entity\Company $companyId) {
$this->companyId = $companyId;
return $this;
}
public function setCreated(\DateTime $created) {
$this->created = $created;
return $this;
}
public function setUpdated(\DateTime $updated) {
$this->updated = $updated;
return $this;
}
public function setOnwaycount($onwaycount) {
$this->onwaycount = $onwaycount;
return $this;
}
public function setInstorecount($instorecount) {
$this->instorecount = $instorecount;
return $this;
}
public function setWayoutcount($wayoutcount) {
$this->wayoutcount = $wayoutcount;
return $this;
}
public function setInstore($instore) {
$this->instore = $instore;
return $this;
}
public function getDefaultsellprice() {
return $this->defaultsellprice;
}
public function setDefaultsellprice($defaultsellprice) {
$this->defaultsellprice = $defaultsellprice;
return $this;
}
public function getInventoryslug() {
return $this->inventoryslug;
}
public function setInventoryslug($inventoryslug) {
$this->inventoryslug = $inventoryslug;
return $this;
}
public function setTranslatableLocale($locale) {
$this->locale = $locale;
}
public function getIsarchived() {
return $this->isarchived;
}
public function getArchivestatus() {
return $this->archivestatus;
}
public function setIsarchived($isarchived) {
$this->isarchived = $isarchived;
return $this;
}
public function setArchivestatus($archivestatus) {
$this->archivestatus = $archivestatus;
return $this;
}
}
Found this not sure if it will help though (http://tocacar.com/2013/01/25/doctrine2-object-introspection/)
To get an array of metadata:
$cmf = $em->getMetadataFactory();
$metadata = $cmf->getMetadataFor(\AppBundle\Entity\Inventory::class);
//Doctrine\ORM\Mapping\ClassMetadata instance
//as array:
$metadata = (array) $metadata;
To get the inversed information:
$metadata->getAssociationMapping('companyId')['inversedBy'];
//as array
$metadata['associationMappings']['companyId']['inversedBy'];
You can find more info on the docs.
I haven't found any solid example on how to do this.
I have my entity Shield, which can have more than 1 ShieldTypes. What I want to do is, create a form that creates a new Shield with different Shieldtypes.
This is my code, I honestly don't know where is my error:
Error is:
Entities passed to the choice field must be managed
500 Internal Server Error - FormException
Armory\SearchBundle\Entity\Shield.php
namespace Armory\SearchBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Armory\SearchBundle\Entity\Shield
*
* #ORM\Table(name="shield")
* #ORM\Entity
*/
class Shield
{
/**
* #var integer $id
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $name
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var integer $defense
* #ORM\Column(name="defense", type="integer", nullable=false)
*/
private $defense;
/**
* #var boolean $active
* #ORM\Column(name="active", type="boolean", nullable=false)
*/
private $active;
/**
* #ORM\ManyToMany(targetEntity="ShieldTypes")
* #ORM\JoinTable(name="i_orbs_type",
* joinColumns={#ORM\JoinColumn(name="id_orb", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="id_type", referencedColumnName="id")}
* )
* #var ArrayCollection $types
*/
protected $types;
public function __construct(){
$this->types = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getTypes(){
return $this->types;
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setDefense($defense)
{
$this->defense = $defense;
}
public function getDefense()
{
return $this->defense;
}
public function setActive($active)
{
$this->active = $active;
}
public function getActive()
{
return (bool)$this->active;
}
}
Armory\SearchBundle\Form\ShieldType.php:
namespace Armory\SearchBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class ShieldType extends AbstractType{
public function buildForm(FormBuilder $builder, array $options){
$builder->add('name','text');
$builder->add('defense','integer');
$builder->add('active','checkbox');
$builder->add('types','entity',
array(
'class'=>'Armory\SearchBundle\Entity\ShieldTypes',
'query_builder'=> function($repository){
return $repository->createQueryBuilder('t')->orderBy('t.id', 'ASC');
},
'property'=>'name', )
);
}
public function getName(){
return 'shield';
}
public function getDefaultOptions(array $options){
return array('data_class'=>'Armory\\SearchBundle\\Entity\\Shield');
}
}
Armory\SearchBundle\Entity\ShieldTypes.php
namespace Armory\SearchBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SOA\CRMBundle\Entity\ShieldTypes
*
* #ORM\Table(name="orbs_type")
* #ORM\Entity
*/
class ShieldTypes
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var string $title
*
* #ORM\Column(name="title", type="string", length=45, nullable=false)
*/
private $title;
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
It can be a little confusing but:
Shield entity (database)
ShieldTypes entity (database)
ShieldType form (abstracttype)
Thank you...
So the problem was that I didn't create a repository. I created it (see code at the end) and I still got 'Entities passed to the choice field must be managed' error.
Then I set mutiple to true in:
$builder->add('types','entity',
array(
'class'=>'Armory\SearchBundle\Entity\ShieldTypes',
'query_builder'=> function(\Armory\SearchBundle\Entity\Repository\ShieldTypesRepository $repository){
return $repository->createQueryBuilder('s')->orderBy('s.id', 'ASC');},
'property'=>'title',
'multiple'=>true
)
);
I hope someone finds this useful, cause if I had had this, it would been easier.
Code for my repository:
namespace Armory\SearchBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
class ShieldTypesRepository extends EntityRepository
{
public function getAll()
{
return $this->_em->createQuery('SELECT s FROM Armory\SearchBundle\Entity\ShieldTypes s')
->getResult();
}
}