At first let’s make clear what is Magento application? Magento it’s a CMS (content management system) specially designed and developed for web stores creating, in other words it’s an e-commerce platform. And Magento application it is a component of this system that processes user request and returns the final result.
Recently we published an article dedicated to adding of image attribute to a category in Magento 2. So now, I’d like to share with another way that uses an amazing mechanism in Magento 2, that is called Plugin.
In order to add an image to a category, we have to perform the following steps:
- To add a required attribute to a category (by Setup during module installation);
- To create a controller, which will upload selected image;
- To expand category form, using ui_component (Magento 2 merges configuration files, which let you easily expand particular forms; app/code/BelVG/AdditionalImageTemplate/view/adminhtml/ui_component/category_form.xml);
- To implement a handler to a category saving event;
- Do not forget to wrap \Magento\Catalog\Model\Category\DataProvider::getData, using plugin system, for proper image attribute processing.
That’s all concerns backend works, so now let’s get down to frontend.
To display an image on the category page, it’s preferable when $category->getAdditionalImage() method is being called, it returns a link to the image, but not an attribute value. This is rather convenient for using in templates, that’s why we will create a plugin. It will wrap getData method in \Magento\Catalog\Model\Category models, and when getData is called with a key, which is an attribute, it will process and return the link to the image.
In order to easily navigate in code (link to that code is placed below) you should get acquainted with several parts of Magento 2 Developer Documentation:
To look through and download the source code, please check our github repository.