0

I created a custom magento 2 form. As far as saving, I would like to take the modified value in the save.php of the controller. Is there any method I can use?

This is my save.php controller

<?php
namespace Vendor\Module\Controller\Adminhtml\Index;

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

const ADMIN_RESOURCE = 'Index';

protected $resultPageFactory;
protected $contactFactory;

public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    \Vendor\Module\Model\ProfileFactory $contactFactory
)
{
    $this->resultPageFactory = $resultPageFactory;
    $this->contactFactory = $contactFactory;
    parent::__construct($context);
}

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

    $formKey = $data['form_key'];
    $data = $data['info']['manage_profile'];
    $data['form_key'] = $formKey;

    if($data)
    {
        try{

            $id = $data['profile_id'];

            $contact = $this->contactFactory->create()->load($id);

            $data = array_filter($data, function($value) {return $value !== ''; });

            $contact->setData($data);
            $contact->save();
            $this->messageManager->addSuccess(__("Profilo {$data['name']} salvato con successo"));
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
            return $resultRedirect->setPath('*/*/');
        }
        catch(\Exception $d)
        {
            $this->messageManager->addError($e->getMessage());
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData($data);
            return $resultRedirect->setPath('*/*/edit', ['id' => $contact->getId()]);
        }
    }

    return $resultRedirect->setPath('*/*/');
}

}

Instead of $data = $this->getRequest()->getPostValue();

I would like to use a method to get all the values modified in the form`

1

You can check the changed data by adding this code before the $contact->save().

$diff = array_diff_assoc($contact->getOrigData(), $contact->getData());
  • What I was looking for, thanks! – Mastafis Aug 6 at 9:17

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.