A “Category Chooser” in Magento 2 Backend

Mar 16, 2017805Mishel Soiko
A “Category Chooser” in Magento 2 Backend

Let’s imagine, you need to create a category chooser for magento admin panel. For example, this might be necessary in the following cases:

1. To be used for some standard form as follows:

2. For some backend configurations:

3. Or, like in my case, for some widgets:

So, let’s consider how it is possible to arrange that. Magento source code offers us several solutions but we have selected the simplest one to use. First off, we write down the code for the element itself:

But that is only a form’s input. Now, let’s write down some html and javascript code to output the chooser in the backend and let it perform properly:

So, this is the Multi Category Chooser. But what if we need only one category? For such case there is a ready-made solution available, so we do not need to invent anything new:

This solution I have applied for one of my widgets, but it is also possible to adapt it for configuring various form elements.

 



9 Comments

  1. Dear Daniel,

    the code is above, in the article. Just put it into your module.
    In this case, we used the code from one of the client’s projects; the module where this code was created is more extensive.

    Regards,
    Mishel

  2. Can you please specify the file names as suggested above because that will really help a lot for creating the new type and used in the form.

  3. Hi Roshan,
    The article describes the creation of one file: [Vendor]\[Modul]\Block\Adminhtml\[Chooser], which is a form element. All these blocks are similar – there are plenty of examples. Do not be lazy and try to explore it yourself: \Magento\Config\Block\System\Config\*. There are three examples of adding fields to a form described at the beginning of the article. Each of the examples is used in many of the modules in default Magento.

  4. Hello!It’s a very good approach. Can you explain why the only available categories to choose are only the NON anchor categories?

  5. Hi Kosta,
    We see that the queries are sent to ‘adminhtml/widget_instance/categories’. Here is what’s inside: http://joxi.ru/8AnJXpjij91JOA. It’s all in your hands. Change the sent ajax parameters (parameters : postParameters). This must help.

Post a new comment

top
BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *