I am attempting to override the __construct
method in the Magento\Catalog\block\Product\View
block so that I can access the Magento\Eav\Model\Entity\Attribute\SetFactory
to get the AttributeSetName
of a product in the addtocart.phtml
. However, I keep running into a 404 Error.
I created a module and extended the Magento\Catalog\Block\Product\View
class.
namespace MyVendor\MyModule\Block\Product;
use Magento\Catalog\Block\Product\View as BaseView;
class View extends BaseView {
protected $_attributeSetFactory;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Framework\Url\EncoderInterface $urlEncoder,
\Magento\Framework\Json\EncoderInterface $jsonEncoder,
\Magento\Framework\Stdlib\StringUtils $string,
\Magento\Catalog\Helper\Product $productHelper,
\Magento\Catalog\Model\ProductTypes\ConfigInterface $productTypeConfig,
\Magento\Framework\Locale\FormatInterface $localeFormat,
\Magento\Customer\Model\Session $customerSession,
ProductRepositoryInterface $productRepository,
\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
\Magento\Eav\Model\Entity\Attribute\SetFactory $attributeSetFactory,
array $data = []
) {
$this->_attributeSetFactory = $attributeSetFactory;
parent::__construct(
$context,
$urlEncoder,
$jsonEncoder,
$string,
$productHelper,
$productTypeConfig,
$localeFormat,
$customerSession,
$productRepository,
$priceCurrency,
$data
);
}
/**
* Add meta information from product to head block
*
* @return \Magento\Catalog\Block\Product\View
*/
protected function _prepareLayout()
{
parent::_prepareLayout();
}
}
In the Magento\view\frontend\templates\product\view\addtocart.phtml
template I wasn't sure if I had to change the line /** @var $block \Magento\Catalog\Block\Product\View */
to reference my block instead of the core block either.
Snippet from MyVendor\MyModule\view\frontend\templates\product\view\addtocart.phtml
:
...
/** @var $block \Magento\Catalog\Block\Product\View */
?>
<?php $_product = $block->getProduct(); ?>
<?php echo $block->getAttributeSetName(); ?>
<?php $buttonTitle = __('Add to Cart'); ?>
...
After reading documentation I do not think I am injecting the factory correctly in the construct because before getting the 404 error I was having issues with the order the parameters are passed in the __construct
. However, after I cleared the cache I get the 404 error. Any help and direction would greatly be appreciated.
This is my di.xml
file:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Block\Product\View" type="MyVendor\MyModule\Block\Product\View" />
</config>