Here we’ll learn how to add custom form elements in product add/edit form in specific group section in Magento 2
Using magento2 ‘adminhtml_catalog_product_edit_prepare_form’ observer we can add custom form elements in product add/edit form.
1# First we’ll define observer (event) in event.xml file at folder app/code/NameSpace/ModuleName/etc/adminhtml
<?xml version="1.0"?> <!-- /** * Webkul Admin events * * @category Webkul * @author Webkul Software Private Limited * */ --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="adminhtml_catalog_product_edit_prepare_form"> <observer name="custom_product_fields" instance="NameSpace\ModuleName\Observer\CatalogProductEditPrepareForm" /> <!-- CatalogProductEditPrepareForm is name of class in which we'll add custom fields in form--> </event> </config>
2# Now create CatalogProductEditPrepareForm.php class file in app/code/NameSpace/ModuleName/Observer
<?php /** * @category Webkul * @author Webkul Software Pvt. Ltd. */ namespace NameSpace\ModuleName\Observer; use Magento\Framework\Event\ObserverInterface; class CatalogProductEditPrepareForm implements ObserverInterface { /** * @var \Magento\Framework\Registry */ protected $_coreRegistry; /** * @param \Magento\Framework\Registry $coreRegistry */ public function __construct( \Magento\Framework\Registry $coreRegistry ) { $this->_coreRegistry = $coreRegistry; } /** * product from prepare event handler. * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $form = $observer->getForm(); // $observer contain form object // get your group element in which you want to add custom filed $fieldset = $form->getElement('group-fields-id-in-which-you-want-to-add-elements'); if ($fieldset) { // get current product if you want to use any data from product $product = $this->_coreRegistry->registry('product'); $fieldset ->addField( 'custom-field-1', 'text', [ 'name' => 'custom-field-1', 'label' => __('Custom Field 1'), 'id' => 'custom-field-1' ] ); $fieldset ->addField( 'custom-field-2', 'text', [ 'name' => 'custom-field-2', 'label' => __('Custom Field 2'), 'id' => 'custom-field-2' ] ); // You can set any data in these elements for display default value $form->addValues( [ 'custom-field-1' => 'data according to you', // ex. $product->getName() 'custom-field-2' => 'data according to you' ] ); } return $this; } }
Note:- its use for display data on form and you can get data on submit but Data will not save with product …
Be the first to comment.