Magento2 - Magento 2 How To Call Any Block Function in PHTML
Magento2 - Magento 2 How To Call Any Block Function in PHTML
What's the deal with Deno? We talk with a major contributor to find out. Listen now.
How can I call any block function in any phtml? For example if I want to call my custom block
function in product list.phtml?
37
magento2 blocks template
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
<?php
our Terms namespace
of Service. Company\Helloworld\Block;
https://magento.stackexchange.com/questions/121364/magento-2-how-to-call-any-block-function-in-phtml 1/4
1/10/2020 magento2 - magento 2 how to call any block function in phtml - Magento Stack Exchange
use Magento\Framework\View\Element\Template;
then in any phtml file you can use following code to get method of this block.
<?php
$blockObj= $block->getLayout()->createBlock('Company\Helloworld\Block\Main');
echo $blockObj->getMyCustomMethod();
?>
And you have a public method myMethod() defined in Vendor\Module\Block\Name you can call the
following in name.phtml :
$block->myMethod();
You need to assign your block to the template.phtml in layout file. Then only you can call your own function
in phtml. – Aman Srivastava Jun 17 '16 at 9:30
Place your block File in the root directory of your module /Block/Your_block_file.php(remember to
user first capital Letter for folder and file).
0
App/Code/Your/Module/Block/Your_block_file.php
<?php
namespace Your\Module\Block;
/**
* Get form action URL for POST booking request
*
* @return string
*/
public function getFormAction()
{
die('Hello World');
}
}
Then link your block file with template in view/frontend/layout/your_file.xml file you defined the
block file
<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.x
<head>
<title
By using our site, you >{Page Title
acknowledge that</title
you > read and understand our Cookie Policy, Privacy Policy, and
have
</head>
our Terms of Service
<body>
.
https://magento.stackexchange.com/questions/121364/magento-2-how-to-call-any-block-function-in-phtml 3/4
1/10/2020 magento2 - magento 2 how to call any block function in phtml - Magento Stack Exchange
<referenceContainer name="content">
<block class="Your/Module/Block/Your_block_file" name="gridpage.form"
template="Your_Module:: your_template.phtml"/>
</referenceContainer>
</body>
</page>
0 <?php
$blockName = $block->getLayout()-
>createBlock('Vendor\Module\Block\your_block_file_name');
echo $blockName -> yourBlockFileMethodName();
?>
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.
https://magento.stackexchange.com/questions/121364/magento-2-how-to-call-any-block-function-in-phtml 4/4