The form (uiComponent) of the backend and the CRUD in magento2 admin
In uiComponent listing (grid) to our module in the backend of magento2! We will now see how to add a form to Add / Modify / Delete (CRUD) our objects with in this module. For that, we will start from the files of our previous tutorial.
Display the form via the magento2 Action
To create our Form, we will first create the newAction action in our controller like this: (/Hikmadh/Mymodule/Controller/Adminhtml/Contact/NewAction.php)
_view->loadLayout();
$this->_view->renderLayout();
$contactDatas = $this->getRequest()->getParam('mymodel');
if(is_array($mymodelDatas)) {
$mymodel = $this->_objectManager->create(Mymodel::class);
$mymodel->setData($mymodelDatas)->save();
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/index');
}
}
}
We load and then display the layout that will contain the form. We check if we receive the parameter “contact” (if the form is sent), if yes then we save the contact in the database . Logically, we will now create the layout (/Hikmadh/Mymodule/view/adminhtml/layout/mymodel_test_newaction.xml):
In this layout, we just tell him to look for our layout contacts_text_edit. We create the layout file for editing (/Hikmadh/Mymodule/view/adminhtml/layout/mymodel_test_edit.xml):
Creating the file uiComponent for creation our form in magento2
Here it is said to load a uiComponent named “hikmadh_mymodel_form”, ( remember we did the same for the grid in the previous tutorial). We will therefore create the form in this uiComponent form.
So let’s create our uiComponent file for our form ( app/code/Hikmadh/Mymodule/view/adminhtml/ui_component/hikmadh_mymodel_form.xml ) :
Here the file looks complicated but you have to break it down.Do not worry it’s not that complicated. The file uiComponent for a form is composed of several tags:
- argument: The base of the file, which allows to configure the data_source to use, the label, and the display of buttons
- data: allows to make the links with the dataSource, pay attention to well define your “file name paths.” of the datasource
- buttons: if you have come up to it is that you know how to read an xml normally but we will still specify it is here that the buttons are added. For each button a name and a class to be used are delined. We’ll come back to it later.
- dataSource: The configuration of the dataSource itself, the links between the database and our form. The datasource defines the links between the database and your formualire, here it is given the name “mymodel_form_data_source” and the class “Hikmadh\Mymodule\Model\Mymodel\DataProvider”. We define that the id in our table will be “hikmadh_mymodel_id” but that it will be renamed “id” in our form.
- fieldset: The fieldset is used to define the fields of your form.
- field: represents a field of our form, they can be of several types that I invite you to search on the documentation of magento2. Here we used only text fields to facilitate our work. We define the same as the cahmps for the id will be invisible.
The DataSource of our magento2 form
The datasource of our magento2 form takes here our class “Hikmadh\Mymodule\Model\Mymodel\DataProvider” so we will create it.
So create the app/code/Hikmadh/Mymodule/Model/Mymodel/DataProvider.php file like this:
collection = $mymodelCollectionFactory->create();
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
}
public function getData()
{
if (isset($this->loadedData)) {
return $this->loadedData;
}
$items = $this->collection->getItems();
$this->loadedData = array();
/** @var Customer $customer */
foreach ($items as $mymodel) {
// notre fieldset s'apelle "mymodel" d'ou ce tableau pour que magento puisse retrouver ses datas :
$this->loadedData[$mymodel->getId()]['mymodel'] = $mymodel->getData();
}
return $this->loadedData;
}
}
It is this file that allows our fields to be automatically mapped to the database. The so-called “dataBinding”. Here we called our fieldset “mymodel”, so we pass our Mymodel object in the loadedData array that we return.
Configuring our form buttons
Under magento2, in the forms, we define classes for buttons like what we did in our uiComponent:
-
- Hikmadh\Mymodule\Block\Adminhtml\Contact\Edit\BackButton
- Hikmadh\Mymodule\Block\Adminhtml\Contact\Edit\DeleteButton
- Hikmadh\Mymodule\Block\Adminhtml\Contact\Edit\ResetButton
- Hikmadh\Mymodule\Block\Adminhtml\Contact\Edit\SaveButton
try' );
We will create our files:
Create a GenericButton:
The GenericButton is the element that allows other buttons to exist. This is the base that extends the other buttons. app/code/Hikmadh/Mymodule/Block/Adminhtml/Contact/Edit/GenericButton.php
urlBuilder = $context->getUrlBuilder();
$this->registry = $registry;
}
/**
* Return the synonyms group Id.
*
* @return int|null
*/
public function getId()
{
$mymodel = $this->registry->registry('mymodel');
return $mymodel ? $mymodel->getId() : null;
}
/**
* Generate url by route and parameters
*
* @param string $route
* @param array $params
* @return string
*/
public function getUrl($route = '', $params = [])
{
return $this->urlBuilder->getUrl($route, $params);
}
}
Create a button to save our magento2 form
Create the file app/code/Hikmadh/Mymodule/Block/Adminhtml/Mymodel/Edit/BackButton.php In which you just configure the label of the button, the associated event and the form-role that automatically triggers events js for magento2.
__('Back'),
'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
'class' => 'back',
'sort_order' => 10
];
}
/**
* Get URL for back (reset) button
*
* @return string
*/
public function getBackUrl()
{
return $this->getUrl('*/*/');
}
}
Create a button to delete an object using our form
Then create the file to delete an item from our formular App/code/Hikmadh/Mymodule/Block/Adminhtml/Mymodel/Edit/DeleteButton.php Here it is more or less pariel but for the suppression:
getId()) {
$data = [
'label' => __('Delete Contact'),
'class' => 'delete',
'on_click' => 'deleteConfirm(\''
. __('Are you sure you want to delete this contact ?')
. '\', \'' . $this->getDeleteUrl() . '\')',
'sort_order' => 20,
];
}
return $data;
}
/**
* @return string
*/
public function getDeleteUrl()
{
return $this->getUrl('*/*/delete', ['hikmadh_mymodel_id' => $this->getId()]);
}
}
Create a reset button to reset our magento2 form
app/code/Hikmadh/Mymodule/Block/Adminhtml/Contact/Edit/ResetButton.php
__('Reset'),
'class' => 'reset',
'on_click' => 'location.reload();',
'sort_order' => 30
];
}
}
Create a reset button to save our form
app/code/Hikmadh/Mymodule/Block/Adminhtml/Contact/Edit/SaveButton.php
__('Save Contact'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 90,
];
}
}
And here are !! Our buttons are created and theoretically everything should work 🙂
Create our delete action
We create our delete action to remove an object from the magento grid like this:
getRequest()->getParam('id');
if (!($contact = $this->_objectManager->create(Contact::class)->load($id))) {
$this->messageManager->addError(__('Unable to proceed. Please, try again.'));
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/index', array('_current' => true));
}
try{
$contact->delete();
$this->messageManager->addSuccess(__('Your contact has been deleted !'));
} catch (Exception $e) {
$this->messageManager->addError(__('Error while trying to delete contact: '));
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/index', array('_current' => true));
}
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/index', array('_current' => true));
}
}
);