How to get only list of products that are selected inside the bundle product in magento2 when we create a bundle product we can selects some products to attach in bundle products i just want to show these attached products on detail page
2 Answers
Below snippet code to get all the selection products of bundle product:
<?php
namespace Vendor\Module\Helper;
use Magento\Catalog\Model\ProductFactory;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var Magento\Catalog\Model\ProductFactory
*/
protected $_productFactory;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
ProductFactory $productFactory
) {
parent::__construct($context);
$this->_productFactory = $productFactory;
}
public function getBundleProductOptionsData()
{
$productId = 40; //any bundle product id
$product = $this->_productFactory->create()->load($productId);
//get all the selection products used in bundle product.
$selectionCollection = $product->getTypeInstance(true)
->getSelectionsCollection(
$product->getTypeInstance(true)->getOptionsIds($product),
$product
);
foreach ($selectionCollection as $proselection) {
$selectionArray = [];
$selectionArray['selection_product_name'] = $proselection->getName();
$selectionArray['selection_product_quantity'] = $proselection->getPrice();
$selectionArray['selection_product_price'] = $proselection->getSelectionQty();
$selectionArray['selection_product_id'] = $proselection->getProductId();
$productsArray[$proselection->getOptionId()][$proselection->getSelectionId()] = $selectionArray;
}
}
}
Let me know if this code is not working.
Try this
foreach ($collection as $item) {
$data[] = $item->getId().", ".$item->getTypeId().", - , ".$item->getSku().", ".$item->getPackSize().", ".$visibility.", ".$status.", ".$item->getPrice().", ".str_replace(',', '/',$item->getName()).", ";
$children = [];
if ($type == 'configurable') {
$children = $item->getTypeInstance()->getUsedProducts($item);
} elseif ($type == 'bundle') {
$children = $item->getTypeInstance(true)
->getSelectionsCollection($item->getTypeInstance(true)->getOptionsIds($item), $item)->getItems();
} elseif ($type == 'grouped') {
$children = $item->getTypeInstance(true)->getAssociatedProducts($item);
}
if($children) {
foreach ($children as $child) {
$data[] = $child->getId().", ".$child->getTypeId().", ".$item->getSku().", ".$child->getSku().", ".str_replace(',', '/',$child->getAttributeText('status')).", ".$child->getPrice().", ".str_replace(',' ".str_replace(',', '/',$child->getName()).", ";
}
}
}