Magento 2.4.6

I am trying to get the simple product of a configurable product when a product is added to the cart. I am listening to the checkout_cart_product_add_after event. This is what I have so far:

$item = $observer->getEvent()->getData('quote_item');
$item = ($item->getParentItem() ? $item->getParentItem() : $item);
$logger->info('item: ' . $item->getName());

This however, always gives me the name of the configurable, not the child simple products name. No matter what I try to access, its always the data from the parent configurable. Any ideas whats wrong here?


2 Answers 2

  • To access the child simple product's data, you need to make use of the getOptionByCode method.

  • By using the getConfigurableOptions method, you can retrieve the selected options for the configurable product.

  • Assuming there's only one configurable attribute, the first option's value will represent the child product's ID. You can then load the child product using getUsedProductById and access its name using $childProduct->getName().

  • This approach should give you the name of the child simple product instead of the parent configurable product.

Here is the example code,

$item = $observer->getEvent()->getData('quote_item');
$item = ($item->getParentItem() ? $item->getParentItem() : $item);

// Get the selected options for the configurable product
$options = $item->getProduct()->getTypeInstance()->getConfigurableOptions($item->getProduct());

// Get the first option (assuming there's only one configurable attribute)
$selectedOption = reset($options);

// Get the child product's ID
$childProductId = $selectedOption['value'];

// Load the child product
$childProduct = $item->getProduct()->getTypeInstance()->getUsedProductById($childProductId);

// Access the child product's name
$childProductName = $childProduct->getName();

$logger->info('Child Product Name: ' . $childProductName);

You should be able to do the following

$item = $observer->getEvent()->getData('quote_item');
if ($item->getHasChildren() ) {
    foreach ($item->getChildren() as $child)  $logger->info('item: ' . $child->getName());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.