Verify Downloadable product type by product object in Magento 2 using SKU or by id.
You can retrieve product objects by the Product Repository interface in the Model Class and use the getTypeId() method to check the type of product.
use const from the Magento\Downloadable\Model\Product\Type class to get type id of TYPE_DOWNLOADABLE for the product.
<?php namespace Jesadiya\ProductType\Model; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Downloadable\Model\Product\Type; use Magento\Framework\Exception\NoSuchEntityException; use Psr\Log\LoggerInterface; class DownloadableType { /** * @var LoggerInterface */ private $logger; /** * @var ProductRepositoryInterface */ private $productRepository; public function __construct( LoggerInterface $logger, ProductRepositoryInterface $productRepository ) { $this->logger = $logger; $this->productRepository = $productRepository; } /** * Check type of product * * @return bool|null */ public function hasDownloadableType(string $sku) { $isDownloadableType = null; try { $product = $this->productRepository->get($sku); if ($product->getTypeId() === Type::TYPE_DOWNLOADABLE) { $isDownloadableType = true; } } catch (NoSuchEntityException $exception) { $this->logger->error($exception->getMessage()); } return $isDownloadableType; } }
If you have product id available you need to call product repository with getById($productId) in the above method instead of get($sku).
Call from the template or any PHP class,
$sku = '240-LV09'; $isDownloadable = $this->hasDownloadableType($sku);
Output:
boolean