4

I have added an admin form using Ui component.

example_example_edit.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <uiComponent name="example_form"/>
        </referenceContainer>
    </body>
</page>

example_form.xml

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">example_form.example_form_data_source</item>
            <item name="deps" xsi:type="string">example_form.example_form_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">example Information</item>
        <item name="config" xsi:type="array">
            <item name="dataScope" xsi:type="string">data</item>
            <item name="namespace" xsi:type="string">example_form</item>
        </item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
        <item name="buttons" xsi:type="array">
            <item name="save" xsi:type="string">Company\Module\Block\Adminhtml\Example\Edit\Button\Save</item>
            <item name="delete" xsi:type="string">Company\Module\Block\Adminhtml\Example\Edit\Button\Delete</item>
            <item name="back" xsi:type="string">Company\Module\Block\Adminhtml\Example\Edit\Button\Back</item>        
        </item>
    </argument>

    <dataSource name="example_form_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Company\Module\Model\ResourceModel\Example\DataProvider</argument>
            <argument name="name" xsi:type="string">example_form_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">example_id</argument>
            <argument name="requestFieldName" xsi:type="string">example_id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="submit_url" xsi:type="url" path="module/example/save"/>
                </item>
            </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="example_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">example [General]</item>
                <item name="sortOrder" xsi:type="number">10</item>
                <item name="openOnShow" xsi:type="boolean">true</item>
            </item>
        </argument>
        <field name="example_id">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="visible" xsi:type="boolean">false</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="source" xsi:type="string">label_id</item>
                </item>
            </argument>
        </field>
        <field name="title">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string">Title</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="disabled" xsi:type="boolean">false</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="source" xsi:type="string">title</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
        <field name="status">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Company\Module\Model\Config\Source\Status</item>
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Status</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="dataType" xsi:type="string">number</item>
                    <item name="formElement" xsi:type="string">select</item>
                    <item name="source" xsi:type="string">status</item>
                    <item name="dataScope" xsi:type="string">status</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
    </fieldset> 

</form>

And in DataProvider.php

<?php
namespace Company\Module\Model\ResourceModel\Example;

use Company\Module\Model\ResourceModel\Example\CollectionFactory;;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;  

class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{
    /**
     * @var array
     */
    protected $_loadedData;

    protected $storeManager;

    protected $scopeConfig;

    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $exampleCollectionFactory,
        StoreManagerInterface $storeManager,
        ScopeConfigInterface $scopeConfig,
        array $meta = [],
        array $data = []
    ) {
        $this->storeManager = $storeManager;
        $this->scopeConfig = $scopeConfig;
        $this->collection = $exampleCollectionFactory->create();
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
    }


    /**
    * Get data
    *
    * @return array
    */
    public function getData()
    {
        if (isset($this->_loadedData)) {
            return $this->_loadedData;
        }

    return $this->_loadedData;
    }
}

save.php

public function execute()
{
    $data = $this->getRequest()->getPostValue();
    /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();


    if ($data) {    

        /** @var \Webspeaks\ProductsGrid\Model\Contact $model */
        $model = $this->moduleModel;

        $id = $this->getRequest()->getParam('module_id');
        if ($id) {
            $model->load($id);
        }

        $model->setData($data);

        try {
            $model->save();

            $this->messageManager->addSuccess(__('You saved this item.'));
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
            if ($this->getRequest()->getParam('back')) {
                return $resultRedirect->setPath('*/*/edit', ['module_id' => $model->getId(), '_current' => true]);
            }
            return $resultRedirect->setPath('*/*/');
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\RuntimeException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('Something went wrong while saving the label.'));
        }

        $this->_getSession()->setFormData($data);
        return $resultRedirect->setPath('*/*/edit', ['module_id' => $this->getRequest()->getParam('module_id')]);
    }
    return $resultRedirect->setPath('*/*/');
}

Not able to save this form. Please help..

8

Add the following code in your execute function of Save Controller (Module/Controller/Adminhtml/Example/Save.php)

 public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();

        if ($data) {
            try{
                $id = $data['id'];
                $customModel = $this->customModel->load($id);
                $data = array_filter($data, function($value) { return $value !== ''; });
                $customModel->setData($data);
                $customModel->save();

                $this->messageManager->addSuccess(__('Successfully saved the item.'));
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);                
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {               
                $this->messageManager->addError($e->getMessage());
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData($data);
                return $resultRedirect->setPath('*/*/edit', ['id' => $customModel->getId()]);
            }
        }
        return $resultRedirect->setPath('*/*/');
    }
  • Thanks @Jancy. . it works.[$data = array_filter($data, function($value) { return $value !== ''; });] – E.B Dec 20 '16 at 4:38

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.