InsideDarkWeb.com

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

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.

Magento Asked by sandip on February 14, 2021

2 Answers

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!

Related Questions

Magento 2 Access-Control-Allow-Origin

2  Asked on September 9, 2020 by borche-glafche

   

Magento 2: what is the catalog_attributes.xml file?

2  Asked on September 7, 2020 by raphael-at-digital-pianism

       

magento 2 – modify db_schema.xml field length

1  Asked on September 4, 2020 by sairaj-gadekar

 

Magento 2.3.2 Upgrade to 2.4

2  Asked on September 4, 2020 by hatim

 

Magento 2: Make sales without stock

1  Asked on August 9, 2020 by hudson-alves-triunfante

     

Magento 2 : print_r or var_dump is not working

4  Asked on July 30, 2020 by zed-blackbeard

   

Create quick order form at product page

0  Asked on July 29, 2020 by faraz-bashir

   

How to Special price based on attribute?

2  Asked on July 26, 2020 by user90560

     

is creating block within template in magento 2 good practice

0  Asked on July 24, 2020 by herve-tribouilloy

       

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.