I'm working with magento2, I have created custom add to cart product functionality. Now I want update product quantity. I have fetched all cart items and I want update but I am getting incorrect quantities of configurable child product. I have fetched quantity using $item->getQty() inside cart get all items it is working fine with normal product. But I get incorrect cart item quantity for child configurable product. Can we use any other way instead of $item->getQty() I have also configurable child product I'ds.
3 Answers
To get the children quantity you need to check if the item in the cart has children first then go through children, this code will show you how you can get the QTY of the children
if ($item->getHasChildren() ) {
foreach ($item->getChildren() as $child) {
// get child quantity by this calling $child->getQty();
}
}
where $item is the the cart item
this code works well for me, I hope it will help you.
-
Thanks for quick reply @wisam hakim suppose I have three child then there is no need to other conditions or check for perticular child product from your given code. Apr 18, 2018 at 4:00
-
usually in configurable product you will have only one child, the condition is needed in case you have two products in the cart, one is simple product and other is configurable, in this case you need the condition to not have any error in your code Apr 18, 2018 at 4:06
-
I have three child product with dropdown I hope given code will also work. Apr 18, 2018 at 5:14
may be it will work for more then one option
if ($item->getHasChildren() ) {
foreach ($item->getChildren() as $child) {
// get child quantity by this calling $child->getQty();
}
}
-
I have checked with given and my custom code if ($item->getHasChildren() ) { foreach ($item->getChildren() as $child) { $child_prod_id=$child->getProductId(); if($child_prod_id==$selected_configurable_option) { echo"qty".$itemqty1=$item->getQty();} } } Apr 18, 2018 at 5:51
-
but for first child it is working fine at all time updated cart item and add but for second child it work first time fine but when when i update second child i and get quantity from cart item and cart has only one qty but i get two quantity for second child at first update and after first update i have update 7 to 10 time it is working fine. only sesond time it get incorrect qty please check and let me know Apr 18, 2018 at 5:51
if you have the item object then you can directly fetch the child product from the items as follows; If you check for each quote item we have the record in the "quote_item_option" table and the details can be fetch using method "getOptionByCode('simple_product')"
foreach ($cart->getQuote()->getAllVisibleItems() as $item) {
$productId = $item->getProduct()->getId(); // parent product id
$childItemId = $item->getOptionByCode('simple_product')->getProduct()->getId(); // child product id
}
A very late answer but hope it helps others.