Inserting Data into Custom Tables in Magento2 Using Resource Model and Block Class
Hello and welcome! Today, I’m going to guide you through the process of inserting data into custom tables in Magento2 using the resource model and block class. This is a common requirement when developing custom extensions for Magento.
Step 1: Understanding Your Current Setup
You’ve already created your model classes (Book and Collection) and your resource model (Collection). You’re on the right track! Let’s break down what you have so far:
Model Classes
class Book extends AbstractModel
{
protected function _construct()
{
$this->_init(\Vendor\BooksModule\Model\ResourceModel\Book::class);
}
}
// -- and --
class Collection extends AbstractCollection
{
// ... (your existing code)
}
Resource Model
class Collection extends AbstractCollection
{
protected $_idFieldName = 'id';
protected function _construct()
{
$this->_init("Vendor\BooksModule\Model\Book","Vendor\BooksModule\Model\ResourceModel\Book");
}
}
Step 2: Refactoring the Block Class
The key to successfully inserting data lies in correctly using the resource model and the save() method of your model. Let’s refactor your block class:
class Insert extends Template
{
private $collectionFactory;
public $successMessage = null;
public function __construct(
Template\Context $context,
CollectionFactory $collectionFactory,
array $data = []
) {
$this->collectionFactory = $collectionFactory;
parent::__construct($context, $data);
}
public function execute()
{
$name = $this->getRequest()->getParam('bookName');
$author = $this->getRequest()->getParam('bookAuthor');
$description = $this->getRequest()->getParam('bookDescription');
// Create a new instance of your model
$model = $this->collectionFactory->create();
// Set the data to be inserted
$data = [
'name' => $name,
'author' => $author,
'description' => $description,
];
$model->setData($data);
try {
// Save the new record
$model->save();
$this->successMessage = "Saved Successfully!";
} catch (\Exception $e) {
// Handle any exceptions (for example, database errors)
$this->successMessage = "Error: " . $e->getMessage();
}
}
public function getSuccessMessage()
{
return $this->successMessage;
}
}
Step 3: Using Your Block Class
To use your new block class:
- Include it in your layout XML file (usually located in
app/code/Vendor/BooksModule/view/frontend/layout).
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="customer_account"/>
<referenceContainer name="content">
<block class="Vendor\BooksModule\Block\Insert" template="Vendor_BooksModule::insert.phtml" name="books.insert" />
</referenceContainer>
</page>
- Create a form in your PHTML file (
app/code/Vendor/BooksModule/view/frontend/templates/insert.phtml).
<?php if ($block->getSuccessMessage()): ?>
<div class="success-msg"><?= $block->getSuccessMessage() ?></div>
<?php endif; ?>
<form action="<?= $block->getActionUrl('insert') ?>" method="post">
<input name="bookName" type="text" />
<input name="bookAuthor" type="text" />
<textarea name="bookDescription"></textarea>
<button type="submit">Save</button>
</form>
Conclusion
In this guide, we’ve covered how to insert data into a custom table using the resource model and block class in Magento2. The key is to create a new instance of your model, set the data you want to insert, and then call the save() method.
Remember to handle exceptions and display appropriate messages for both success and failure scenarios. This will provide a better user experience for your customers.
I hope this helps! If you have any further questions or need more advanced techniques, feel free to visit our Magento development blog at Laravel Company. We’re always happy to help!
Happy coding!