Example of Code and Configuration for a Simple Magento 2 CRUD Model

crudmagento2PHPsql

How can I, an end-user-programmer, create a new "CRUD" model in Magento 2? That is, I want to create the PHP class files and XML configuration files that will

  1. Let me Create, Read, Update and Delete data from a database table
  2. Let me create the initial database table(s) that will store this information.

In Magento 1 this was handled by a Model, Resource Model, Setup Resource Model, and various nodes in config.xml. It's not 100% clear how this is handled in Magento 2.

Is there a sample module or clear tutorial out there yet for this? Or is working backwards from an existing core model (like CMS page) our only option?

Best Answer

Tracked this one down on my own.

First, Magento 2 requires no additional XML for creating a CRUD model. Magento 2 automatically knows how to create the needed resource model and collection objects based on a naming convention.

Magento 2 does require a

  • Model Class
  • Resource Model Class
  • Collection Model Class
  • A Schema install class

The specifics of each of these are beyond the scope of a single Stack Exchange answer, but the CMS Page model offers a simple example of each class.

https://github.com/magento/magento2/blob/develop/app/code/Magento/Cms/Model/Page.php

https://github.com/magento/magento2/blob/develop/app/code/Magento/Cms/Model/ResourceModel/Page.php

https://github.com/magento/magento2/blob/develop/app/code/Magento/Cms/Model/ResourceModel/Page/Collection.php

https://github.com/magento/magento2/blob/develop/app/code/Magento/Cms/Setup/InstallSchema.php

Also, my Magento 2 code generation tool pestle now has a generate_crud_model command.