0

I created a ui component, but I have no idea how to save it in the database. I know I have to pass it to the controller for it to pass to the model but I don't know how my controller should be, here's my code:

form ui component:

 <dataSource name="novo_desconto_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Vendor\Desconto\Model\DataProvider</argument>
            <argument name="name" xsi:type="string">novo_desconto_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
    </dataSource>
    <fieldset name="employee_details">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="collapsible" xsi:type="boolean">true</item>
                <item name="label" xsi:type="string" translate="true">Employee Details</item>
                <item name="sortOrder" xsi:type="number">20</item>
            </item>
        </argument>
        <field name="employee_name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Nome</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="source" xsi:type="string">employee</item>
                    <item name="dataScope" xsi:type="string">employee_name</item>
                </item>
            </argument>
        </field>
        <field name="employee_salary">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Valor</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="source" xsi:type="string">employee</item>
                    <item name="dataScope" xsi:type="string">employee_salary</item>
                </item>
            </argument>
        </field>
        <field name="employee_address">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Desconto</item>
                    <item name="formElement" xsi:type="string">textarea</item>
                    <item name="source" xsi:type="string">employee</item>
                    <item name="dataScope" xsi:type="string">employee_address</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

DataProvider.php

<?php
namespace Vendor\Desconto\Model;
 
use Vendor\Desconto\Model\ResourceModel\Employee\CollectionFactory;
 
class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{
    /**
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param CollectionFactory $employeeCollectionFactory
     * @param array $meta
     * @param array $data
     */
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $employeeCollectionFactory,
        array $meta = [],
        array $data = []
    ) {
        $this->collection = $employeeCollectionFactory->create();
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
    }
 
    /**
     * Get data
     *
     * @return array
     */
    public function getData()
    {
        return [];
    }
}

My saveButton.php

<?php

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Desconto\Block\Adminhtml\Edit;

use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

/**
 * Class SaveButton
 * @package Magento\Customer\Block\Adminhtml\Edit
 */
class SaveButton extends GenericButton implements ButtonProviderInterface
{
    /**
     * @var AccountManagementInterface
     */
    protected $customerAccountManagement;

    /**
     * Constructor
     *
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param AccountManagementInterface $customerAccountManagement
     */
    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        \Magento\Framework\Registry $registry,
        AccountManagementInterface $customerAccountManagement
    ) {
        parent::__construct($context, $registry);
        $this->customerAccountManagement = $customerAccountManagement;
    }

    /**
     * @return array
     */
    public function getButtonData()
    {
        $customerId = $this->getCustomerId();
        $canModify = !$customerId || !$this->customerAccountManagement->isReadonly($this->getCustomerId());
        $data = [];
        if ($canModify) {
            $data = [
                'label' => __('Salvar'),
                'class' => 'save primary',
                'data_attribute' => [
                    'mage-init' => ['button' => ['event' => 'save']],
                    'form-role' => 'save',
                ],
                'sort_order' => 90,
            ];
        }
        return $data;
    }

    public function getSaveUrl()
    {
        return $this->getUrl('*/*/save', []);
    }
}




   <?php
namespace vendor\Desconto\Model;

use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Employee extends AbstractModel
{
    protected function _construct()
    {
        $this->_init('Vendor\test\Model\ResourceModel\Employee');
    }
}

Model.php

<?php
namespace Vendor\Desconto\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Employee extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('banktest', 'id_desconto');
    }
}

2 Answers 2

1

if you have multiple fieldsets happened to me that i had to set them "manually" like:

$rawData->setEmployeeName($data['employee_details']['employee_name']);

or if you have a plain form without tabs this should do the trick:

$rawData->setData($data);

You create a save action controller where you call your modelFactory witch create's or uses the current 'entity_id' to overwrite or create a new row.

Your controller should look like this,

<?php
    
    
    namespace Vendor\Module\Controller\Adminhtml\Employee;
    
    
    class Save extends \Magento\Backend\App\Action
    {
        var $employeeFactory;
    
    
        public function __construct(
            \Magento\Backend\App\Action\Context $context,
            \Vendor\Module\Model\EmployeeFactory $employeeFactory
        ) {
            parent::__construct($context);
            $this->employeeFactory = $employeeFactory;
        }
    
    
        public function execute()
        {
            $data = $this->getRequest()->getPostValue();
            if (!$data) {
    
                $this->_redirect('vendor_module/employee/edit'); // your edit url
                return;
            }
    
            try {
                $rawData = $this->employeeFactory->create();
                $rawData->setData($data);
                if (isset($data['entity_id'])) {
                    $rawData->setEntityId($data['entity_id']);
                }
                $rawData->save();
                $this->messageManager->addSuccess(__('Row data has been successfully saved.'));
            } catch (\Exception $e) {
                $this->messageManager->addError(__($e->getMessage()));
            }
            $this->_redirect('vendor_module/employee/index');
    
        }
    
    
    
    }

In Your ui component you have to declare the button:

<settings>
        <buttons>
            <button name="save" class="Vendor\Module\Block\Adminhtml\Employee\Edit\SaveButton"/>
        </buttons>
    </settings>
1

Please add controller file for save data in database

create save.php on below path

Vendor\Desconto\Controller\Adminhtml\Employee\save.php

<?php


namespace Vendor\Desconto\Controller\Adminhtml\Employee;

use Magento\Framework\Exception\LocalizedException;

class Save extends \Magento\Backend\App\Action
{

    private $dataPersistor;

    private $employeeModel;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor,
        \Vendor\Desconto\Model\Employee  $employeeModel
    ) {
        $this->dataPersistor = $dataPersistor;
        $this->employeeModel = $employeeModel;
        parent::__construct($context);
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();
        if ($data) {
            $id = $this->getRequest()->getParam('id_desconto');
        
            $model = $this->employeeModel->load($id);
            if (!$model->getId() && $id) {
                $this->messageManager->addErrorMessage(__('This item no longer exists.'));
                return $resultRedirect->setPath('*/*/');
            }
        
            $model->setData($data);
        
            try {
                $model->save();
                $this->messageManager->addSuccessMessage(__('You saved the data.'));
        
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['id_desconto' => $model->getId()]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the data.'));
            }
        
            return $resultRedirect->setPath('*/*/edit', ['id_desconto' => $this->getRequest()->getParam('id_desconto')]);
        }
        return $resultRedirect->setPath('*/*/');
    }


}

hope this will help you :)

3
  • error 404, page not found, button is not leading to the controller. How can I solve this?
    – lucas
    May 31, 2021 at 14:22
  • In saveButton.php you adeed get button data..here you not declared url so its not leading to controller. May 31, 2021 at 14:40
  • and how I do it ? ;=;
    – lucas
    May 31, 2021 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.