TransWikia.com

Magento 2: Get all product types pro-grammatically in system admin?

Magento Asked by sandip on February 14, 2021

Magento 2 provides product types as simple, bundle, configurable, grouped, gift card, etc.

Is there any way programmatically to fetch all the product types which exist in the Magento codebase including custom product type also?

This should probably scan the product-type.xml which is located in the respective module.

2 Answers

Refer below code can be useful in any class.

use MagentoCatalogApiProductTypeListInterface;
use MagentoCatalogModelProductTypesConfigInterface;

Below code for construct method.

public function __construct(
     ConfigInterface $productTypeConfig,
     MagentoCatalogApiDataProductTypeInterfaceFactory $productTypeFactory
) {
     $this->productTypeConfig = $productTypeConfig;
     $this->productTypeFactory = $productTypeFactory;
}

Core function to get all product types

public function getProductTypes()
{
    if ($this->productTypes === null) {
        $productTypes = [];
        foreach ($this->productTypeConfig->getAll() as $productTypeData) {
            /** @var MagentoCatalogApiDataProductTypeInterface $productType */
            $productType = $this->productTypeFactory->create();
            $productType->setName($productTypeData['name'])
                ->setLabel($productTypeData['label']);
            $productTypes[] = $productType;
        }
        $this->productTypes = $productTypes;
    }
    return $this->productTypes;
}

Refer: /app/code/Magento/Catalog/Model/ProductTypeList.php

Correct answer by MageSoftech on February 14, 2021

Cleaner way: inject MagentoCatalogModelProductType and call toOptionArray()

Answered by Robert Schmidt on February 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP