Magento2 CRUD – Module Development Series
In this post we will show you Magento2 CRUD – Module Development Series, hear for Magento2 CRUD – Module Development Series we will give you demo and example for implement.
we will see how to setup magento models and do database related operations.
To setup models in magento we need to add many files. The fastest way to do this is using code generate tools. You can find many tools online for magento2 code generation, but the one i used for this blog is this
To install this tool, go to your magento2 root folder and run this command
curl -LO http://pestle.pulsestorm.net/pestle.phar chmod +x pestle.phar
Next run this code for Magento2 CRUD
./pestle.phar generate_crud_model onlinecode_Hello Test
This should generate all the required files for a model
Creating IT : /var/www/html/magento2/app/code/onlinecode/Hello/Model/TestInterface.php
Creating IT : /var/www/html/magento2/app/code/onlinecode/Hello/Model/ResourceModel/Test/Collection.php
Creating IT : /var/www/html/magento2/app/code/onlinecode/Hello/Model/ResourceModel/Test.php
Creating IT : /var/www/html/magento2/app/code/onlinecode/Hello/Model/Test.php
Creating IT : /var/www/html/magento2/app/code/onlinecode/Hello/Setup/InstallSchema.php
Creating IT : /var/www/html/magento2/app/code/onlinecode/Hello/Setup/InstallData.php
Lets look at the files in details for Magento2 CRUD
Setup Script for Magento2 CRUD
The file onlinecode/Hello/Setup/InstallSchema.php contains code creating your database table. This is executed only one time during module installation. The contents for the file are
<?php namespace onlinecode\Hello\Setup; class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface { public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context) { $installer = $setup; $installer->startSetup(); //START: install stuff //END: install stuff //START table setup $table = $installer->getConnection()->newTable( $installer->getTable('onlinecode_hello_test') )->addColumn( 'onlinecode_hello_test_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, [ 'identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true, ], 'Entity ID' )->addColumn( 'title', \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 255, [ 'nullable' => false, ], 'Demo Title' )->addColumn( 'creation_time', \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, null, [ 'nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT, ], 'Creation Time' )->addColumn( 'update_time', \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, null, [ 'nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE, ], 'Modification Time' )->addColumn( 'is_active', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, [ 'nullable' => false, 'default' => '1', ], 'Is Active' ); $installer->getConnection()->createTable($table); //END table setup $installer->endSetup(); } }
looking at the file contents, its clear how the table is created. You can also edit this to make a table according to your needs.
The file onlinecode/Hello/Setup/InstallData.php is for setting initial data for the module, but we will discuss that in detail later.
At this point, if you look at your database tables you will not the see the table “onlinecode_hello_test” in database. The reason is, we have previously already setup the model and version 0.0.1 is already enabled in magento. So magento won’t run the setup scripts since as per magento the module is already installed.
To fix, see the table ‘setup_module’ in your magento2 database. It should have an entry for your module ‘onlinecode_Hello’.
Delete that entry from table and run the command
bin/magento setup:upgrade
This should run the setup scripts again and create your table.
Model File Magento2 CRUD
The model file is located at ‘onlinecode/Hello/Model/Test.php’
The code in the file is
<?php namespace onlinecode\Hello\Model; class Test extends \Magento\Framework\Model\AbstractModel implements TestInterface, \Magento\Framework\DataObject\IdentityInterface { const CACHE_TAG = 'onlinecode_hello_test'; protected function _construct() { $this->_init('onlinecode\Hello\Model\ResourceModel\Test'); } public function getIdentities() { return [self::CACHE_TAG . '_' . $this->getId()]; } }
The CACHE_TAG is important in magento2 for models. We will see later in detail what is it, just remember it should be unique for each model.
To use models in blocks we need to injected it. Magento2 we always we need to dependency injection, never should be we directly create block instance using “new” or “Mage::getModel”
Let’s see how to use the model in our block
In our block onlinecode\Hello\Block\Main we will add this code
<?php namespace onlinecode\Hello\Block; class Main extends \Magento\Framework\View\Element\Template { protected $_testFactory; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \onlinecode\Hello\Model\TestFactory $testFactory ) { $this->_testFactory = $testFactory; parent::__construct($context); } protected function _prepareLayout() { $test_data = $this->_testFactory->create(); $test_data->setTitle('Test Title'); $test_data->save(); $this->setTestModel($test_data); } }
You notice that the class \onlinecode\Hello\Model\TestFactory doesn’t exist. We have not created it. Factory are special kind of class in magento2. Any class with name Factory in it, magento will auto generate it and place that in var/generation/vendor/module/model folders
In our template file “content.phtml” we will write the code for Magento2 CRUD.
<h1><?php echo __('Model Saved With Entity ID %1',$block->getTestModel()->getData('onlinecode_hello_test_id')); ?></h1>
When you open the url, it will do the database entry and show the ID.
Magento2 models are pretty much same as magento1 models, so function like this load(), delete(), etc all work for Magento2 CRUD.
$test_data = $this->_testFactory->create(); $test_data->setTitle('Test Title'); $test_data->save(); $test_data->load(2); print_r($test_data->getData()); $test_data->delete(2);
Collection for Magento2 CRUD
The collection is located at ‘onlinecode\Hello\Model\ResourceModel\Test\Collection.php’ with the code
<?php namespace onlinecode\Hello\Model\ResourceModel\Test; class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { protected function _construct() { $this->_init('onlinecode\Hello\Model\Test','onlinecode\Hello\Model\ResourceModel\Test'); } }
We can do standard collection operations same as magento1 like
$test_data = $this->_testFactory->create(); $collection_data = $test_data->getCollection(); foreach($collection_data as $row) { print_r($row->getData()); }
Resource Model for Magento2 CRUD
Resource Model’s are the place where actual sql queries get executed. Model file contain overall database logic, but resource file do the actual sql operations for Magento2 CRUD.
e.g In your model file you can write this code for Magento2 CRUD.
<?php namespace onlinecode\Hello\Model; class Test extends \Magento\Framework\Model\AbstractModel implements TestInterface, \Magento\Framework\DataObject\IdentityInterface { const CACHE_TAG = 'onlinecode_hello_test'; protected function _construct() { $this->_init('onlinecode\Hello\Model\ResourceModel\Test'); } public function getIdentities() { return [self::CACHE_TAG . '_' . $this->getId()]; } public function loadByTitle($title_data){ if(!$title_data){ $title_data = $this->getTitle(); //random data logic. can be much more complex. //this is just example } $id_data = $this->getResource()->loadByTitle($title_data); return $this->load($id_data); } }
and resource model will have this code for Magento2 CRUD.
<?php namespace onlinecode\Hello\Model\ResourceModel; class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { protected function _construct() { $this->_init('onlinecode_hello_test','onlinecode_hello_test_id'); } public function loadByTitle($title){ $table_data = $this->getMainTable(); $where_data = $this->getConnection()->quoteInto("title = ?", $title); $sql_data = $this->getConnection()->select()->from($table_data,array('onlinecode_hello_test_id'))->where($where_data); $id_data = $this->getConnection()->fetchOne($sql_data); return $id_data; } }
and in our block file we call the model function for Magento2 CRUD.
<?php namespace onlinecode\Hello\Block; class Main extends \Magento\Framework\View\Element\Template { protected $_testFactory; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \onlinecode\Hello\Model\TestFactory $testFactory ) { $this->_testFactory = $testFactory; parent::__construct($context); } protected function _prepareLayout() { $testval = $this->_testFactory->create(); $test->loadByTitle('Test Title Hear'); $this->setTestModel($testval); } }
This is an important design pattern in magento, model should have the database logic and resource model the actual sql operations.
Hope this code and post will helped you for implement Magento2 CRUD Module Development Series. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs onlincode.org