save form data to the custom table in Magento 2. When you fill out details in a form and click on a Submit button, the data has to be stored in a table. To do that, you will need to create Submit.php file. For instance, if you want to collect name, email addresses and telephone number of customers for sending newsletters, the data should be stored in a database. If the data is not stored in the database, we simply cannot access and send newsletters. Learn the programmatic method as shown below:
Method to Save Form Data to the Custom Table in Magento 2:
Create a file app\code\Extension\Controller\Index\Submit.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<?php
namespace Cozmot\Extension\Controller\Index;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Meetanshi\Extension\Model\ExtensionFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
class Submit extends Action
{
protected $resultPageFactory;
protected $extensionFactory;
public function __construct(
Context $context,
PageFactory $resultPageFactory,
ExtensionFactory $extensionFactory
)
{
$this->resultPageFactory = $resultPageFactory;
$this->extensionFactory = $extensionFactory;
parent::__construct($context);
}
public function execute()
{
try {
$data = (array)$this->getRequest()->getPost();
if ($data) {
$model = $this->extensionFactory->create();
$model->setData($data)->save();
$this->messageManager->addSuccessMessage(__(“Data Saved Successfully.”));
}
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e, __(“We can\’t submit your request, Please try again.”));
}
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl($this->_redirect->getRefererUrl());
return $resultRedirect;
}
}
|
