0

I'm trying to get parent products id for child products but i'm getting empty result.

<?php


namespace CustomColumn\Addproductcolumn\Ui\Component\Listing\Column;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Ui\Component\Listing\Columns\Column;

class ParentProductId extends Column
{
    protected $configurable;
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $configurable,
        array $components = [],
        array $data = []
    ) {
        parent::__construct($context, $uiComponentFactory, $components, $data);
        $this->_configurable = $configurable;
    }

    public function prepareDataSource(array $dataSource)
    {

        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$items) {

            if($items['type_id'] == 'simple'){

                $productId = $items['entity_id'];
                $getParent = $this->_configurable->getParentIdsByChild($productId);

                if($getParent){
                    $items['parentid_col'] = $getParent[0];
                }else{
                    $items['parentid_col'] = "nothing found";
                }
            }
        }
    }
        return $dataSource;
    }
}
?>
1

You should try

For Configurable Product

\Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurable;

$this->_configurable->getParentIdsByChild($productId);

For Bundle Product

\Magento\Bundle\Model\ResourceModel\Selection $bundleSelection;

$this->bundleSelection->getParentIdsByChild($productId);

Also please make sure that you are getting correct simple product ID which is assigned to Configurable product.

2
  • Thanks, it's working for Configurable product, do you know how to get the bundle products? – Tajveez Rehman Jan 3 '19 at 6:52
  • Please check my updated answer for Bundle product as well. – Abhishek Panchal Jan 3 '19 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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