Inserting Data in Existing Table During Magento 2 Extension Installation

Inserting Data in Existing Table During Magento 2 Extension Installation

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.

Magento version upgrade In short, whenever you want to set initial default values to the database tables of your extension, the need for data script occurs.

Magento Malware Removal

Here, we will learn to create data install script and use it while extension installation.

We need to create “InstallData.php” file inside extension setup folder

app\code\Vendor\Extension\Setup

<?php 
namespace Vendor\Extension\Setup;

use Vendor\Extension\Model\Demo; 
use Vendor\Extension\Model\DemoFactory; 
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(
DemoFactory $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();
        }
    }
}

Magento 2 Speed & Performance Optimization Services

Previous Article

How to Setup Multi Store in Magento 2 (Updated)

Next Article

How to Upgrade Magento 2.x to the Latest Version?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨