Getting the Original SKU of a Bundled Item in the Cart
When dealing with bundled products in Magento 2, retrieving the original parent ID or SKU for individual items purchased through bundles can indeed be complex. The info_buyRequest option that works for grouped products doesn’t provide this information for bundled items by default.
However, there are a few ways to achieve this using Magento’s observer and model structure:
Using an Observer to Track Bundled Items
One approach is to use a bundle product save after event observer. This allows you to track the parent bundle item when a simple product is saved within that bundle.
Here’s how you can create this observer:
<event name="catalog_product_bundle_item_save_after">
<observer name="save_bundle_item_after" instance="Vendor\Module\Model\Observer"/>
</event>
In your Observer class, you can retrieve the parent bundle product:
public function execute(\Magento\Framework\Event\Observer $observer)
{
$item = $observer->getProduct();
$bundleItem = $item->getBundleProduct();
if ($bundleItem instanceof \Magento\Catalog\Model\Product) {
$parentSku = $bundleItem->getSku();
// Perform additional tracking or operations with the parent SKU
}
return $this;
}
This observer will fire every time a simple product is saved within a bundle, allowing you to access and process the parent bundle SKU.
Retrieving Bundle Item Information During Checkout
If you need this information during the checkout process specifically, you can use Magento’s quote model. However, this requires more complex setup involving observers for quote items collection load events.
You would need to override the Magento\Quote\Model\Quote\Item class and add a custom method or attribute to store the original bundled SKU:
protected $_bundleSku;
public function setBundleSku($sku)
{
$this->_bundleSku = $sku;
}
public function getBundleSku()
{
return $this->_bundleSku;
}
Then, in your observer for quote_item_collection_load_after, you can populate this attribute:
public function execute(\Magento\Framework\Event\Observer $observer)
{
$collection = $observer->getCollection();
foreach ($collection as $item) {
if ($item->getProductType() === \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
$bundleItems = $item->getBundleSelectionItems();
// Process the bundle items to find the parent SKU and set it using $item->setBundleSku($parentSku);
}
}
return $this;
}
This approach allows you to access the original bundled SKU within each purchased item during checkout, but it requires more extensive customization of Magento’s core models.
Remember that these are advanced topics in Magento development. If you’re not comfortable with this level of customization or need further assistance, consider reaching out to a professional Magento 2 developer.
For more information on working with bundled products and observers in Magento 2, check out our comprehensive guide at Laravel Company.