A case when Magento Plugin get a stalemate

Mobeen Sarwar
mobeensarwar
Published in
2 min readJan 1, 2022

A plugin is a class that modifies the behavior of public class functions. For a Magento developer, it’s the first approach to add a new feature, modify the existing ones,s and while fixing some bugs or issues.

But there are some cases when we got stuck in a stalemate while developing a plugin and can’t get the desired results.

Let’s suppose we want to change search results in quick search suggestions and we decided to use after plugin for this.

After plugin is used to modify the original result of the method and to execute some required business logic depending upon the result.

This Magento class is responsible to render search suggestions.

In PHPStrom press Ctrl + Shift + N , paste \Magento\Search\Controller\Ajax\Suggest and Hit Enter

Let’s create an after plugin for this method

1- Add plugin entry to frontend/di.xml of your module:

2- Create an after plugin class for the target class:

If we check the $result variable by adding a breakpoint using XDebug, we’ll find that search suggestions are set in JSON format

Now here's the main point:

Even we have created an after plugin, we can’t get this JSON data.

This looks amazing that in an after plugin we are supposed to get the return result of the parent method but we can not get it.

Reason:

The reason is the $result is an object of this class: \Magento\Framework\Controller\Result\Json. And this class didn’t have any method to get JSON Data.

Give it a try, and you’ll be stuck there

--

--