Magento 2 Training : Unit 3 – Lesson C

Datas setup

Now we’ve got our tables and our models, we can add some datas inside !

Before beginning, we will add 2 methods on Job model.
Open the file :
app/code/Maxime/Jobs/Model/Job.php

And add these methods :

    public function getEnableStatus() {
        return 1;
    }

    public function getDisableStatus() {
        return 0;
    }

Now let’s create our setup. In order to add a datas setup, we have to create the file :
app/code/Maxime/Jobs/Setup/UpgradeData.php

Here is the code, I will explain it below :

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Maxime\Jobs\Setup;

use Maxime\Jobs\Model\Department;
use Maxime\Jobs\Model\Job;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class UpgradeData implements UpgradeDataInterface
{

    protected $_department;
    protected $_job;

    public function __construct(Department $department, Job $job){
        $this->_department = $department;
        $this->_job = $job;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        // Action to do if module version is less than 1.0.0.1
        if (version_compare($context->getVersion(), '1.0.0.1') < 0) {
            $departments = [
                [
                    'name' => 'Marketing',
                    'description' => 'Sed cautela nimia in peiores haeserat plagas, ut narrabimus postea,
                aemulis consarcinantibus insidias graves apud Constantium, cetera medium principem sed
                siquid auribus eius huius modi quivis infudisset ignotus, acerbum et inplacabilem et in
                hoc causarum titulo dissimilem sui.'
                ],
                [
                    'name' => 'Technical Support',
                    'description' => 'Post hanc adclinis Libano monti Phoenice, regio plena gratiarum et
                venustatis, urbibus decorata magnis et pulchris; in quibus amoenitate celebritateque
                nominum Tyros excellit, Sidon et Berytus isdemque pares Emissa et Damascus saeculis condita
                priscis.'
                ],
                [
                    'name' => 'Human Resource',
                    'description' => 'Duplexque isdem diebus acciderat malum, quod et Theophilum insontem atrox
                interceperat casus, et Serenianus dignus exsecratione cunctorum, innoxius, modo non reclamante publico vigore,
                discessit.'
                ]
            ];

            /**
             * Insert departments
             */
            $departmentsIds = array();
            foreach ($departments as $data) {
                $department = $this->_department->setData($data)->save();
                $departmentsIds[] = $department->getId();
            }


            $jobs = [
                [
                    'title' => 'Sample Marketing Job 1',
                    'type' => 'CDI',
                    'location' => 'Paris, France',
                    'date'  => '2016-01-05',
                    'status' => $this->_job->getEnableStatus(),
                    'description' => 'Duplexque isdem diebus acciderat malum, quod et Theophilum insontem atrox
                interceperat casus, et Serenianus dignus exsecratione cunctorum, innoxius, modo non reclamante publico vigore,
                discessit.',
                    'department_id' => $departmentsIds[0]
                ],
                [
                    'title' => 'Sample Marketing Job 2',
                    'type' => 'CDI',
                    'location' => 'Paris, France',
                    'date'  => '2016-01-10',
                    'status' => $this->_job->getDisableStatus(),
                    'description' => 'Duplexque isdem diebus acciderat malum, quod et Theophilum insontem atrox
                interceperat casus, et Serenianus dignus exsecratione cunctorum, innoxius, modo non reclamante publico vigore,
                discessit.',
                    'department_id' => $departmentsIds[0]
                ],
                [
                    'title' => 'Sample Technical Support Job 1',
                    'type' => 'CDD',
                    'location' => 'Lille, France',
                    'date'  => '2016-02-01',
                    'status' => $this->_job->getEnableStatus(),
                    'description' => 'Duplexque isdem diebus acciderat malum, quod et Theophilum insontem atrox
                interceperat casus, et Serenianus dignus exsecratione cunctorum, innoxius, modo non reclamante publico vigore,
                discessit.',
                    'department_id' => $departmentsIds[1]
                ],
                [
                    'title' => 'Sample Human Resource Job 1',
                    'type' => 'CDI',
                    'location' => 'Paris, France',
                    'date'  => '2016-01-01',
                    'status' => $this->_job->getEnableStatus(),
                    'description' => 'Duplexque isdem diebus acciderat malum, quod et Theophilum insontem atrox
                interceperat casus, et Serenianus dignus exsecratione cunctorum, innoxius, modo non reclamante publico vigore,
                discessit.',
                    'department_id' => $departmentsIds[2]
                ]
            ];

            foreach ($jobs as $data) {
                $this->_job->setData($data)->save();
            }
        }

        $installer->endSetup();
    }
}

Our class has got 2 protected attributes :
– department
– job

We define their types on the construct method:
– Department $department
– Job $job

This is the new dependency injection with Magento 2. With this code, we say to Magento we must have these 2 modules available in the class to do the things we want.
We cannot use the Mage::getModel() like Magento 1.

After that, we have the “upgrade” methode wich contain a data table. We loop on it to create the objects and save its. The save method add the datas on database.

During the departments’ save, we stock the created ids on a table. So we can use it to link department with jobs on the next step.

We also use our 2 new methods the get the job status (enable, disable).

As you can see, we have a condition with the module version (like schemas upgrades).
Our condition check the version 1.0.0.1, so we have to modify it on the file :
app/code/Maxime/Jobs/etc/module.xml

Change the “setup_version” to “1.0.0.1”

Go to your Magento root and launch the upgrade command :
./bin/magento setup:upgrade

You will see lines like these :

Module 'Maxime_Jobs':
Upgrading data..

Is you check your tables on database, you will see the freshly created datas !

department_datas

jobs_datas

It’s important to know you can create a class “InstallData.php” inside the Setup folder, which work like the “InstallSchema.php” class, and launched at the first module upgrade.

Globally, during an upgrade, Magento launch these processes with this order :
Setup\InstallSchema
Setup\UpgradeSchema
Setup\Recurring
Setup\InstallData
Setup\UpgradeData

To finish, if you go on the “setup_module” table, you will see our module on it’s current version. You can put an older one in order to launch some upgrades since the version you want.

setup_modules

On the next lesson, we will manage our datas on the Magento’s backoffice 🙂

Continue training
Return to previous lesson
Module datas setup with Magento 2
Share on FacebookTweet about this on TwitterShare on Google+Email this to someone
Tagged on:         

2 thoughts on “Module datas setup with Magento 2

  • 07/26/2016 at 19:17
    Permalink

    Hello,

    Thanks for providing such a useful blog. It helps me a lot to learn magento 2.

    Thanks.

    Reply
  • 12/09/2017 at 13:03
    Permalink

    Thanks Fro Your Providein Use Full Blog Plase Put New Blog For Magento 2 Training

    Reply

Leave a Reply to Vishal Patidar Cancel reply

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

We use cookies to ensure that we give you the best experience on our website.
Ok