\Magento\Framework\Registry is the class to get and set the value of the custom attribute in Magento2.
However, you can use registry method to get information about the current Product, Category, CMS Page.
You can add the below code in your custom module block file.
for example
app/code/VR/CustomModule/Block/CustomBlock.php
1234567891011121314151617181920212223242526272829303132333435363738 <?php
namespace
VR\CustomModule\Block;
class
CustomBlock
extends
\Magento\Framework\View\Element\Template
{
protected
$_registry
;
public
function
__construct(
\Magento\Backend\Block\Template\Context
$context
,
\Magento\Framework\Registry
$registry
,
array
$data
= []
)
{
$this
->_registry =
$registry
;
parent::__construct(
$context
,
$data
);
}
public
function
_prepareLayout()
{
return
parent::_prepareLayout();
}
public
function
getCurrentCategory()
{
return
$this
->_registry->registry(
'current_category'
);
}
public
function
getCurrentProduct()
{
return
$this
->_registry->registry(
'current_product'
);
}
public
function
getCurrentPage()
{
return
$this
->_registry->registry(
'current_cms_page'
);
}
}
?>
Now by using above functions in your .phtml file, you can get information about current product as well as current category.12345678910111213 /*for product*/
$currentProduct
=
$block
->getCurrentProduct())
echo
$currentProduct
->getName() . '
';
echo
$currentProduct
->getSku() . '
';
echo
$currentProduct
->getId() . '
';
/*for category*/
$currentCategory
=
$block
->getCurrentCategory())
You can use your own logic as per above code to achieve your functionality.
Below code will be used to registry / register / unregister value of your custom attribute in custom module.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | /** * @var \Magento\Framework\Registry */ protected $_registry ; /** * ... * ... * @param \Magento\Framework\Registry $registry, */ public function __construct( ..., ..., \Magento\Framework\Registry $registry , ... ) { $this ->_registry = $registry ; ... ... } /** * Setting custom variable in registry to be used * */ public function setCustomVariable() { $this ->registry->register( 'custom_var' , 'Added Value' ); } /** * Retrieving custom variable from registry * @return string */ public function getCustomVariable() { return $this ->registry->registry( 'custom_var' ); } public function getCustomVariable() { return $this ->registry->unregister( 'custom_var' ); } |
Tag :
Magento2
0 Comments On "How to use Registry & Register in Magento2"