Passing Variables Between .phtml Files in Magento2
Hello developers! Today we’re going to tackle a common question for those new to Magento2 - how to pass variables from one .phtml file to another.
The Challenge: Sharing Data Across Modules
You have two modules, each with its own .phtml file. You want to share data (an array variable called $transactions) between these files. Here’s a breakdown of your current setup:
File 1 - transactions.phtml
- Located in
/var/www/html/MyProject/app/design/frontend/Megnor/mag110246_4/Lof_CustomerMembership/templates/customer/membership/transactions.phtml - Contains the
$helper,$transactions, and$addressvariables. - Uses object manager to get customer session details.
File 2 - info.phtml
- Located in
/var/www/html/MyProject/app/design/frontend/Megnor/mag110246_4/Magedelight_SMSProfile/templates/account/dashboard/info.php - Needs access to the
$transactionsarray from file 1.
The Solution: Block Class and Template
To pass data between .phtml files, you can use a block class associated with your template. Here’s how:
Step 1 - Create the Block Class
In your module (Lof_CustomerMembership in this case), create a new block class under app/code/Lof/CustomerMembership/Block:
class Membership extends \Magento\Framework\View\Element\Template
{
protected $_transactions;
protected $helper;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
array $data = [],
\Lof\CustomerMembership\Helper\Data $helper
) {
parent::__construct($context, $data);
$this->helper = $helper;
}
public function getTransactions()
{
if (is_null($this->_transactions)) {
// Your logic to fetch transactions here
$this->_transactions = 'Your array data from the helper';
}
return $this->_transactions;
}
}
Step 2 - Use the Block in Template
In your transactions.phtml file, use the block class:
<?php
/** @var \Magento\Customer\Block\Account\Dashboard\Address $block */
$helper = $this->getHelper('Lof\CustomerMembership\Helper\Data');
$address = $this->getPrimaryBillingAddress();
/* Get transactions using the new block */
$transactions = $block->getTransactions();
Step 3 - Access Data in Second Template
In your info.phtml file, you can now access $transactions:
<?php
/** @var \Magento\Customer\Block\Account\Dashboard\Address $block */
$helper = $this->getHelper('Lof\CustomerMembership\Helper\Data');
/* Access transactions array */
$transactions = $block->getTransactions();
Conclusion
By creating a block class and using it in your .phtml files, you’ve successfully shared data between them. This approach is cleaner, safer, and more efficient than using object manager directly.
Remember to always follow best practices like avoiding direct object manager usage for dependency injection. If you need further assistance with Magento2 development, feel free to explore our Magento Development Services at Laravel Company.
Stay tuned for more tips on improving your Magento skills!