Back to Top

Create Ui Form In Magento2 – Part 2

Updated 21 February 2024

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.
Ui Form

Searching for an experienced
Magento 2 Company ?
Find out More

That’s all for Magento Ui Component Form.
If you have any query or issue, please comment below.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


4 comments

  • Greg
    • abhishek (Moderator)
  • Jayashree N
    • Webkul Support
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home