Although Magento recommends using ui_component for creating grid or form in admin, Magento core itself has multiple forms & grid which is created using block(Old technique). So let's see how to add a field using the block technique:
For this first, we need to locate the block class which contains _prepareForm() method. And then we will create the Plugin for this class.
Step 1: Add the below code to the di.xml file of the custom module.
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\CheckoutAgreements\Block\Adminhtml\Agreement\Edit\Form">
<plugin name="add_embassy_field" type="MageInsight\CheckoutAgreements\Plugin\Block\Adminhtml\Agreement\Edit\Form" sortOrder="1"/>
</type>
</config>
Step 2: Create a new file inside your module plugin folder like MageInsight\CheckoutAgreements\Plugin\Block\Adminhtml\Agreement\Edit\Form.php
<?php
namespace MageInsight\CheckoutAgreements\Plugin\Block\Adminhtml\Agreement\Edit;
use MageInsight\Embassy\Model\Options\Embassy;
class Form
{
protected $embassy;
protected $_coreRegistry;
public function __construct(
\Magento\Framework\Registry $_coreRegistry,
Embassy $embassy
) {
$this->embassy = $embassy;
$this->_coreRegistry = $_coreRegistry;
}
public function aroundGetFormHtml(
\Magento\CheckoutAgreements\Block\Adminhtml\Agreement\Edit\Form $subject,
\Closure $proceed)
{
$form = $subject->getForm();
if (is_object($form)) {
$fieldset = $form->getElement('base_fieldset');
$model = $this->_coreRegistry->registry('checkout_agreement');
$fieldset->addField(
'embassies',
'multiselect',
[
'name' => 'embassies[]',
'label' => __('Embassies'),
'title' => __('EMbassies'),
'required' => false,
'values' => $this->embassy->toOptionArray(),
'value' => !empty($model->getData('embassies')) ? json_decode($model->getData('embassies'), true) : []
]
);
}
return $proceed();
}
}
Step 3: If you are adding a multi-select field, then the form submit will pass values in an array and we have to take care of this. In my case, I have added a Plugin for the beforeSave() which will take care of values every time the entity is saved by admin. Below is the code of that plugin.
<?php
namespace MageInsight\CheckoutAgreements\Plugin\Model;
class Agreement
{
public function aroundBeforeSave(
\Magento\CheckoutAgreements\Model\Agreement $subject,
\Closure $proceed
) {
if (!empty($subject->getData('embassies'))) {
$subject->setData('embassies', json_encode($subject->getData('embassies')));
}
return $proceed();
}
}
Conclusion: By following the above steps you will be able to save the values in the form and see the saved values in edit form. I have saved the values in JSON format because later it makes my work easy to filter using JSON_SEARCH queries.
Comments
Post a Comment