Saving Data Using Model in Magento2: A Step-by-Step Guide
As a senior developer working on Magento2 projects, I often encounter questions like yours - how to save data using a custom model in a custom table. In this post, I’ll guide you through the process step by step, ensuring your code is clean and efficient.
1. Understanding Your Current Setup
You’ve already created a basic module with a controller and view that’s working perfectly. Great! Now, let’s dive into the custom model creation process to save data in a custom table containing question attributes (question Title, Question).
2. Creating the Custom Model
In your Chirag\Mygrid\Model directory, create a new file called Question.php. This will be our custom model.
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Chirag\Mygrid\Model;
class Question extends \Magento\Framework\Model\AbstractModel
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->init('Chirag\Mygrid\Model\Resource\Question');
}
}
In this file, we extend the Magento\Framework\Model\AbstractModel class and initialize our custom resource model in the _construct method.
3. Creating the Resource Model
Next, create a new file called Resource.php under Chirag\Mygrid\Model\Resource.
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Chirag\Mygrid\Model\Resource;
class Question extends \Magento\Framework\Model\Resource\Db\AbstractDb
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->init('questions_and_answers', 'question_id');
}
}
Here, we extend Magento\Framework\Model\Resource\Db\AbstractDb and initialize our custom table name (‘questions_and_answers’) and primary key (‘question_id’).
4. Creating the Resource Model Collection
Finally, create a new file called Collection.php under Chirag\Mygrid\Model\Resource\Question.
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Chirag\Mygrid\Model\Resource\Question;
class Collection extends \Magento\Framework\Model\Resource\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->init('Chirag\Mygrid\Model\Question', 'Chirag\Mygrid\Model\Resource\Question');
$this->map['fields']['page_id'] = 'main_table.page_id';
}
/**
* Prepare page's statuses.
* Available event cms_page_get_available_statuses to customize statuses.
*
* @return array
*/
public function getAvailableStatuses()
{
return [self::STATUS_ENABLED => __('Enabled'), self::STATUS_DISABLED => __('Disabled')];
}
}
This file handles the collection of our custom model.
5. Saving Data Using the Custom Model
Now, let’s modify your execute method in the Post.php controller to use the custom model and save data:
public function execute()
{
$post = $this->getRequest()->getPostValue();
$model = $this->_objectManager->create('Chirag\Mygrid\Model\Question');
$model->setData('question_title', $post['question_title']);
$model->setData('question', $post['question']);
try {
$model->save();
} catch (\Exception $e) {
// Handle exception, e.g., log the error
$this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
}
}
In this code:
- We retrieve the post data from the request.
- Create an instance of our custom model.
- Set the question title and question data using
setData()method. - Attempt to save the data using the
save()method inside a try-catch block.
6. Conclusion
With this setup, you should now be able to save data in your custom table using the Magento2 custom model. Remember to always handle exceptions properly to ensure your application remains stable and secure.
For more advanced topics like creating custom database columns or complex relationships, I recommend checking out our comprehensive guides on Magento2 module development. We cover everything from the basics to advanced techniques for Magento developers.
Happy coding! Let me know if you have any further questions.