getAllVisibleItems: Show Configurable Products & Hide Parent Products

getAllVisibleItems shows both configurable and parent products

In this post, we will show you simple tutorials to address this issue. By utilizing the ‘getAllVisibleItems’ function, we can tailor the product display to show only the configurable options while hiding parent products. Let’s get started!

PROBLEM:

The developer has a custom observer executing after “sales_order_place_after” that compiles a list of purchased items from the order and sends them to a third party.

This script worked fine in Magento 1, but when upgrading to Magento 2, it shows both the configurable product and its parent product being listed. Here is the code:

public function execute(\Magento\Framework\Event\Observer $observer) {
  $order = $observer->getOrder();
  foreach($order->getAllVisibleItems() as $item) {
    // Build XML
  }
}

The resulting XML looks like the following:

<item>
  <price>7.90</price>
  <sku>THE_SKU_NUMBER</sku>
  <qty>1</qty>
</item>
<item>
  <price>0.00</price>
  <sku>THE_SKU_NUMBER</sku>
  <qty>1</qty>
</item>

The issue here is duplicate items listed. So, is there a different function we can use to hide the parent product, and only show the configurable product actually purchased?

SOLUTIONS:

This is how to apply different methods to get the items from an order work:

  • getItems(): returns array of items from loaded order item collection
  • getAllItems(): returns array of all items that are not marked as deleted
  • getAllVisibleItems(): returns array of all items that are not marked as deleted and don’t have a parent item

Hence, in order to get only the configurable product without getting its parent product, getAllVisibleItems() is the correct method:

  • The single simple item doesn’t have a parent => Visible
  • The configurable item doesn’t have a parent => Visible
  • The associated simple item has a parent => Not visible
magento 2 getAllVisibleItems

After getting the SKU after each loop, you will get products.

private $productRepository;
...
public function __construct(
...
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
...
) {
...
$this->productRepository = $productRepository;
    ...
}
$item = $order->getAllVisibleItems();
foreach ($item as $item){
    if($item->getProductType() == 'configurable'){
        $sku = $item->getProductOptions()['simple_sku'];
        $product = $this->productRepository->get($sku);
    }
}

We have shown you an easy way to show the configurable products only when implementing the getAllVisibleItems function in Magento 2. If you have any problems when following the instruction, please leave a comment below. See you in the next tutorial!

See More:

How To Protect Original Product Images In Magento 2?

Magento 2 Tutorials – From A to Z For Beginners

Leave a Reply

Your email address will not be published. Required fields are marked *