Reputation: 422
I have a Wishlist entity, which has relationship with a Product entity using MTM Doctrine annotation.
I have the definition that $products
is an Array Collection
In Wishlist's __construct() and that's why I have addProduct()
and removeProduct()
methods.
So, the class has the following view:
<?php
namespace WishlistBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use ShopBundle\Entity\Product;
/**
* Wishlist
*
* @ORM\Table(name="wishlist")
* @ORM\Entity()
*/
class Wishlist
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="ShopBundle\Entity\Product")
* @ORM\JoinTable(
* name="mtm_products_in_wishlists",
* joinColumns={
* @ORM\JoinColumn(
* name="wishlist_id",
* referencedColumnName="id"
* )
* },
* inverseJoinColumns={
* @ORM\JoinColumn(
* name="product_id",
* referencedColumnName="id",
* unique=true
* )
* }
* )
*/
private $products;
...
/**
* @param Product $product
*/
public function addProduct(Product $product)
{
$this->products->add($product);
}
/**
* @param Product $product
*/
public function removeProduct(Product $product)
{
$this->products->remove($product);
}
/**
* Get products.
*
* @return string
*/
public function getProducts()
{
return $this->products;
}
/**
* Wishlist constructor.
*/
public function __construct()
{
$this->products = new ArrayCollection();
}
}
In my Controller, I have a place where I try to use removeProduct()
method. I use it in the following way:
$wishlist->removeProduct($product);
But I receive the following error:
Warning: Illegal offset type in isset or empty (500 Internal Server Error)
It is at the line in
vendor\doctrine\collections\lib\Doctrine\Common\Collections\ArrayCollection.php at line 126
It has the following view:
public function remove($key)
{
if ( ! isset($this->elements[$key]) && ! array_key_exists($key, $this->elements)) {
return null;
}
}
At the same time, addProduct()
works fine.
What do I do wrong? How can this issues be solved?
Upvotes: 1
Views: 1818
Reputation: 2654
NOTE: You are using ArrayCollection
.
/**
* @param Product $product
*/
public function addProduct(Product $product)
{
$this->products->add($product);
}
/**
* @param Product $product
*/
public function removeProduct(Product $product)
{
$this->products->removeElement($product);
}
Upvotes: 1
Reputation: 4582
What you are looking for is ArrayCollection's removeElement($element)
function and not remove($key)
function.
As indicated by their definitions remove($key)
function removes the element at the specified index ($key) from a collection, while removeElement($element)
removes the specified element from the collection, if it is found.
Since you are trying to remove a product as an element and not by its index you should use removeElement($product)
.
Doctrine ArrayCollection API Reference here
Upvotes: 13