Installation scripts comes in picture when you are working with custom extension in Magento 2 and wanted to load it with pre-added data in tables and later on you persist data in database. Once you add data through scripts, the available data get filled by default and then you can add more records as per requirement. In short, whenever you want to set initial default values to the database tables of your extension, the need for data script occurs.
Here, we will learn to create data install script and use it while extension installation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!--?php namespace [Vendor_Name]\[Extension_name]\Setup; use [Vendor_Name]\[Extension_name]\Model\[Model_Name]; use [Vendor_Name]\[Extension_name]\Model\[Model_Name]Factory; use Magento\Framework\Module\Setup\Migration; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; class InstallData implements InstallDataInterface { private $modelFactory; public function __construct([Model_Name]Factory $modelFactory) { $this->modelFactory = $modelFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $modeldata = [ [ 'fieldname1' => 'value1', 'fieldname2' => 'value2' ], [ 'fieldname1' => 'value3', 'fieldname2' => 'value4' ] ]; foreach ($modeldata as $data) { $this->modelFactory->create()->setData($data)->save(); } } } </pre> <p>This is how install script work while extension installation. Give it a try and if you find any queries or issues, feel free to ask through commenting. And yes, feedbacks are always appreciated!</p> <p><a href="https://www.magecomp.com/contacts/?utm_source=blog&utm_medium=CTA&utm_campaign=mcstdev"><img src="https://magecomp.com/blog/wp-content/uploads/2016/08/CTA_magento-custom-development.jpg" alt="CTA_magento-custom-development" width="669" height="200" class="aligncenter size-full wp-image-927" ?--> |