In previous blog we created a Ui Form in admin.
See How Create Ui Component Form In Magento2 – Part 1.
Here we will see how to fill data from database in Ui Form.
Steps to create Ui Form In Magento2
First of all create a Ui Grid for employee details table so that you can edit each record.
Or you can simply pass id or primary field as parameter in url directly.
Important thing is requestFieldName value in ui_component xml file must be same as url parameter.
Here in this example primary key is id. So we used id everywhere. You can use it according to your primary key.
Finally its time to display data in fields on edit page.
Edit DataProvider.php file in location ‘Webkul/UiForm/Model’
<?php /** * Webkul Software. * * @category Webkul * @package Webkul_UiForm * @author Webkul * @copyright Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ namespace Webkul\UiForm\Model; use Webkul\UiForm\Model\ResourceModel\Employee\Collection; class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider { /** * @var array */ protected $_loadedData; /** * @var \Webkul\UiForm\Model\ResourceModel\EmployeeDetail\Collection */ protected $collection; /** * @param string $name * @param string $primaryFieldName * @param string $requestFieldName * @param \Webkul\UiForm\Model\ResourceModel\EmployeeDetail\Collection $employeeCollection */ public function __construct( $name, $primaryFieldName, $requestFieldName, Collection $employeeCollection ) { parent::__construct($name, $primaryFieldName, $requestFieldName); $this->collection = $employeeCollection; } /** * Get data * * @return array */ public function getData() { if (isset($this->_loadedData)) { return $this->_loadedData; } $items = $this->collection->getItems(); foreach ($items as $employee) { $this->_loadedData[$employee->getId()] = $employee->getData(); } return $this->_loadedData; } }
Now your data will be automatically filled in fields of Ui Form.
That’s all for Magento Ui Component Form.
If you have any query or issue, please comment below.
4 comments
Hello Greg,
In code we only initialize collection which will use in AbstractDataProvider for filter data accoridng to pass id in form for load data.
Thanks