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?

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 then create it first.

For this post, I am gonna use the simple custom module that we have created before in this post – Create a simple custom module in Magento 2

If all things are clear then let’s get started.
We have a app/code/Webcreta/Helloworld/view/frontend/templates/helloworld.phtml and in it, we just have below code right now


<h1><?php echo $this->getHelloWorldTxt(); ?></h1>

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.



<form class="" action="<?php echo $block->
getBaseUrl().'helloworld/index/save'; ?>" id="webcreta_helloworld -form" method="post">

<fieldset class="fieldset">

<legend class="legend"><span>Test Form For Webcreta_Helloworld Module</span></legend>


<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().’helloworld/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 Webcreta/Helloworld/Controller/Index/Save.php


<?php namespace Webcreta\Helloworld\Controller\Index; use Magento\Framework\App\Action\Context; use Webcreta\Helloworld\Model\TestFactory; class Save extends \Magento\Framework\App\Action\Action { /** * @var Helloworld */ protected $_helloworld; public function __construct( Context $context, TestFactory $helloworld ) { $this->_helloworld = $helloworld;
parent::__construct($context);
}
public function execute()
{
$helloworld = $this->_helloworld->create();
$helloworld->setData($data);
if($helloworld->save()){
$this->messageManager->addSuccessMessage(__('You saved the data.'));
}else{
$this->messageManager->addErrorMessage(__('Data was not saved.'));
}
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('helloworld/index/index');
return $resultRedirect;
}
}

Now our form has the input names same as the database fields. So we can use $helloworld->setData($data); otherwise we will have to use $helloworld->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 Webcreta/HelloworldModel/Helloworld.php


<?php
namespace Webcreta\Helloworld\Model;
use Magento\Framework\Model\AbstractModel;
class Helloworld extends AbstractModel
{
    /**
     * Define resource model
     */
    protected function _construct()
    {
        $this->_init('Webcreta\Helloworld\Model\ResourceModel\Helloworld');
    }
}

Second, Create Webcreta/Helloworld/Model/ResourceModel/Helloworld.php


<?php
namespace Webcreta\Helloworld\Model\ResourceModel;
class Helloworld extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    /**
     * Define main table
     */
    protected function _construct()
    {
        $this->_init('webcreta_helloworld', 'helloworld_id');   //here "webcreta_helloworld" is table name and "helloworld_id" is the primary key of custom table
    }
}

Third, Create Webcreta/Helloworld/Model/ResourceModel/Helloworld/Collection.php


<?php
namespace Webcreta\Helloworld\Model\ResourceModel\Helloworld;
 
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Define model & resource model
     */
    protected function _construct()
    {
        $this->_init(
            'Webcreta\Helloworld\Model\Helloworld',
            'Webcreta\Helloworld\Model\ResourceModel\Helloworld'
        );
    }
}

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 (Magento 2 Setup Upgrade Command)
php bin/magento cache:flush (Magento 2 Cache Flush Command)

I think we are done here now. Open your URL where we are displaying our form. For example, it’s http://localhost/magento/helloworld. 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
$helloworld = $this->_helloworld->create(); // after this line
try below code.
echo ‘ ‘; print_r($helloworld->getCollection()->getData());die((__FILE__).’–>’.(__FUNCTION__).’–Line(‘. (__LINE__).’)’);

That’s how you insert data into the table using ResourceModel and use Model. ResourceModel, Collection in Magento 2.
I hope it helps you.

    

Leave a Reply