2

I need to add a parameter from the registry to my form save action

Currently i'm attempting to do this by storing my parameter in the registry, then collecting it in the the buttons save block class. This works in as far as it changes the on-click event of the button, but does not affect the submit url of the form. Therefore when it comes to retrieving the order_id in the save controller the parameter is not there.

<?php

namespace Blah\OrderResources\Block\Adminhtml\Buttons;

use Blah\OrderResources\Block\Adminhtml\Buttons\Generic;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;


class Save extends Generic implements ButtonProviderInterface
{
    /**
     * get button data
     *
     * @return array
     */
    public function getButtonData()
    {
        $orderId = $this->getOrderId();
        // Add the order id to the url so we can maintain the association
        $url = $this->getUrl('order-resource/form/save', ['order_id' => $orderId]);

        return [
            'label' => __('Save Resource'),
            'class' => 'save primary',
            'data_attribute' => [
                'mage-init' => ['button' => ['event' => 'save']],
                'form-role' => 'save',
            ],
            'sort_order' => 90,
            'url' => $url
        ];

    }



}

I imagine that this needs to be done using a data provider but I can't seem to be able to figure this out. Here is the ui-component xml where the submit url is set :

<dataSource name="order_resources_form_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Blah\OrderResources\Model\DataProvider</argument>
            <argument name="name" xsi:type="string">order_resources_form_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">resource_id</argument>
            <argument name="requestFieldName" xsi:type="string">resource_id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="submit_url" xsi:type="url" path="order_resources/form/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>

Does anyone know how I can achieve this ?

2 Answers 2

5

You can add a URL parameter to the submit URL more easily using a button adapter as follows:

 public function getButtonData()
    {
        return
            [
                'label' => __('Save'),
                'class' => 'save',
                'on_click' => '',
                'sort_order' => 80,
                'data_attribute' => [
                    'mage-init' => [
                        'Magento_Ui/js/form/button-adapter' => [
                            'actions' => [
                                [
                                    'targetName' => 'your_ui_component_name.your_ui_component_name',
                                    'actionName' => 'save',
                                    'params' => [
                                        true,
                                        ['order_id' => $this->getOrderId()],
                                    ]
                                ]
                            ]
                        ]
                    ],

                ]
            ];
    }
3
  • did you get any solution? Apr 17, 2018 at 6:33
  • Yes, I posted the solution :) Apr 18, 2018 at 0:13
  • This work great. I think better option than first answer. Aug 16, 2018 at 19:09
2

After fiddling around for a while i figured out that the data persister is the way to go.

Below is my data provider and save controller which demonstrated setting and getting the data persister.

<?php

namespace Blah\OrderResources\Model;

use Blah\OrderResources\Model\ResourceModel\OrderResources\CollectionFactory;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Registry;

class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{

    protected $collection;

    /**
     * @var DataPersistorInterface
     */
    protected $dataPersistor;

    /**
     * @var array
     */
    protected $loadedData;

    protected $_requestInterface;

    protected $_registry;

    /**
     * DataProvider constructor.
     *
     * @param string                 $name
     * @param string                 $primaryFieldName
     * @param string                 $requestFieldName
     * @param CollectionFactory      $resourcesCollectionFactory
     * @param DataPersistorInterface $dataPersistor
     * @param RequestInterface       $requestInterface
     * @param Registry               $registry
     * @param array                  $meta
     * @param array                  $data
     */
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $resourcesCollectionFactory,
        DataPersistorInterface $dataPersistor,
        RequestInterface $requestInterface,
        Registry $registry,
        array $meta = [],
        array $data = []
    ) {
        $this->collection = $resourcesCollectionFactory->create();
        $this->dataPersistor = $dataPersistor;
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
        $this->_requestInterface = $requestInterface;
        $this->_registry = $registry;
        $this->meta = $this->prepareMeta($this->meta);
    }

    /**
     * Prepares Meta
     *
     * @param array $meta
     * @return array
     */
    public function prepareMeta(array $meta)
    {
        return $meta;
    }

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

        $this->dataPersistor->set('current_order_id', $this->_registry->registry(
            'current_order_id'
        ));

        return $this->loadedData;
    }
}

Controller

<?php

namespace Blah\OrderResources\Controller\Adminhtml\Form;

use Magento\Backend\Model\Session;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;
use Blah\OrderResources\Api\OrderResourcesRepositoryInterface;
use Blah\OrderResources\Api\Data\OrderResourcesInterface;
use Blah\OrderResources\Api\Data\OrderResourcesInterfaceFactory;
use Blah\OrderResources\Model\Uploader;
use Blah\OrderResources\Model\UploaderPool;
use Blah\OrderResources\Model\OrderResourcesFactory;
use Blah\OrderResources\Controller\Adminhtml\Form;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\Model\View\Result\ForwardFactory;
use Magento\Framework\Stdlib\DateTime\Filter\Date;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\App\Request\DataPersistorInterface;

class Save extends Form
{
    /**
     * @var DataObjectProcessor
     */
    protected $_dataObjectProcessor;

    /**
     * @var \Magento\Framework\Api\DataObjectHelper
     */
    protected $_dataObjectHelper;

    /**
     * @var UploaderPool
     */
    protected $_uploaderPool;

    protected $_dataPersistor;


    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        ForwardFactory $resultForwardFactory,
        OrderResourcesFactory $orderResourcesFactory,
        OrderResourcesRepositoryInterface $orderResourcesRepository,
        Registry $registry,
        Date $dateFilter,
        DataObjectProcessor $dataObjectProcessor,
        DataObjectHelper $dataObjectHelper,
        UploaderPool $uploaderPool,
        DataPersistorInterface $dataPersistor
    ) {
        $this->_orderResourcesFactory = $orderResourcesFactory;
        $this->_dataObjectProcessor = $dataObjectProcessor;
        $this->_dataObjectHelper = $dataObjectHelper;
        $this->_uploaderPool = $uploaderPool;
        $this->_dataPersistor = $dataPersistor;

        parent::__construct(
            $context, $resultPageFactory, $resultForwardFactory,
            $orderResourcesFactory, $orderResourcesRepository, $registry
        );
    }

    /**
     * run the action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
        $orderResource = null;
        $data = $this->getRequest()->getPostValue();
        $orderId = $this->_dataPersistor->get('current_order_id');

        $resultRedirect = $this->resultRedirectFactory->create();


        try {
            $orderResource = $this->_orderResourcesFactory->create();

            $file = $this->getUploader('file')->uploadFileAndGetName('file', $data);
            $data['path'] = $file;
            $data['order_id'] = $orderId;
            $data['resource_id'] = null;


            $this->_dataObjectHelper->populateWithArray($orderResource, $data, OrderResourcesInterface::class);
            $this->_orderResourcesRepository->save($orderResource);
            $this->messageManager->addSuccessMessage(__('You saved the order resource'));
            if ($this->getRequest()->getParam('back')) {
                $resultRedirect->setPath('sales/order/view/', ['order_id' => $orderId]);
            } else {
                $resultRedirect->setPath('sales/order/view/',['order_id' => $orderId]);
            }
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            if ($orderResource != null) {
                $this->storeOrderResourceDataToSession(
                    $this->_dataObjectProcessor->buildOutputDataArray(
                        $orderResource,
                        OrderResourcesInterface::class
                    )
                );
            }
            $resultRedirect->setPath('sales/order/view/',['order_id' => $orderId]);
        } catch (\Exception $e) {
            echo $e->getMessage();
            $this->messageManager->addErrorMessage(__('There was a problem saving the order resource'));
            if ($orderResource != null) {
                $this->storeOrderResourceDataToSession(
                    $this->_dataObjectProcessor->buildOutputDataArray(
                        $orderResource,
                        OrderResourcesInterface::class
                    )
                );
            }
            $resultRedirect->setPath('sales/order/view/',['order_id' => $orderId]);
        }
        return $resultRedirect;
    }

    /**
     * @param $type
     * @return Uploader
     * @throws \Exception
     */
    protected function getUploader($type)
    {
        return $this->_uploaderPool->getUploader($type);
    }

    protected function storeOrderResourceDataToSession($orderResourceData)
    {
        $this->_getSession()->setOrderResourceData($orderResourceData);
    }

}
1
  • it's working for me
    – Devidas
    May 11, 2022 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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