Magento 2 How to pass custom parameters to Block?

Hello everyone,

In this blog, I am going to tell you guys how you can send your custom parameter to your block when you want to create the block using createBlock method from the controller.

There might be a use case where you want your custom widget to be non-cacheable, in that case ideally you would go with the approach of making an Ajax call and getting the updated html content every time when the widget code is triggered.

Ideally, you can get the widget’s configuration from the widget’s block file but in your case, the HTML content is coming from a different template and block file where you don’t get access to this data.

So in this case send these values as params in the Ajax call, then perform the below steps as mentioned.

Step 1: Create a Block in the controller

$products = $layout->createBlock('Sandesh\CustomModule\Block\Items')

Step 2: Inside your block create two methods

Inside your block Define a global variable like $this->widgetParams and create a method called setWidgetParams($params) which takes params coming from Ajax request as input.

public function setWidgetParams($widgetParams)
    $this->widgetParams = $widgetParams;
    return $this;

public function getWidgetParams()
    return $this->widgetParams;

Step 3: Use the get method in the template.

Now you can call the getWidgetParams() method in your template to access the global variable.

<?= $block->getWidgetParams() ?>

So the logic used behind this approach is very simple when you try to create a block using createBlock() method it returns the instance(object) of that Block class, through that, you can call your custom method defined in that Block and you can use the PHP’s global variable concept and set the value to that variable.

I hope you got to learn something after reading this. Feedback is appreciated. Thanks!!!

Leave a Comment

Your email address will not be published. Required fields are marked *