cancel
Showing results for 
Search instead for 
Did you mean: 

Save data on controller

Save data on controller

Hey guys,

have a controller receiving a post.

How do I save the data and retreive on frontend?

1 REPLY 1

Re: Save data on controller

Hi @AlexMesquita,

 

You should use a repository. Maybe this simple example can help a little bit.

Look at vendor/magento/module-customer/Controller/Adminhtml/Group/Save.php.

Into method execute you'll find this:

 

   /**
     * Create or save customer group.
     *
     * @return \Magento\Backend\Model\View\Result\Redirect|\Magento\Backend\Model\View\Result\Forward
     */
    public function execute()
    {
        $taxClass = (int)$this->getRequest()->getParam('tax_class');

        /** @var \Magento\Customer\Api\Data\GroupInterface $customerGroup */
        $customerGroup = null;
        if ($taxClass) {
            $id = $this->getRequest()->getParam('id');
            $resultRedirect = $this->resultRedirectFactory->create();
            try {
                $customerGroupCode = (string)$this->getRequest()->getParam('code');
                if ($id !== null) {
                    $customerGroup = $this->groupRepository->getById((int)$id);
                    $customerGroupCode = $customerGroupCode ?: $customerGroup->getCode();
                } else {
                    $customerGroup = $this->groupDataFactory->create();
                }
                $customerGroup->setCode(!empty($customerGroupCode) ? $customerGroupCode : null);
                $customerGroup->setTaxClassId($taxClass);

                $this->groupRepository->save($customerGroup);

                $this->messageManager->addSuccess(__('You saved the customer group.'));
                $resultRedirect->setPath('customer/group');
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                if ($customerGroup != null) {
                    $this->storeCustomerGroupDataToSession(
                        $this->dataObjectProcessor->buildOutputDataArray(
                            $customerGroup,
                            \Magento\Customer\Api\Data\GroupInterface::class
                        )
                    );
                }
                $resultRedirect->setPath('customer/group/edit', ['id' => $id]);
            }
            return $resultRedirect;
        } else {
            return $this->resultForwardFactory->create()->forward('new');
        }
    }

At

 

$this->groupRepository->save($customerGroup);

The data is saved.

You should explore hoy to build a repository (service contracts + models).

 

https://devdocs.magento.com/guides/v2.2/extension-dev-guide/service-contracts/service-contracts.html