How to save custom frontend form to database in Magento2.2.5?
Any help would be appreciated
How to save custom frontend form to database in Magento2.2.5?
Any help would be appreciated
You can save the form data using the controller :
namespace VendorName\ModuleName\Controller\Customer;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class Save extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $session;
public function __construct(
\Magento\Framework\App\Action\Context $context,
PageFactory $resultPageFactory
)
{
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();
//$resultPage = $this->resultPageFactory->create();
//$resultPage->getConfig()->getTitle()->set(__('Helpdesk'));
//return $resultPage;
$data = $this->getRequest()->getPostValue();
$model = $this->_objectManager->create('VendorName\ModuleName\Model\ModelName');
$model->setData($data);
try {
$model->save();
$this->messageManager->addSuccess(__('The Data has been saved.'));
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 Data.'));
}
}
}