I have a test app with a manytomany relationship and I can get a JSON correctly:
Job.php:
<?php
namespace App\Entity;
use Symfony\Component\Serializer\Annotation\Groups;
use App\Repository\JobRepository;
use Doctrine\ORM\Mapping as ORM;
use \App\Entity\Category;
/**
* #ORM\Entity(repositoryClass=JobRepository::class)
*/
class Job
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Category", inversedBy="jobs")
* #ORM\JoinTable(
* name="jobs_categories",
* joinColumns={#ORM\JoinColumn(name="job_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="id")}
* )
*/
private $categories;
/**
* Constructor
*/
public function __construct()
{
$this->categories = new \Doctrine\Common\Collections\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 addCategory($categories): self
{
$this->categories[] = $categories;
return $this;
}
public function removeCategory(Category $categories)
{
$this->categories->removeElement($categories);
}
public function getCategories()
{
return $this->categories;
}
public function __toString () {
return $this->name;
}
}
Category.php
<?php
namespace App\Entity;
use App\Repository\CategoryRepository;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Job;
/**
* #ORM\Entity(repositoryClass=CategoryRepository::class)
*/
class Category
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\ManyToMany(targetEntity="Job", mappedBy="categories")
*/
protected $jobs;
/**
* Constructor
*/
public function __construct()
{
$this->jobs = new \Doctrine\Common\Collections\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 addJob(Job $post): self
{
$this->jobs[] = $post;
return $this;
}
public function removeJob(Job $post)
{
$this->jobs->removeElement($post);
}
public function getJob()
{
return $this->jobs;
}
public function __toString () {
return $this->name;
}
}
index.html (JQuery Ajax):
// Añadir tarea
$('#addJob').click(function () {
var name = $('#name').val();
var categories = [];
var categoriesChbx = $(".category");
if (name === "") {
alert("Tienes que agregar una tarea."); // TODO
} else {
categoriesChbx.each(function () {
var item = $(this);
item.is(':checked') ? categories.push(item.attr("name")) : "";
});
var job = {
name: name,
categories: categories
};
var error = false;
$.ajax({
url: "{{ url('ajax_save_job') }}",
type: "POST",
dataType: "json",
data: {
"job": job,
"error": error
},
async: true,
success: function (data, error) {
console.log(data, error);
if (error !== false) {
// TODO
errorDiv = $('.error');
errorDiv.html(error);
errorDiv.show();
}
}
});
}
return false;
});
BackendController.php (ajax method):
public function ajaxSaveJob ()
{
//dump($request->isXMLHttpRequest());
if ($request->isXMLHttpRequest()) {
$jobArray = $request->request->get('job');
$jobInclude = $this->getDoctrine()->getRepository(Job::class)->findOneBy(['name' => $jobArray['name']]);
if (!isset($jobInclude)) {
$job = new Job();
$job->setName($jobArray['name']);
if (isset($jobArray['categories'])) {
foreach ($jobArray['categories'] as $value) {
$category = new Category();
$category = $this->getDoctrine()->getRepository(Category::class)->findOneBy(['name' => $value]);
$job->addCategory($category);
}
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($job);
$entityManager->flush();
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
// Serializar objeto a JSON
$jobJson = $serializer->serialize($job, 'json', [
'circular_reference_handler' => function ($object) {
return $object->getName();
}
]);
dump($jobJson);
return new JsonResponse([ 'data' => $jobJson, 'error' => false ]);
}
else {
return new JsonResponse([ 'data' => '', 'error' => 'Ese taréa ya existe' ]);
}
}
else {
return new JsonResponse([ 'data' => '', 'error' => "Error: ..." ]); // TODO
}
}
I want to get somethink like this:
{
"id":137,
"name":"43545",
"categories":["php", "javascript"]
}
But instead I get this:
{
"id":142,
"name":"Diego",
"categories":[{"id":5,"name":"javascript","job":[{"id":103,"name":"5654","categories":[{"id":4,"name":"php","job":["5654",{"id":139,"name":"Mar\u00eda","categories":["php","javascript",{"id":6,"name":"css","job":[{"id":135,"name":"53453453","categories":["javascript","css"]},{"id":138,"name":"Fernando","categories":["javascript","css"]},"Mar\u00eda",{"id":140,"name":"Jose","categories":["css"]}]}]}]},"javascript"]},{"id":135,"name":"53453453","categories":["javascript",{"id":6,"name":"css","job":["53453453",{"id":138,"name":"Fernando","categories":["javascript","css"]},{"id":139,"name":"Mar\u00eda","categories":[{"id":4,"name":"php","job":[{"id":103,"name":"5654","categories":["php","javascript"]},"Mar\u00eda"]},"javascript","css"]},{"id":140,"name":"Jose","categories":["css"]}]}]},{"id":138,"name":"Fernando","categories":["javascript",{"id":6,"name":"css","job":[{"id":135,"name":"53453453","categories":["javascript","css"]},"Fernando",{"id":139,"name":"Mar\u00eda","categories":[{"id":4,"name":"php","job":[{"id":103,"name":"5654","categories":["php","javascript"]},"Mar\u00eda"]},"javascript","css"]},{"id":140,"name":"Jose","categories":["css"]}]}]},{"id":139,"name":"Mar\u00eda","categories":[{"id":4,"name":"php","job":[{"id":103,"name":"5654","categories":["php","javascript"]},"Mar\u00eda"]},"javascript",{"id":6,"name":"css","job":[{"id":135,"name":"53453453","categories":["javascript","css"]},{"id":138,"name":"Fernando","categories":["javascript","css"]},"Mar\u00eda",{"id":140,"name":"Jose","categories":["css"]}]}]},"Diego"]}]
}
¿How could you get only the categories associated with the currently handled job?
PS: Sorry for my bad English.
Related
My Entity Item has a Repository (ItemRepository) with the function findItemCount(). When I use
$repository = $em->getRepository(Item::class);
$items = $repository->findItemCount();
I get the warning:
Potentially polymorphic call. The code may be inoperable depending on the actual class instance passed as the argument.
Also the auto completion doesn't suggest me the function "findItemCount". What is my mistake?
Controller:
/**
* Artikel Liste
* #Route("/item/list", name="app_item_list")
* #param EntityManagerInterface $em
* #return Response
*/
public function listItems(EntityManagerInterface $em): Response
{
$repository = $em->getRepository(Item::class);
$items = $repository->findItemCount();
return $this->render('item_admin/itemList.html.twig', [
'items' => $items,
'title' => 'Artikel Übersicht',
'blocked' => false
]);
}
Item.php
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\OrderBy;
/**
* #ORM\Entity(repositoryClass="App\Repository\ItemRepository")
*/
class Item
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #OrderBy({"name" = "ASC"})
*/
private $name;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Itemparent", inversedBy="item")
*/
private $itemparent;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Itemgroup", inversedBy="items")
*/
private $itemgroup;
/**
* #ORM\Column(type="string", length=255)
*/
private $minsize;
/**
* #ORM\Column(type="boolean")
*/
private $charge;
/**
* #ORM\Column(type="boolean")
*/
private $blocked;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Barcode", mappedBy="item", orphanRemoval=true)
*/
private $barcodes;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ItemStock", mappedBy="item", orphanRemoval=true)
*/
private $itemStocks;
/**
* #ORM\OneToMany(targetEntity="App\Entity\BookingItem", mappedBy="item", orphanRemoval=true)
*/
private $bookingItems;
/**
* #ORM\Column(type="float", nullable=true)
*/
private $price;
/**
* #ORM\OneToMany(targetEntity=SupplierItems::class, mappedBy="item")
*/
private $supplierItems;
/**
* #ORM\OneToMany(targetEntity=ItemStockCharge::class, mappedBy="item")
*/
private $itemStockCharges;
public function __construct()
{
$this->barcodes = new ArrayCollection();
$this->itemStocks = new ArrayCollection();
$this->suppliers = new ArrayCollection();
$this->supplierItems = new ArrayCollection();
$this->itemStockCharges = 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 getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getItemparent(): ?Itemparent
{
return $this->itemparent;
}
public function setItemparent(?Itemparent $itemparent): self
{
$this->itemparent = $itemparent;
return $this;
}
public function getItemgroup(): ?Itemgroup
{
return $this->itemgroup;
}
public function setItemgroup(?Itemgroup $itemgroup): self
{
$this->itemgroup = $itemgroup;
return $this;
}
public function getMinsize(): ?string
{
return $this->minsize;
}
public function setMinsize(string $minsize): self
{
$this->minsize = $minsize;
return $this;
}
public function getCharge(): ?bool
{
return $this->charge;
}
public function setCharge(bool $charge): self
{
$this->charge = $charge;
return $this;
}
public function getBlocked(): ?bool
{
return $this->blocked;
}
public function setBlocked(bool $blocked): self
{
$this->blocked = $blocked;
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->setItem($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->getItem() === $this) {
$barcode->setItem(null);
}
}
return $this;
}
/**
* #return Collection|ItemStock[]
*/
public function getItemStocks(): Collection
{
return $this->itemStocks;
}
public function addItemStock(ItemStock $itemStock): self
{
if (!$this->itemStocks->contains($itemStock)) {
$this->itemStocks[] = $itemStock;
$itemStock->setItem($this);
}
return $this;
}
public function removeItemStock(ItemStock $itemStock): self
{
if ($this->itemStocks->contains($itemStock)) {
$this->itemStocks->removeElement($itemStock);
// set the owning side to null (unless already changed)
if ($itemStock->getItem() === $this) {
$itemStock->setItem(null);
}
}
return $this;
}
/**
* #return Collection|BookingItem[]
*/
public function getBookingItems(): Collection
{
return $this->bookingItems;
}
public function addBookingItem(BookingItem $bookingItem): self
{
if (!$this->bookingItems->contains($bookingItem)) {
$this->bookingItems[] = $bookingItem;
$bookingItem->setItem($this);
}
return $this;
}
public function removeBookingItem(BookingItem $bookingItem): self
{
if ($this->bookingItems->contains($bookingItem)) {
$this->bookingItems->removeElement($bookingItem);
if ($bookingItem->getItem() === $this) {
$bookingItem->setItem(null);
}
}
return $this;
}
public function getPrice(): ?float
{
return $this->price;
}
public function setPrice(?float $price): self
{
$this->price = $price;
return $this;
}
public function getCommaPrice(): string
{
return number_format($this->price, 2, ',', '');
}
/**
* #return Collection|SupplierItems[]
*/
public function getSupplierItems(): Collection
{
return $this->supplierItems;
}
public function addSupplierItem(SupplierItems $supplierItem): self
{
if (!$this->supplierItems->contains($supplierItem)) {
$this->supplierItems[] = $supplierItem;
$supplierItem->setItem($this);
}
return $this;
}
public function removeSupplierItem(SupplierItems $supplierItem): self
{
if ($this->supplierItems->contains($supplierItem)) {
$this->supplierItems->removeElement($supplierItem);
// set the owning side to null (unless already changed)
if ($supplierItem->getItem() === $this) {
$supplierItem->setItem(null);
}
}
return $this;
}
/**
* #return Collection|ItemStockCharge[]
*/
public function getItemStockCharges(): Collection
{
return $this->itemStockCharges;
}
public function addItemStockCharge(ItemStockCharge $itemStockCharge): self
{
if (!$this->itemStockCharges->contains($itemStockCharge)) {
$this->itemStockCharges[] = $itemStockCharge;
$itemStockCharge->setItem($this);
}
return $this;
}
public function removeItemStockCharge(ItemStockCharge $itemStockCharge): self
{
if ($this->itemStockCharges->contains($itemStockCharge)) {
$this->itemStockCharges->removeElement($itemStockCharge);
// set the owning side to null (unless already changed)
if ($itemStockCharge->getItem() === $this) {
$itemStockCharge->setItem(null);
}
}
return $this;
}
}
ItemRepository.php
<?php
namespace App\Repository;
use App\Entity\Item;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
/**
* #method Item|null find($id, $lockMode = null, $lockVersion = null)
* #method Item|null findOneBy(array $criteria, array $orderBy = null)
* #method Item[] findAll()
* #method Item[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ItemRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Item::class);
}
public function findItem()
{
return $this->createQueryBuilder('a')
->andWhere('a.blocked = :val')
->setParameter('val', false)
->orderBy('a.name', 'ASC')
->getQuery()
->getResult()
;
}
public function findBlockedItemCount()
{
return $this->createQueryBuilder('item')
->select('item, SUM(stocks.count) as sums')
->andWhere('item.blocked = :val')
->setParameter('val', true)
->leftJoin('item.itemStocks', 'stocks')
->groupBy('item')
->orderBy('item.name', 'ASC')
->getQuery()
->getResult()
;
}
public function findItemCount(){
return $this->createQueryBuilder('item')
->select('item, SUM(stocks.count) as sums')
->andWhere('item.blocked = :val')
->setParameter('val', false)
->leftJoin('item.itemStocks', 'stocks')
->groupBy('item')
->orderBy('item.name', 'ASC')
->getQuery()
->getResult()
;
}
}
The IDE has now way of knowing that $em->getRepository(Item::class); will return ItemRepository, since that's not resolved until runtime.
Inject ItemRepository instead of the entity manager, it's the better practice in any case:
public function listItems(ItemRepository $itemRepository): Response
{
$items = $itemRepository->findItemCount();
// etc
}
I have a colleague entity, which has a many to one relation with user entity.
I want to only have the ability to access colleagues attached to identified user.
This is for all CRUD permissions: list, edit, update, delete.
I've tried a lot of things, like DQL filter in easy_admin.yaml, but I can't manage to get authenticated user id.
I'm a Symfony junior, so I don't know how to do this and I must use Easyadmin.
So, it seems I can't use ColleagueController.php. Maybe with ColleagueRepository.php?
For the moment, everything is configured in easy_admin.yaml:
easy_admin:
design:
templates:
label_null: 'null_value.html.twig'
entities:
Colleague:
class: App\Entity\Colleague
list:
# dql_filter: "entity.user = 15"
# dql_filter: "entity.user = '%env(AUTHENTICATED_USER)%'"
# dql_filter: "entity.user = (SELECT id FROM user WHERE email = '%env(AUTHENTICATED_USER)%')"
# dql_filter: "entity.user = (SELECT id FROM App\Entity\User WHERE email = 'aaa#gmail.com')"
fields:
- user
- name
- role
- notes
- { property: 'thumbnail', type: 'image', base_path: '%uploads_path%' }
actions: ['show', 'edit', 'delete']
form:
fields:
- user
- name
- role
- notes
- { property: 'thumbnailFile', type: 'vich_image' }
show:
fields:
- user
- name
- role
- notes
- { property: 'thumbnail', type: 'image', base_path: '%uploads_path%' }
And my Entity\Colleague.php:
<?php
namespace App\Entity;
use App\Repository\ColleagueRepository;
use Doctrine\ORM\Mapping as ORM;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;
/**
* #ORM\Entity(repositoryClass=ColleagueRepository::class)
* #Vich\Uploadable
*/
class Colleague
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="colleagues")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $role;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $notes;
/**
* #ORM\Column(type="string", length=255, nullable=true, options={"default": 0})
*
* #var string
*/
private $thumbnail;
/**
* #Vich\UploadableField(mapping="colleague_thumbnails", fileNameProperty="thumbnail")
*
* #var File
*/
private $thumbnailFile;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $createdAt;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
public function __construct()
{
$this->setCreatedAt(new \DateTime());
$this->setUpdatedAt(new \DateTime());
// var_dump($this->get('security.token_storage')->getToken()->getUser());
// die;
}
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;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getRole(): ?string
{
return $this->role;
}
public function setRole(?string $role): self
{
$this->role = $role;
return $this;
}
public function getNotes(): ?string
{
return $this->notes;
}
public function setNotes(?string $notes): self
{
$this->notes = $notes;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
public function getThumbnail(): ?string
{
return $this->thumbnail;
}
public function setThumbnail(?string $thumbnail): self
{
$this->thumbnail = $thumbnail;
return $this;
}
/**
* #return File
*/
public function getThumbnailFile()
{
return $this->thumbnailFile;
}
/**
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*
* #return User
*/
public function setThumbnailFile(File $thumbnail = null)
{
$this->thumbnailFile = $thumbnail;
if ($thumbnail) {
$this->updatedAt = new \DateTime('now');
}
return $this;
}
}
Thanks in advance for your precious help.
Here is the same answer as proposed on Linkedin: easy admin advanced permissions. (french post content)
You can combine an event subscriber with a voter, simply follow this example.
Best regards.
I've managed to do Easyadmin specific filtering this way:
config/packages/easy_admin.yaml:
easy_admin:
entities:
Colleague:
class: App\Entity\Colleague
controller: App\Controller\ColleagueController
src/Controller/ColleagueController.php:
<?php
namespace App\Controller;
use Symfony\Component\Routing\Annotation\Route;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class ColleagueController extends EasyAdminController
{
protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{
$result = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
if (method_exists($entityClass, 'getUser')) {
$result->andWhere('entity.user = :user');
$result->setParameter('user', $this->getUser());
}
return $result;
}
protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
{
$result = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter);
if (method_exists($entityClass, 'getUser')) {
$result->andWhere('entity.user = :user');
$result->setParameter('user', $this->getUser());
}
return $result;
}
protected function createEditForm($entity, array $entityProperties)
{
$result = parent::createEditForm($entity, $entityProperties);
if ($entity->getUser() !== $this->getUser()) {
throw new AccessDeniedException();
}
return $result;
}
protected function showAction()
{
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
if ($entity->getUser() !== $this->getUser()) {
throw new AccessDeniedException();
}
$result = parent::showAction();
return $result;
}
protected function deleteAction()
{
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
if ($entity->getUser() !== $this->getUser()) {
throw new AccessDeniedException();
}
$result = parent::deleteAction();
return $result;
}
/**
* Create a colleague.
*/
protected function persistEntity($entity)
{
$entity->setUser($this->getUser());
$result = parent::persistEntity($entity);
return $result;
}
}
I have a CollectionType fields in my form, and I made it so I can add as many of these fields as you like, here's a pic (the collectiontype are the fields under Exception)
https://imgur.com/a/xQ7qUNT
Now I'm trying to loop through the data and insert it into an array and finally insert it into my database, but this is what I get in my databse https://imgur.com/a/WyBmmwr
also, tried getting the data that is cough after clicking submit: https://imgur.com/a/pLBKx1y and it's there.
this is my method:
/**
* #Route("/new", name="type_parking_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$typeParking = new TypeParking();
$exception = new Exception();
$form = $this->createForm(TypeParkingType::class, $typeParking);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$lesjours = $typeParking->getJourstravail();
$typeParking->getException()->add($exception);
// Here I try getting the data
$excep = $form->get('Exception');
foreach ($excep as $ExceptionForm) {
$name = $ExceptionForm->get('nom')->getData();
$StartDate = $ExceptionForm->get('datedebut')->getData();
$EndDate = $ExceptionForm->get('datefin')->getData();
$StartTime = $ExceptionForm->get('tempsdebut')->getData();
$EndTime = $ExceptionForm->get('tempsfin')->getData();
$exception->setNom($name);
$exception->setDatedebut($StartDate);
$exception->setDatefin($EndDate);
$exception->setTempsdebut($StartTime);
$exception->setTempsfin($EndTime);
$typeParking->addException($exception);
}
// ends here
// this is unrelated
$jour = $lesjours['jour'];
$debut = $lesjours['debut']->format('H:i:s');
$fin = $lesjours['fin']->format('H:i:s');
$newDate = Array('lesjour' => Array($jour => Array('heuredebut' => $debut, 'heurefin' => $fin)));
$typeParking->setJourstravail($newDate);
//end unrelated
$this->addFlash('success', "type added ");
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($typeParking);
$entityManager->flush();
return $this->redirectToRoute('type_parking_index');
}
return $this->render(
'Admin/type_parking/new.html.twig',
['type_parking' => $typeParking, 'form' => $form->createView()]
);
}
and here's my entity TypeParking
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="App\Repository\TypeParkingRepository")
*/
class TypeParking
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=55)
*/
private $libelle;
/**
* #ORM\Column(type="time", nullable=true)
*/
private $tempsmax;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $jourdebut;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $jourfin;
/**
* #ORM\Column(type="json_array", nullable=true)
*/
private $jourstravail;
/**
* #ORM\Column(type="json_array", nullable=true)
*/
private $exception;
public function __construct()
{
$this->exception = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTempsmax(): ?\DateTimeInterface
{
return $this->tempsmax;
}
public function setTempsmax(\DateTimeInterface $tempsmax): self
{
$this->tempsmax = $tempsmax;
return $this;
}
public function getJourdebut(): ?\DateTimeInterface
{
return $this->jourdebut;
}
public function setJourdebut(\DateTimeInterface $jourdebut): self
{
$this->jourdebut = $jourdebut;
return $this;
}
public function getJourfin(): ?\DateTimeInterface
{
return $this->jourfin;
}
public function setJourfin(\DateTimeInterface $jourfin): self
{
$this->jourfin = $jourfin;
return $this;
}
public function getJourstravail()
{
return array_merge([
'jour' => '',
'debut' => null,
'fin' => null,
// other sub-fields "empty" values
], $this->jourstravail ?? [] // prevent array_merge from failing if exception is empty
); }
public function setJourstravail($jourstravail): self
{
$this->jourstravail = $jourstravail;
return $this;
}
public function getException() {
return $this->exception;
}
public function setException($exception): self
{
$this->exception = $exception;
return $this;
}
public function addException($exception)
{
$this->exception->add($exception);
return $this;
}
public function getLibelle(): ?string
{
return $this->libelle;
}
public function setLibelle(string $libelle): self
{
$this->libelle = $libelle;
return $this;
}
}
btw, I have two entities, TypeParking and Exception, TypeParking has a property named Exception which is a json file type and must contain the data from Exception.
I've a problem about datas on my form view
The principle is the same as this video (https://www.youtube.com/watch?v=MRfsHix1eRA&t=1257s), that is to say: when I select a "management" I want the "services" associated to this "management".
These must be selected in a "report Form" (Report Entity).
OneOrMany service is linked to One management, and a report is linked to a management and a service.
Entities
Management.php
<?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\ManagementRepository")
*/
class Management
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Service", mappedBy="management")
*/
private $services;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Report", mappedBy="management")
*/
private $reports;
public function __construct()
{
$this->services = new ArrayCollection();
$this->reports = 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|Service[]
*/
public function getServices(): Collection
{
return $this->services;
}
public function addService(Service $service): self
{
if (!$this->services->contains($service)) {
$this->services[] = $service;
$service->setManagement($this);
}
return $this;
}
public function removeService(Service $service): self
{
if ($this->services->contains($service)) {
$this->services->removeElement($service);
// set the owning side to null (unless already changed)
if ($service->getManagement() === $this) {
$service->setManagement(null);
}
}
return $this;
}
/**
* #return Collection|Report[]
*/
public function getReports(): Collection
{
return $this->reports;
}
public function addReport(Report $report): self
{
if (!$this->reports->contains($report)) {
$this->reports[] = $report;
$report->setManagement($this);
}
return $this;
}
public function removeReport(Report $report): self
{
if ($this->reports->contains($report)) {
$this->reports->removeElement($report);
// set the owning side to null (unless already changed)
if ($report->getManagement() === $this) {
$report->setManagement(null);
}
}
return $this;
}
}
Service.php
<?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\ReportRepository")
*/
class Report
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="date")
*/
private $assigned_date;
/**
* #ORM\Column(type="decimal", precision=7, scale=2, nullable=true)
*/
private $time;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Game", inversedBy="reports")
*/
private $game;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Management", inversedBy="reports")
*/
private $management;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Service", inversedBy="reports")
*/
private $service;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Format", inversedBy="reports")
*/
private $format;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="reports")
* #ORM\JoinColumn(nullable=false)
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="reports")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
public function getId(): ?int
{
return $this->id;
}
public function getAssignedDate(): ?\DateTimeInterface
{
return $this->assigned_date;
}
public function setAssignedDate(\DateTimeInterface $assigned_date): self
{
$this->assigned_date = $assigned_date;
return $this;
}
public function getTime()
{
return $this->time;
}
public function setTime($time): self
{
$this->time = $time;
return $this;
}
public function getGame(): ?Game
{
return $this->game;
}
public function setGame(?Game $game): self
{
$this->game = $game;
return $this;
}
public function getManagement(): ?Management
{
return $this->management;
}
public function setManagement(?Management $management): self
{
$this->management = $management;
return $this;
}
public function getService(): ?Service
{
return $this->service;
}
public function setService(?Service $service): self
{
$this->service = $service;
return $this;
}
public function getFormat(): ?Format
{
return $this->format;
}
public function setFormat(?Format $format): self
{
$this->format = $format;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
Report.php
<?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\ReportRepository")
*/
class Report
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="date")
*/
private $assigned_date;
/**
* #ORM\Column(type="decimal", precision=7, scale=2, nullable=true)
*/
private $time;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Game", inversedBy="reports")
*/
private $game;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Management", inversedBy="reports")
*/
private $management;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Service", inversedBy="reports")
*/
private $service;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Format", inversedBy="reports")
*/
private $format;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="reports")
* #ORM\JoinColumn(nullable=false)
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="reports")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
public function getId(): ?int
{
return $this->id;
}
public function getAssignedDate(): ?\DateTimeInterface
{
return $this->assigned_date;
}
public function setAssignedDate(\DateTimeInterface $assigned_date): self
{
$this->assigned_date = $assigned_date;
return $this;
}
public function getTime()
{
return $this->time;
}
public function setTime($time): self
{
$this->time = $time;
return $this;
}
public function getGame(): ?Game
{
return $this->game;
}
public function setGame(?Game $game): self
{
$this->game = $game;
return $this;
}
public function getManagement(): ?Management
{
return $this->management;
}
public function setManagement(?Management $management): self
{
$this->management = $management;
return $this;
}
public function getService(): ?Service
{
return $this->service;
}
public function setService(?Service $service): self
{
$this->service = $service;
return $this;
}
public function getFormat(): ?Format
{
return $this->format;
}
public function setFormat(?Format $format): self
{
$this->format = $format;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
FormType
ReportType.php
<?php
namespace App\Form;
use App\Entity\Report;
use App\Entity\Game;
use App\Entity\Management;
use App\Entity\Service;
use App\Entity\Format;
use App\Entity\Category;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
class ReportType extends AbstractType
{
protected $tokenStorage;
public function __construct(TokenStorage $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->tokenStorage->getToken()->getUser();
$builder->add('assigned_date', DateType::class, array(
'widget' => 'single_text',
// prevents rendering it as type="date", to avoid HTML5 date pickers
'html5' => false,
// adds a class that can be selected in JavaScript
'attr' => ['class' => 'js-datepicker'],
));
$builder->add('time');
$builder->add('game', EntityType::class, array(
'class' => Game::class,
'placeholder' => '',
'choice_label' => 'name'));
$builder->add('management', EntityType::class, array(
'class' => Management::class,
'placeholder' => 'Select a management',
'mapped' => false,
'choice_label' => 'name'));
$builder->get('management')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event)
{
$form = $event->getForm();
$form->getParent()->add('service',EntityType::class, array(
'class' => Service::class,
'placeholder' => 'Select a service',
'choices' => $form->getData()->getServices()
));
}
);
$builder->add('format', EntityType::class, array(
'class' => Format::class,
'placeholder' => '',
'choice_label' => 'name'));
$builder->add('category', EntityType::class, array(
'class' => Category::class,
'placeholder' => '',
'choice_label' => 'name'));
$builder->add('user', EntityType::class, array(
'class' => User::class,
'query_builder' => function (EntityRepository $er) {
$user = $this->tokenStorage->getToken()->getUser();
return $er->createQueryBuilder('u')
->Where('u.id='. $user->getId());
},
'choice_label' => 'id',
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Report::class,
]);
}
}
Twig associated
_form.twig.php
<?php
namespace App\Controller;
use App\Entity\Report;
use App\Form\ReportType;
use App\Repository\ReportRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* #Route("/report")
*/
class ReportController extends AbstractController
{
/**
* #Route("/", name="report_index", methods="GET")
*/
public function index(ReportRepository $reportRepository): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser()->getId();
return $this->render('report/index.html.twig', ['reports' => $reportRepository->findAllByIdUser($user)]);
}
/**
* #Route("/new", name="report_new", methods="GET|POST")
*/
public function new(Request $request): Response
{
$report = new Report();
$form = $this->createForm(ReportType::class, $report);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($report);
$em->flush();
return $this->redirectToRoute('report_index');
}
return $this->render('report/new.html.twig', [
'report' => $report,
'form' => $form->createView(),
]);
}
/**
* #Route("/{id}", name="report_show", methods="GET")
*/
public function show(Report $report): Response
{
return $this->render('report/show.html.twig', ['report' => $report]);
}
/**
* #Route("/{id}/edit", name="report_edit", methods="GET|POST")
*/
public function edit(Request $request, Report $report): Response
{
$form = $this->createForm(ReportType::class, $report);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('report_edit', ['id' => $report->getId()]);
}
return $this->render('report/edit.html.twig', [
'report' => $report,
'form' => $form->createView(),
]);
}
/**
* #Route("/{id}", name="report_delete", methods="DELETE")
*/
public function delete(Request $request, Report $report): Response
{
if ($this->isCsrfTokenValid('delete'.$report->getId(), $request->request->get('_token'))) {
$em = $this->getDoctrine()->getManager();
$em->remove($report);
$em->flush();
}
return $this->redirectToRoute('report_index');
}
}
When I dump() my $form->getData()->getServices(), this return a collection. but i've this message : Neither the property "service" nor one of the methods "service()", "getservice()"/"isservice()"/"hasservice()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
on {{ form_widget(form.service, { 'attr': {'placeholder': "Service"} }) }}
Some people have a solution ?
I can provide more information if you need it
Thank you.
I have a scenario like this: Hmo has a bidirectional Many2Many association with Hcp. What i mean is Hmo can add Hcp, Hcp should be able to view its Hmos and view some other information about an Hmo.
I have already created several Hmos and Hcps so the actual association is when editing Hmos in order to select Hcps to make association i kept getting an error:
Argument 1 passed to Hmo\Entity\Hmos::addHcp() must be an instance of Hcp\Entity\Hcps, instance of Doctrine\Common\Collections\ArrayCollection given, called in /var/www/insta/vendor/doctrine/doctrine-module/src/DoctrineModule/Stdlib/Hydrator/Strategy/AllowRemoveByValue.php on line 61 and defined in /var/www/insta/module/Hmo/src/Hmo/Entity/Hmos.php on line 58
Hcps.php
<?php
namespace Hcp\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Hmo\Entity\Hmos;
/** #ORM\Entity */
class Hcps
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/** #ORM\Column(type="string") */
protected $name;
/** #ORM\Column(type="string") */
protected $address;
/** #ORM\Column(type="string") */
protected $telno;
/** #ORM\Column(type="string") */
protected $email;
/** #ORM\Column(type="string") */
protected $typeoffac;
/** #ORM\Column(type="string") */
protected $catofreg;
/** #ORM\Column(type="string") */
protected $sregno;
/** #ORM\Column(type="string") */
protected $directorname;
/** #ORM\Column(type="date", nullable=true) */
protected $regdate;
/** #ORM\Column(type="time", nullable=true) */
protected $regtime;
/** #ORM\Column(type="datetime", nullable=true) */
protected $regdatetime;
/** #ORM\Column(type="datetime", nullable=true) */
protected $lastlogin;
/**
*#var \Doctrine\Common\Collections\ArrayCollection
* #ORM\ManyToMany(targetEntity="Hmo\Entity\Hmos", mappedBy="hcp")
*/
protected $hmo;
public function __constructor()
{
$this->hmo = new ArrayCollection();
}
public function addHmo(Hmos $hmo)
{
if ($this->hmo->contains($hmo)) {
return;
}
$this->hmo->add($hmo);
$hmo->addHcp($this);
}
public function setHmo(Hmos $hmo = null)
{
$this->hmo = $hmo;
}
public function getHmo()
{
return $this->hmo;
}
public function setLastlogin($lastlogin)
{
$this->lastlogin = $lastlogin;
return $this;
}
public function getLastlogin()
{
return $this->lastlogin;
}
public function setRegDatetime($regdatetime)
{
$this->regdatetime = $regdatetime;
return $this;
}
public function getRegdatetime()
{
return $this->regdatetime;
}
public function setRegtime($regtime)
{
$this->regtime = $regtime;
return $this;
}
public function getRegtime()
{
return $this->regtime;
}
public function setRegdate($regdate)
{
$this->regdate = $regdate;
return $this;
}
public function getRegdate()
{
return $this->regdate;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getId()
{
return $this->id;
}
public function setDirectorname($directorname)
{
$this->directorname = $directorname;
return $this;
}
public function getDirectorname()
{
return $this->directorname;
}
public function setSregno($sregno)
{
$this->sregno = $sregno;
return $this;
}
public function getSregno()
{
return $this->sregno;
}
public function setCatofreg($cof)
{
$this->catofreg = cof;
return $this;
}
public function getCatofreg()
{
return $this->catofreg;
}
public function setTypeoffac($tof)
{
$this->typeoffac = $tof;
return $this;
}
public function getTypeoffac()
{
return $this->typeoffac;
}
public function setTelno($telno)
{
$this->telno = $telno;
return $this;
}
public function getTelno()
{
return $this->telno;
}
public function setAddress($address)
{
$this->address = $address;
return $this;
}
public function getAddress()
{
return $this->address;
}
public function setName($name)
{
$this->name = $name;
return $name;
}
public function getName()
{
return $this->name;
}
public function setEmail($email)
{
$this->email = $email;
return $email;
}
public function getEmail()
{
return $this->email;
}
public function populate($data = array())
{
$this->id = $data['id'];
$this->name = $data['name'];
$this->address = $data['address'];
$this->telno = $data['telno'];
$this->email = $data['email'];
$this->typeoffac = $data['typeoffac'];
$this->catofreg = $data['catofreg'];
$this->sregno = $data['sregno'];
$this->directorname = $data['directorname'];
}
}
Hmos.php
<?php
namespace Hmo\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Hcp\Entity\Hcps;
/** #ORM\Entity */
class Hmos
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/** #ORM\Column(type="string") */
protected $nameofhmo;
/** #ORM\Column(type="string") */
protected $headoffice;
/** #ORM\Column(type="string") */
protected $telno;
/** #ORM\Column(type="string") */
protected $email;
/** #ORM\Column(type="string") */
protected $doincor;
/** #ORM\Column(type="string") */
protected $rcno;
/** #ORM\Column(type="string") */
protected $ceoname;
/** #ORM\Column(type="string") */
protected $bankers;
/** #ORM\Column(type="date", nullable=true) */
protected $regdate;
/** #ORM\Column(type="time", nullable=true) */
protected $regtime;
/** #ORM\Column(type="datetime", nullable=true) */
protected $regdatetime;
/** #ORM\Column(type="datetime", nullable=true) */
protected $lastlogin;
/**
* #ORM\ManyToMany(targetEntity="Hcp\Entity\Hcps", inversedBy="hmo")
* #ORM\JoinTable(name="hmo_hcp",
* joinColumns={#ORM\JoinColumn(name="hmo_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="hcp_id", referencedColumnName="id")}
* )
*/
protected $hcp;
public function __constructor()
{
$this->hcp = new ArrayCollection();
}
public function addHcp(Hcps $hcp)
{
// $hcp->addHmo($this); // synchronously updating inverse side
//$this->hcp[] = $hcp;
// $this->hcp->add($hcp);
//return $this->hcp;
if ($this->hcp->contains($hcp)) {
return;
}
$this->hcp->add($hcp);
$hcp->addHmo($this);
}
public function removeHcp(Hcps $hcp)
{
$this->hcp->removeElement($hcp);
return $this;
}
public function setNameofhmo($hmo)
{
$this->nameofhmo = $hmo;
return $this;
}
public function getNameofhmo()
{
return $this->nameofhmo;
}
public function setHeadoffice($headoffice)
{
$this->headoffice = $headoffice;
return $this;
}
public function getHeadoffice()
{
return $this->headoffice;
}
public function setTelno($telno)
{
$this->telno = $telno;
return $this;
}
public function getTelno()
{
return $this->telno;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
public function getEmail()
{
return $this->email;
}
public function setDoincor($doincor)
{
$this->doincor = $doincor;
return $this;
}
public function getDoincor()
{
return $this->doincor;
}
public function setRcno($rc)
{
$this->rcno = $rc;
return $this;
}
public function getRcno()
{
return $this->rcno;
}
public function setCeoname($ceo)
{
$this->ceoname = $ceo;
return $this;
}
public function getCeoname()
{
return $this->ceoname;
}
public function setBankers($bk)
{
$this->bankers = $bk;
return $this;
}
public function getBankers()
{
return $this->bankers;
}
public function setLastlogin($lastlogin)
{
$this->lastlogin = $lastlogin;
return $this;
}
public function getLastlogin()
{
return $this->lastlogin;
}
public function setRegDatetime($regdatetime)
{
$this->regdatetime = $regdatetime;
return $this;
}
public function getRegdatetime()
{
return $this->regdatetime;
}
public function setRegtime($regtime)
{
$this->regtime = $regtime;
return $this;
}
public function getRegtime()
{
return $this->regtime;
}
public function setRegdate($regdate)
{
$this->regdate = $regdate;
return $this;
}
public function getRegdate()
{
return $this->regdate;
}
public function setId($id)
{
$this->id = $id;
return $this;
//die();
}
public function getId()
{
return $this->id;
}
public function populate($data = array())
{
$this->id = $data['id'];
$this->nameofhmo = $data['nameofhmo'];
$this->headoffice = $data['headoffice'];
$this->telno = $data['telno'];
$this->email = $data['email'];
$this->doincor = $data['doincor'];
$this->rcno = $data['rcno'];
$this->ceoname = $data['ceoname'];
$this->bankers = $data['bankers'];
}
public function setHcp(Hcps $hcp = null)
{
//Hmos $hmo = null
$this->hcp = $hcp;
return $this;
}
public function getHcp()
{
return $this->hcp;
}
}
HmohcpForm.php
class HmohcpForm extends Form{
public function __construct(ObjectManager $objectManager){
parent::__construct('filmForm');
$this->setAttribute('method','post')
->setHydrator(new DoctrineHydrator($objectManager,'\Hmo\Entity\Hmos'))
->setObject(new Hmos());
$this->add(array(
'name' => 'id',
'type' => 'hidden'
));
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'hcp',
'attributes' => array(
'multiple' => 'multiple',
'class'=>'form-control',
),
'options' => array(
'object_manager' => $objectManager,
'target_class' => 'HCP\Entity\Hcps',
'property' => 'name',
'label' => 'HCP: ',
),
)
);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Add HCPs to HMO',
'id' => 'submitbutton',
'class' => 'btn btn-primary',
),
));
}
hcptohmo.php
<?php
$form = $this->form;
$form->prepare();
$form->setAttribute('action', $this->url(NULL,
array('controller'=>'Index', 'action' => 'hcptohmos','id'=> $this->id)));
$form->setAttribute('method', 'post');
?>
<?php //echo $?>
<div class="row">
<article class="contact-form col-md-8 col-sm-7 page-row">
<h3 class="title">Register HMO</h3>
<?php echo $this->form()->openTag($form); ?>
<?php echo $this->formInput($form->get('id')); ?>
<div class="form-group name">
<?php
echo $this->formElement($form->get('hcp'));
?>
</div><!--//form-group-->
<?php
echo $this->formElement($form->get('submit'));
echo $this->formElementErrors($form->get('submit'));
?>
<?php echo $this->form()->closeTag() ?>
</article><!--//contact-form-->
</div>
IndexController.php
<?php
public function hcptohmoAction()
{
$id = $this->params()->fromRoute('id');
if(!$id) {
return $this->redirect()->toRoute('admin', array(
'action' => 'index'
));
}
$hu= $this->getEntityManager()->find('Hmo\Entity\Hmos',$id);
$form = new HmohcpForm($this->getEntityManager());
$form->bind($hu);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid())
{
$form->bindValues();
$entity = $form->getData();
print_r($entity->getHcp());
}
}
return new ViewModel(array('id'=>$id,'form' => $form));
}
I thought print_r($entity->getHcp()) is supposed to return an object of selected Hcps?
i have toggled the parameter of addHcp() to an arraycollection and Hcps but still shooting same error. is something wrong with this codes pls?
you should pass an ArrayCollection to the add-methods - I think that is the problem.
Modify your add-methods to look like this:
public function addHcp(Collection $hcps)
{
foreach($hcps as $hcp) {
if( ! $this->hcp->contains($hcp)) {
$this->hcp->add($hcp);
$hcp->addHmo(new ArrayCollection(array($this));
}
}
}
Also your remove-methods (the same way):
public function removeHcp(Collection $hcps)
{
foreach($hcps as $hcp) {
$this->hcp->removeElement($hcp);
$hcp->removeHmo(new ArrayCollection(array(this)));
}
}
Doctrine also passes Collections to the add-/remove-methods, that's why it is not working
I think the problem lies in your entity methods.
I would advice to read the documentation on the Doctrine ObjectHydrator and then you will most likely find out what goes wrong.
From a quick look I would say the mistake is in the setHcp and setHmo methods. Since you have a ManyToMany association you are not supposed to use set methods in your associations at all. Check the comment at setTags here in this chapter of the documentation. You should actually only use addHcps, addHcp, removeHcp and removeHcps methods.
Collections should never be swapped.