Reputation: 97
I program shopping cart in Doctrine and Nette Framework.
There is addItem
method: (add to session cart)
public function addItem($item) {
$cart = $this->getCartSection();
$product = $this->product_facade->getProduct($item['voucher_id']);
if (isset($cart->cart_items[$product->getId()])) {
$cart->cart_items[$product->getId()]['amount'] += $item['amount'];
} else {
$cart->cart_items[$product->getId()] = array(
'voucher' => $product,
'amount' => $item['amount']
);
}
}
And there is a method for add order to db
public function add($creator, $data) {
$order = new Orders();
$order->setPrice($data['price']);
$order->setStatus($this->status_facade->getStatus(self::NEW_STATUS_ID));
$order->setPayment($this->payment_facade->getPayment($data->payment));
$order->setDate(new DateTime());
$order->setUser($creator);
foreach ($data['cart'] as $item) {
$order_product = new OrdersProduct();
$order_product->setQuantity($item['amount']);
$order_product->setProduct($item['voucher']);
$order->addItem($order_product);
}
$this->em->persist($order);
$this->em->flush();
}
I get error after click to button 'add to order'
Undefined index: 00000000659576f8000000004032b93e
But I know where is a error. There is a method add
and this method gets Product entity from session.
$order_product->setProduct($item['voucher']);
I need product entity in session becuase I want count total price in cart.
If I call in add method setProduct
with number or $item['voucher']->getId()
(this variable is entity from Product
)
$order_product->setProduct(
$this->product_facade->getProduct(4)
);
It's OK, but I don't know, why I call product entity from session is wronk. This is same method with same result.
Can you help me with problem? Do you know why is wronk?
Thank you, I hope You understand me.
Upvotes: 0
Views: 214
Reputation: 11
Actually you can store an entity in a session. You can read more in Doctrine docs:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/entities-in-session.html
When retrieving an entity from a session you need to call merge
on your EntityManager
$entity = $this->em->merge($entityFromSession);
Upvotes: 0
Reputation: 690
You can't save entities into session. Doctrine uses Identity Map.
Save only entity ID to session and read the entity from database before working with it. If you need more data in session, don't use entity for that. Reather implement DTO.
Upvotes: 1