2

I have two phtml which have its own unique block file. I need to pass variable from one phtml to another.

PHTML 1

<?php 
$option_id = 20;
?>

<a href="<?php echo $baseUrl ?>/brandsmodules/index/demo" ></a>

PHTML 2

In this page is where I need to get the variable. I don't want to pass variables in URL as parameter due to security concerns.

4 Answers 4

1

You can send variable in URL like this to pass variable in another .phtml

In your PHTML 1

<?php $option_id = 20; ?>

<a href="<?php echo $this->getUrl('brandsmodules/index/demo', ['optionId' => $option_id]) ?>

In your PHTML 2

And you will get your optionId in another phtml by using $_GET['optionId'].

Please check and let me know if any question.

1
  • @RameshKR does this work for you ? Commented Feb 11, 2019 at 11:08
0

You can try

<?php echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setKey('dfd')->setTemplate("VendorName_ModuleName::fileName.phtml")->toHtml(); ?>

print your value as

$block->getKey();
0

Inside your block class add two method.

  1. setCustomData

  2. getCustomData


public function setCustomData($data)
{
    $this->registry->register('custom_data', $data);
}

public function getCustomData()
{
    return $this->registry->registry('custom_data');
}

From first phtml, you set data like:


$block->setCustomData(12);

and from 2nd phtml, you can get data like:


$data = $block->getCustomData();

add $this->registry using DI. For example:


public function __construct(
    \Magento\Framework\Registry $registry
) {
    $this->registry = $registry;
}
1
  • What if they are two different blocks? Commented Dec 30, 2021 at 13:59
0

In the first phtml .You can set the data in this way

<?= $block->getLayout()->createBlock(Vendor/ModuleName/Block/BlockFile::class)
    ->setTemplate("Vendor_ModuleName::template_file.phtml")
    ->setData('data', 10)
    ->toHtml() ?>

And In the second phtml ie (template_file.phtml) call the data in this way

 <?= $block->getData('data'); ?> //10

Hope it helps. Happy Coding !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.