28.07.2016

Magento 2. Creating a module. Part IV.

(We need the module that we created in the previous recipes)

Creating a flat table with models

STEP I – Create a resource model:

Create folders:

app/code/Magedd/Education/Model

app/code/Magedd/Education/Model/ResourceModel

 

Create the file:

app/code/Magedd/Education/Model/ResourceModel/Subscription.php

STEP II – Create the table with a schema upgrade script:

 

Create the folder:

app/code/Magedd/Education/Setup

 

Create the file:

app/code/Magedd/Education/Setup/UpgradeSchema.php

 

STEP III – Raise the module version:

Change the file:

app/code/Magedd/Education/etc/module.xml

 

Raise the module version to 2.0.1.

<module name=”Magedd_Education” setup_version=”2.0.1“/>

 

STEP IV – Upgrade setup by CLI

/var/www/local/{your-project-name.dev}> php bin/magento setup:upgrade

STEP V – Check that the table is installed in the database

We can do this by running the query describe magedd_education_subscription; on a MySQL command line.

This will give the following output:

mysql-quey-result

STEP VI – Create a model that interacts with the database table:

Create the file:

app/code/Magedd/Education/Model/Subscription.php

STEP VII – Create the collection class:

Create the file:

app/code/Magedd/Education/Model/ResourceModel/Subscription/Collection.php

All the files are in the right place to start a test. To perform a simple test, we can create a controller action (just for debugging purposes) so:

STEP VIII – create a controller action:

Create the file:

app/code/Magedd/Education/Controller/Index/Subscription.php

 

Open the browser and go to the URL:

htttp://{your-project-name.dev}/magedd/index/subscription

When you see the word Success, this will mean that a new subscription is added to the database table.

 

STEP IX – Check your database:

When you look in your database and run the query: select * from magedd_education_subscription; we will see the following output:

mysql-quey-result2