In this tutorial we will cover saving data to database by coding for front end form and front end normal controller. This will be very useful if you just want to save something to database without any complicated work.
Save to database from any where
If your are using front-end, you need to extend the Front controller with
[code]\Magento\Framework\App\Action\Action[/code]
Model extend \Magento\Framework\Model\AbstractModel
Resource Model extend \Magento\Framework\Model\ResourceModel\Db\AbstractDb
Collection extend \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
Follow the working reference code and check your post data carefully.
[code]class Post extends \Magento\Framework\App\Action\Action
{
public function __construct(
\Magento\Framework\App\Action\Context $context
) {
parent::__construct($context);
}
public function execute()
{
$data = $this->getRequest()->getPostValue();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$question = $objectManager->create(‘Suyati\Scontact\Model\Contacts’);
$question->setData($data);
//$question->setEmail(‘test@test.com’);
//$question->setQuery(‘Question Description’);
$question->save();
$this->messageManager->addSuccess( __(‘Thanks for your valuable feedback.’) );
//$this->messageManager->addSuccess(‘Query subbmitted successfully.’);
$this->_redirect(‘*/*/’);
return;
}
}[/code]
Create Form and save data to database in magento 2
Assuming we are creating new module Company/Module.
Defining the module
[code]/app/code/Company/Module/etc/module.xml[/code]
[code]<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Company_Module" setup_version="1.0.0">
</module>[/code]
Module registration
[code]/app/code/Company/Module/registration.php[/code]
[code]
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
‘Company_Module’,
__DIR__
);[/code]
Create the frontend router
[code]/app/code/Company/Module/etc/frontend/routes.xml[/code]
Create a route for manage :
GET request wich going to display HTML form template
POST request wich going to send form data to Action Controller Class.
[code]<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="companymodule" frontName="companymodule">
<module name="Company_Module"/>
</route>
</router>
</config>[/code]
Create the layout
[code]/app/code/Company/Module/view/frontend/layout/module_index_booking.xml[/code]
Create a basic layout for associate the Block to the form page phtml template
[code]<?xml version="1.0"?>
<page layout="2columns-left" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>HTML title – The booking form page</title>
</head>
<body>
<referenceBlock name="navigation.sections" remove="true" />
<referenceContainer name="content">
<block class="Company\Module\Block\Booking" name="companymodule.booking" template="Company_Module::booking.phtml"/>
</referenceContainer>
</body>
</page>[/code]
Create the Block
[code]/app/code/Company/Module/Block/Booking.php[/code]
Create a block with many functions you want for your form.
[code]<?php
namespace Company\Module\Block;
class Booking extends \Magento\Framework\View\Element\Template
{
/**
* Construct
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
array $data = []
)
{
parent::__construct($context, $data);
}
/**
* Get form action URL for POST booking request
*
* @return string
*/
public function getFormAction()
{
// companymodule is given in routes.xml
// controller_name is folder name inside controller folder
// action is php file name inside above controller_name folder
return ‘/companymodule/controller_name/action’;
// here controller_name is index, action is booking
}
}[/code]
Create the template
[code]/app/code/Company/Module/view/frontend/templates/booking.phtml[/code]
Create a template with your HTML form and add the form action corresponding to the routing.
[code]
<h1>Booking page</h1>
<form action="<?php echo $block->getFormAction() ?>" method="post">
<input name="firstname" type="text">
<input name="lastname" type="text">
<input name="phone" type="text">
<input name="bookingTime" type="date">
<input type="submit" value="Send booking informations">
</form>
[/code]
Create the Action Controller
[code]/app/code/Company/Module/Controller/Index/Booking.php[/code]
Create an Action Controller for manage the requests on the route.
[code]
<?php namespace Company\Module\Controller\Index; use Magento\Framework\Controller\ResultFactory; class Booking extends \Magento\Framework\App\Action\Action { /** * Booking action * * @return void */ public function execute() { // 1. POST request : Get booking data $post = (array) $this->getRequest()->getPost();
if (!empty($post)) {
// Retrieve your form data
$firstname = $post[‘firstname’];
$lastname = $post[‘lastname’];
$phone = $post[‘phone’];
$bookingTime = $post[‘bookingTime’];
// Doing-something with…
// Display the succes form validation message
$this->messageManager->addSuccessMessage(‘Booking done !’);
// Redirect to your form page (or anywhere you want…)
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl(‘/companymodule/index/booking’);
return $resultRedirect;
}
// 2. GET request : Render the booking page
$this->_view->loadLayout();
$this->_view->renderLayout();
}
}[/code]
In resuming you will must have the following architecture :
[code]
app
├ code
| ├ Company
| | ├ Module
| | | ├ Block
| | | | ├ Booking.php
| | | ├ Controller
| | | | ├ Index
| | | | | ├ Booking.php
| | | ├ etc
| | | | ├ frontend
| | | | | ├ routes.xml
| | | ├ view
| | | | ├ frontend
| | | | | ├ layout
| | | | | | ├ module_index_booking.xml
| | | | | ├ templates
| | | | | | ├ booking.phtml[/code]
Then run following commands :
[code]
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush[/code]
Then you can access to your custom form page : http://localhost/companymodule/index/booking
Happy coding!