In this blog, you will learn about how can add custom group and custom fields on the category Edit page in Magento 2.
Step-1: You need to create your own custom module such as Webiators_CustomGroup
Here Webiators is our Vendor Name and CustomGroup
After creating your custom module you will have to follow these steps below to create Magento 2 Custom Group And Fields On Category Edit Page.
Step – 2: Create InstallData.php file in the directory path app/code/Webiators/CustomGroup/Setup
After Creating InstallData.php, you need to add the code given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<?php namespace Webiators\CustomGroup\Setup; use Magento\Eav\Setup\EavSetup; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface; class InstallData implements InstallDataInterface { private $_eavSetupFactory; protected $categorySetupFactory; public function __construct( EavSetupFactory $eavSetupFactory, \Magento\Catalog\Setup\CategorySetupFactory $categorySetupFactory ) { $this->_eavSetupFactory = $eavSetupFactory; $this->categorySetupFactory = $categorySetupFactory; } public function install( ModuleDataSetupInterface $setup, ModuleContextInterface $context ) { /** @var EavSetup $eavSetup */ $eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]); $setup = $this->categorySetupFactory->create(['setup' => $setup]); $setup->addAttribute( \Magento\Catalog\Model\Category::ENTITY, 'banner_image', [ 'type' => 'varchar', 'label' => 'Category Banner', 'name' => 'Category Banner', 'input' => 'image', 'backend' => 'Magento\Catalog\Model\Category\Attribute\Backend\Image', 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE, 'visible' => true, 'required' => false, 'user_defined' => true, 'group' => 'Category Banner', ] ); $setup->addAttribute( \Magento\Catalog\Model\Category::ENTITY, 'is_banner_active', [ 'type' => 'int', 'label' => 'Enable Catgeory Banner', 'name' => 'Enable Catgeory Banner', 'input' => 'boolean', 'backend' => '', 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE, 'visible' => true, 'required' => false, 'user_defined' => true, 'group' => 'Category Banner', ] ); } } |
Step -3: Create category_form.xml file in the directory path app/code/Webiators/CustomGroup/view/adminhtml/ui_component and add this code given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<?xml version="1.0" encoding="UTF-8"?> <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> <fieldset name="category_banner" sortOrder="80"> <settings> <collapsible>true</collapsible> <label translate="true">Catgeory Banner</label> </settings> <field name="is_banner_active" sortOrder="10" formElement="checkbox"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="source" xsi:type="string">category</item> <item name="default" xsi:type="number">0</item> </item> </argument> <settings> <validation> <rule name="required-entry" xsi:type="boolean">false</rule> </validation> <dataType>boolean</dataType> <label translate="true">Enable Catgeory Banner</label> </settings> <formElements> <checkbox> <settings> <valueMap> <map name="false" xsi:type="string">0</map> <map name="true" xsi:type="string">1</map> </valueMap> <prefer>toggle</prefer> </settings> </checkbox> </formElements> </field> <field name="banner_image" sortOrder="40" formElement="imageUploader"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="source" xsi:type="string">category</item> </item> </argument> <settings> <elementTmpl>ui/form/element/uploader/image</elementTmpl> <dataType>string</dataType> <label translate="true">Banner Image</label> <visible>true</visible> <required>false</required> </settings> <formElements> <imageUploader> <settings> <required>false</required> <uploaderConfig> <param xsi:type="url" name="url" path="catbanner/category_image/upload"/> </uploaderConfig> <previewTmpl>Webiators_CustomGroup/image-preview</previewTmpl> <openDialogTitle>Media Gallery</openDialogTitle> <initialMediaGalleryOpenSubpath>catalog/category</initialMediaGalleryOpenSubpath> <allowedExtensions>jpg jpeg gif png</allowedExtensions> <maxFileSize>4194304</maxFileSize> </settings> </imageUploader> </formElements> </field> </fieldset> </form> |
Step – 4: Create image-preview.html file in the directory path app/code/Webiators/CustomGroup/view/adminhtml/web/template and code given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<div class="file-uploader-summary"> <div class="file-uploader-preview image-uploader-preview"> <a class="image-uploader-preview-link" attr="href: $parent.getFilePreview($file)" target="_blank"> <div class="file-uploader-spinner image-uploader-spinner" /> <img class="preview-image" tabindex="0" event="load: $parent.onPreviewLoad.bind($parent)" attr=" src: $parent.getFilePreview($file), alt: $file.name, title: $file.name"> </a> <div class="actions"> <button type="button" class="action-remove" data-role="delete-button" attr="title: $t('Delete image')" disable="$parent.disabled" click="$parent.removeFile.bind($parent, $file)"> <span translate="'Delete image'"/> </button> </div> </div> <div class="file-uploader-filename" text="$file.name"/> <div class="file-uploader-meta"> <text args="$file.previewWidth"/> x <text args="$file.previewHeight"/> </div> </div> |
Step – 5: Create routes.xml file in the directory path app/code/Webiators/CustomGroup/etc/adminhtml and add this code below.
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="admin"> <route id="catbanner" frontName="catbanner"> <module name="Magento_Catalog"/> </route> </router> </config> |
Step – 6: Create File Upload.php in the directory path app/code/Webiators/CustomGroup/Controller/Adminhtml/Category/Image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php namespace Webiators\CustomGroup\Controller\Adminhtml\Category\Image; use Exception; use Webiators\CustomGroup\Model\ImageUploader; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; class Upload extends Action implements HttpPostActionInterface { protected $imageUploader; public function __construct(Context $context, ImageUploader $imageUploader) { parent::__construct($context); $this->imageUploader = $imageUploader; } public function execute() { $imageId = $this->_request->getParam('param_name', 'image'); try { $result = $this->imageUploader->saveFileToTmpDir($imageId); } catch(Exception $e) { $result = ['error' => $e->getMessage() , 'errorcode' => $e->getCode() ]; } return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result); } } |
Step -7: Create ImageUploader.php file in the directory path app/code/Webiators/CustomGroup/Model after creating this file, you need to add this code given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
<?php namespace Webiators\CustomGroup\Model; use Exception; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\File\Uploader; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\WriteInterface; use Magento\Framework\UrlInterface; use Magento\MediaStorage\Helper\File\Storage\Database; use Magento\MediaStorage\Model\File\UploaderFactory; use Magento\Store\Model\StoreManagerInterface; use Psr\Log\LoggerInterface; /** * Feature image uploader */ class ImageUploader { const IMAGE_TMP_PATH = 'webiators/tmp/banner'; const IMAGE_PATH = 'webiators/banner'; /** * Core file storage database * * @var Database */ protected $coreFileStorageDatabase; /** * Media directory object (writable). * * @var WriteInterface */ protected $mediaDirectory; /** * Uploader factory * * @var UploaderFactory */ protected $uploaderFactory; /** * Store manager * * @var StoreManagerInterface */ protected $storeManager; /** * @var LoggerInterface */ protected $logger; /** * Base tmp path * * @var string */ protected $baseTmpPath; /** * Base path * * @var string */ protected $basePath; /** * Allowed extensions * * @var string */ protected $allowedExtensions; /** * List of allowed image mime types * * @var string[] */ protected $allowedMimeTypes; /** * ImageUploader constructor * * @param Database $coreFileStorageDatabase * @param Filesystem $filesystem * @param UploaderFactory $uploaderFactory * @param StoreManagerInterface $storeManager * @param LoggerInterface $logger * @param string $baseTmpPath * @param string $basePath * @param string[] $allowedExtensions * @param string[] $allowedMimeTypes * @throws FileSystemException */ public function __construct( Database $coreFileStorageDatabase, Filesystem $filesystem, UploaderFactory $uploaderFactory, StoreManagerInterface $storeManager, LoggerInterface $logger, $baseTmpPath = self::IMAGE_TMP_PATH, $basePath = self::IMAGE_PATH, $allowedExtensions = [], $allowedMimeTypes = [] ) { $this->coreFileStorageDatabase = $coreFileStorageDatabase; $this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); $this->uploaderFactory = $uploaderFactory; $this->storeManager = $storeManager; $this->logger = $logger; $this->baseTmpPath = $baseTmpPath; $this->basePath = $basePath; $this->allowedExtensions = $allowedExtensions; $this->allowedMimeTypes = $allowedMimeTypes; } /** * Set base tmp path * * @param string $baseTmpPath * * @return void */ public function setBaseTmpPath($baseTmpPath) { $this->baseTmpPath = $baseTmpPath; } /** * Set base path * * @param string $basePath * * @return void */ public function setBasePath($basePath) { $this->basePath = $basePath; } /** * Set allowed extensions * * @param string[] $allowedExtensions * * @return void */ public function setAllowedExtensions($allowedExtensions) { $this->allowedExtensions = $allowedExtensions; } /** * Retrieve base tmp path * * @return string */ public function getBaseTmpPath() { return $this->baseTmpPath; } /** * Retrieve base path * * @return string */ public function getBasePath() { return $this->basePath; } /** * Retrieve allowed extensions * * @return string[] */ public function getAllowedExtensions() { return $this->allowedExtensions; } /** * Retrieve path * * @param string $path * @param string $imageName * * @return string */ public function getFilePath($path, $imageName) { return rtrim($path, '/') . '/' . ltrim($imageName, '/'); } /** * Checking file for moving and move it * * @param string $imageName * * @return string * * @throws LocalizedException */ public function moveFileFromTmp($imageName) { $baseTmpPath = $this->getBaseTmpPath(); $basePath = $this->getBasePath(); $baseImagePath = $this->getFilePath( $basePath, Uploader::getNewFileName( $this->mediaDirectory->getAbsolutePath( $this->getFilePath($basePath, $imageName) ) ) ); $baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName); try { $this->coreFileStorageDatabase->copyFile( $baseTmpImagePath, $baseImagePath ); $this->mediaDirectory->renameFile( $baseTmpImagePath, $baseImagePath ); } catch (Exception $e) { throw new LocalizedException( __('Something went wrong while saving the file(s).') ); } return $imageName; } /** * Checking file for save and save it to tmp dir * * @param string $fileId * * @return string[] * * @throws LocalizedException */ public function saveFileToTmpDir($fileId) { $baseTmpPath = $this->getBaseTmpPath(); /** @var \Magento\MediaStorage\Model\File\Uploader $uploader */ $uploader = $this->uploaderFactory->create(['fileId' => $fileId]); $uploader->setAllowedExtensions($this->getAllowedExtensions()); $uploader->setAllowRenameFiles(true); if (!$uploader->checkMimeType($this->allowedMimeTypes)) { throw new LocalizedException(__('File validation failed.')); } $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath)); unset($result['path']); if (!$result) { throw new LocalizedException( __('File can not be saved to the destination folder.') ); } /** * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS */ $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']); $result['url'] = $this->storeManager ->getStore() ->getBaseUrl( UrlInterface::URL_TYPE_MEDIA ) . $this->getFilePath($baseTmpPath, $result['file']); $result['name'] = $result['file']; if (isset($result['file'])) { try { $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/'); $this->coreFileStorageDatabase->saveFile($relativePath); } catch (Exception $e) { $this->logger->critical($e); throw new LocalizedException( __('Something went wrong while saving the file(s).') ); } } return $result; } } |
Step -8: After following these steps, you need to run the following command given below.
1 2 3 4 5 6 7 |
php -dmemory_limit=5G bin/magento setup:upgrade php -dmemory_limit=5G bin/magento setup:di:compile php -dmemory_limit=5G bin/magento setup:static-content:deploy -f php -dmemory_limit=5G bin/magento cache:flush php -dmemory_limit=5G bin/magento cache:clean php -dmemory_limit=5G bin/magento indexer:reindex |
Step – 9: Now you can see the result: Go to your magento dashboard ->Catalog
We hope that this article will help you.
Thank You!