Magento – Get Tax class name from id in magento2

magento2taxtax-class

I have used below code to get tax class name from id.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$taxClassObj = $objectManager->create('Magento\Tax\Model\TaxClass\Source \Product');

$taxid = 2;
echo $taxName =  $taxClassObj->getOptionText($taxid);

This returns the Options text from id that is "Taxable Goods"

How to get the Id from Text?

Can we get Tax class id(value) from the tax class name?

Can anyone look into this and update your thoughts. thanks

Best Answer

I use this in a plugin but shoud work in every class:

<?php
namespace Vendor\Module\Plugin;

use Magento\Tax\Api\Data\TaxClassKeyInterface;

class PluginName
{
    ....

    public function __construct(
        \Magento\Tax\Api\TaxClassManagementInterface $taxClassManagementInterface,
        \Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory $taxClassKeyDataObjectFactory,
        \Psr\Log\LoggerInterface $logger
    )
    {
        $this->taxClassManagementInterface = $taxClassManagementInterface;
        $this->taxClassKeyDataObjectFactory = $taxClassKeyDataObjectFactory;
        $this->logger = $logger;
    }

    ....

    public function getTaxClassId($clasName){
        $taxClassId = $this->taxClassManagementInterface->getTaxClassId(
            $this->taxClassKeyDataObjectFactory->create()
                ->setType(TaxClassKeyInterface::TYPE_NAME)
                ->setValue($clasName)
        );
        return $taxClassId;
    }

    ....
}
Related Topic