How to insert data into the custom table using Model, Resource Model in Magento 2?
Or how to use Model, Resource Model, Collection for the custom module in Magento 2?
Magento, data interfaces, data models, and models.
We are talking about how to insert data and use of Model. Resource Model, Collection so obviously we need a table and custom module. I am assuming you have a custom module and if you don’t have click here to see how to create a simple custom module. Next thing is you must have a table in your database where you want to insert your data. So if you have a table created no problem. If you don’t have click here and create it first.
For this post, I am gonna use the simple custom module that we have created before in this post – here
And I am gonna use the table that we have created in this post – here
If all things are clear then let’s get started.
We have a Vky/Test/view/frontend/templates/test.phtml
and in it, we just have below code right now.
<?php echo 'This is a simple custom module and it does not include admin and database realted files.'; ?>
To insert data we are going to use a form. I am just going to copy the default contact from design to creating a form. You can make your form however you want just make sure input names are the same as the database table field names. And I am not applying any validation to make it quick and short. I already have made a post about validation if you want to check that click here. And and I will post one more to cover validation in Magento 2.
So our edited Vky/Test/view/frontend/templates/test.phtml
file should look like below now.
<?php //echo 'This is a simple custom module and it does not include admin and database realted files.'; ?> <form class="" action="<?php echo $block->getBaseUrl().'test/index/save'; ?>" id="vky-test-form" method="post"> <fieldset class="fieldset"> <legend class="legend"><span>Test Form For Vky_Test Module</span></legend><br> <div class="field note no-label">Write here anything you want.</div> <div class="field title"> <label class="label" for="title"><span>Title</span></label> <div class="control"> <input name="title" id="title" title="Name" value="" class="input-text" type="text"> </div> </div> <div class="field author"> <label class="label" for="author"><span>Author</span></label> <div class="control"> <input name="author" id="author" title="Author" value="" class="input-text" type="text"> </div> </div> <div class="field content"> <label class="label" for="content"><span>Content</span></label> <div class="control"> <textarea name="content" id="content" title="Content" class="input-text" cols="5" rows="3"></textarea> </div> </div> </fieldset> <div class="actions-toolbar"> <div class="primary"> <button type="submit" title="Submit" class="action submit primary"> <span>Submit</span> </button> </div> </div> </form>
One thing you need to note is we have used action="<?php echo $block->getBaseUrl().'test/index/save'; ?>"
<?php echo $block->getBaseUrl(); ?>
this is how we get base URL in our phtml file. After that
test
– is our module index
– is our controller and save
– is our action which we don’t have yet. We have a index controller and index action in our custom module. So let’s create a save action for our index controller now.
Create Vky/Test/Controller/Index/Save.php
<?php namespace Vky\Test\Controller\Index; use Magento\Framework\App\Action\Context; use Vky\Test\Model\TestFactory; class Save extends \Magento\Framework\App\Action\Action { /** * @var Test */ protected $_test; public function __construct( Context $context, TestFactory $test ) { $this->_test = $test; parent::__construct($context); } public function execute() { $data = $this->getRequest()->getParams(); $test = $this->_test->create(); $test->setData($data); if($test->save()){ $this->messageManager->addSuccessMessage(__('You saved the data.')); }else{ $this->messageManager->addErrorMessage(__('Data was not saved.')); } $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('test/index/index'); return $resultRedirect; } }
Now our form has the input names same as the database fields. So we can use $test->setData($data);
otherwise we will have to use $test->setTitle("Some Title");
you can do this for other fields also if input names are not the same or you want to insert data into the field but not require to display in the form.
Use Model, Resource Model, Collection for the custom module?
Now to insert data using the Resource Model or use Model, Resource Model, Collection for the custom module we only need 3 files but in a proper folder structure.
First, Create Vky/Test/Model/Test.php
<?php namespace Vky\Test\Model; use Magento\Framework\Model\AbstractModel; class Test extends AbstractModel { /** * Define resource model */ protected function _construct() { $this->_init('Vky\Test\Model\ResourceModel\Test'); } }
Second, Create Vky/Test/Model/ResourceModel/Test.php
<?php namespace Vky\Test\Model\ResourceModel; class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { /** * Define main table */ protected function _construct() { $this->_init('vky_test', 'test_id'); //here "vky_test" is table name and "test_id" is the primary key of custom table } }
Third, Create Vky/Test/Model/ResourceModel/Test/Collection.php
<?php namespace Vky\Test\Model\ResourceModel\Test; class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { /** * Define model & resource model */ protected function _construct() { $this->_init( 'Vky\Test\Model\Test', 'Vky\Test\Model\ResourceModel\Test' ); } }
Now we have created a new action for our controller and a few more files to our custom module I suggest you to run some commands from your project’s root directory.
php bin/magento setup:upgrade
php bin/magento cache:flush
I think we are done here now. Open your URL where we are displaying our form. For example, it’s www.magento2.com/test. You will have your form there now submit the form data should be inserted in your custom table and you will be redirected to the same page with a success message.
How to get the collection?
We are going to get the collection and display that data in frontend in next post. But if you want it right now try this
$test = $this->_test->create(); // after this line
try below code.
echo '<pre>'; print_r($test->getCollection()->getData());die((__FILE__).'-->'.(__FUNCTION__).'--Line('. (__LINE__).')');
That’s how you insert data into the table using the Resource Model and use Model. Resource Model, Collection in Magento 2.
I hope it helps you.
Somasekhar
Posted at 11:22h, 01 Maymain.ERROR: Notice: Undefined variable: data in C:\xampp\htdocs\Magento\app\code\Vky\Test\Controller\Index\Save.php on line 25 [] []
Vicky
Posted at 14:10h, 21 JulySorry for that I have changed the code and it will work now.
Liam
Posted at 11:42h, 24 MayWhere/how do you make the TestFactory?
Liam
Posted at 12:10h, 24 Mayhttp://www.coolryan.com/magento/2016/02/10/working-models-magento-2/
Factories
First, you can use Factories in Magento 2. A factory is an autogenerated injectible class. This class let’s you create instances of your model. You can use factories by appending the word ‘Factory’ to the end of your injection. Magento 2 will automatically create the factory for you.
MAGIC!!!! gah.
m
Posted at 14:34h, 03 JulyEverything went good until here but
When posting form to save for database getting error in Vky/Test/Controller/Index/Save.php :24
and it says :
{“0″:”Notice: Undefined variable: data in \/var\/www\/html\/magento2\/app\/code\/Vky\/Test\/Controller\/Index\/Save.php on line 24”,
if Is there any solution and if may you assist me, i would be really pleasure to you
Vicky
Posted at 12:29h, 21 JulySorry about that, I have changed the code. Please check now.