Model

Model is used to create a easie CRUD interface to the database

  • Model ame: The name of the model, the table name wil be <module_name>_<model_name>.
  • Field name: The name of the database table field.
  • Field type: The type of database field.
  • Adminhtml grid: Add this field to the adminhtml grid layout

Model ID field: The snippet will auto add the model id field to the database table, the field name is <model_name>_id.

Use the Model snippet in the Magento 2 module creator.

Files

Model/TestRepository.php

<?php


namespace Mage2Gen\Module\Model;

use Mage2Gen\Module\Api\TestRepositoryInterface;
use Mage2Gen\Module\Api\Data\TestSearchResultsInterfaceFactory;
use Mage2Gen\Module\Api\Data\TestInterfaceFactory;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Reflection\DataObjectProcessor;
use Mage2Gen\Module\Model\ResourceModel\Test as ResourceTest;
use Mage2Gen\Module\Model\ResourceModel\Test\CollectionFactory as TestCollectionFactory;
use Magento\Store\Model\StoreManagerInterface;

class TestRepository implements TestRepositoryInterface
{

    protected $resource;

    protected $TestFactory;

    protected $TestCollectionFactory;

    protected $searchResultsFactory;

    protected $dataObjectHelper;

    protected $dataObjectProcessor;

    protected $dataTestFactory;

    private $storeManager;


    /**
     * @param ResourceTest $resource
     * @param TestFactory $testFactory
     * @param TestInterfaceFactory $dataTestFactory
     * @param TestCollectionFactory $testCollectionFactory
     * @param TestSearchResultsInterfaceFactory $searchResultsFactory
     * @param DataObjectHelper $dataObjectHelper
     * @param DataObjectProcessor $dataObjectProcessor
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        ResourceTest $resource,
        TestFactory $testFactory,
        TestInterfaceFactory $dataTestFactory,
        TestCollectionFactory $testCollectionFactory,
        TestSearchResultsInterfaceFactory $searchResultsFactory,
        DataObjectHelper $dataObjectHelper,
        DataObjectProcessor $dataObjectProcessor,
        StoreManagerInterface $storeManager
    ) {
        $this->resource = $resource;
        $this->testFactory = $testFactory;
        $this->testCollectionFactory = $testCollectionFactory;
        $this->searchResultsFactory = $searchResultsFactory;
        $this->dataObjectHelper = $dataObjectHelper;
        $this->dataTestFactory = $dataTestFactory;
        $this->dataObjectProcessor = $dataObjectProcessor;
        $this->storeManager = $storeManager;
    }

    /**
     * {@inheritdoc}
     */
    public function save(
        \Mage2Gen\Module\Api\Data\TestInterface $test
    ) {
        /* if (empty($test->getStoreId())) {
            $storeId = $this->storeManager->getStore()->getId();
            $test->setStoreId($storeId);
        } */
        try {
            $this->resource->save($test);
        } catch (\Exception $exception) {
            throw new CouldNotSaveException(__(
                'Could not save the test: %1',
                $exception->getMessage()
            ));
        }
        return $test;
    }

    /**
     * {@inheritdoc}
     */
    public function getById($testId)
    {
        $test = $this->testFactory->create();
        $test->load($testId);
        if (!$test->getId()) {
            throw new NoSuchEntityException(__('Test with id "%1" does not exist.', $testId));
        }
        return $test;
    }

    /**
     * {@inheritdoc}
     */
    public function getList(
        \Magento\Framework\Api\SearchCriteriaInterface $criteria
    ) {
        $searchResults = $this->searchResultsFactory->create();
        $searchResults->setSearchCriteria($criteria);
        
        $collection = $this->testCollectionFactory->create();
        foreach ($criteria->getFilterGroups() as $filterGroup) {
            foreach ($filterGroup->getFilters() as $filter) {
                if ($filter->getField() === 'store_id') {
                    $collection->addStoreFilter($filter->getValue(), false);
                    continue;
                }
                $condition = $filter->getConditionType() ?: 'eq';
                $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
            }
        }
        $searchResults->setTotalCount($collection->getSize());
        $sortOrders = $criteria->getSortOrders();
        if ($sortOrders) {
            /** @var SortOrder $sortOrder */
            foreach ($sortOrders as $sortOrder) {
                $collection->addOrder(
                    $sortOrder->getField(),
                    ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
                );
            }
        }
        $collection->setCurPage($criteria->getCurrentPage());
        $collection->setPageSize($criteria->getPageSize());
        $items = [];
        
        foreach ($collection as $testModel) {
            $testData = $this->dataTestFactory->create();
            $this->dataObjectHelper->populateWithArray(
                $testData,
                $testModel->getData(),
                'Mage2Gen\Module\Api\Data\TestInterface'
            );
            $items[] = $this->dataObjectProcessor->buildOutputDataArray(
                $testData,
                'Mage2Gen\Module\Api\Data\TestInterface'
            );
        }
        $searchResults->setItems($items);
        return $searchResults;
    }

    /**
     * {@inheritdoc}
     */
    public function delete(
        \Mage2Gen\Module\Api\Data\TestInterface $test
    ) {
        try {
            $this->resource->delete($test);
        } catch (\Exception $exception) {
            throw new CouldNotDeleteException(__(
                'Could not delete the Test: %1',
                $exception->getMessage()
            ));
        }
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function deleteById($testId)
    {
        return $this->delete($this->getById($testId));
    }
}

Model/Test.php

<?php


namespace Mage2Gen\Module\Model;

use Mage2Gen\Module\Api\Data\TestInterface;

class Test extends \Magento\Framework\Model\AbstractModel implements TestInterface
{

    /**
     * @return void
     */
    protected function _construct()
    {
        $this->_init('Mage2Gen\Module\Model\ResourceModel\Test');
    }

    /**
     * Get test_id
     * @return string
     */
    public function getTestId()
    {
        return $this->getData(self::TEST_ID);
    }

    /**
     * Set test_id
     * @param string $testId
     * @return Mage2Gen\Module\Api\Data\TestInterface
     */
    public function setTestId($testId)
    {
        return $this->setData(self::TEST_ID, $testId);
    }

    /**
     * Get Test
     * @return string
     */
    public function getTest()
    {
        return $this->getData(self::TEST);
    }

    /**
     * Set Test
     * @param string $Test
     * @return Mage2Gen\Module\Api\Data\TestInterface
     */
    public function setTest($Test)
    {
        return $this->setData(self::TEST, $Test);
    }
}

Model/ResourceModel/Test.php

<?php


namespace Mage2Gen\Module\Model\ResourceModel;

class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{

    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('mage2gen_test', 'test_id');
    }
}

Model/ResourceModel/Test/Collection.php

<?php


namespace Mage2Gen\Module\Model\ResourceModel\Test;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{

    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init(
            'Mage2Gen\Module\Model\Test',
            'Mage2Gen\Module\Model\ResourceModel\Test'
        );
    }
}

Api/TestRepositoryInterface.php

<?php


namespace Mage2Gen\Module\Api;

use Magento\Framework\Api\SearchCriteriaInterface;

interface TestRepositoryInterface
{


    /**
     * Save Test
     * @param \Mage2Gen\Module\Api\Data\TestInterface $test
     * @return \Mage2Gen\Module\Api\Data\TestInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    
    public function save(
        \Mage2Gen\Module\Api\Data\TestInterface $test
    );

    /**
     * Retrieve Test
     * @param string $testId
     * @return \Mage2Gen\Module\Api\Data\TestInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    
    public function getById($testId);

    /**
     * Retrieve Test matching the specified criteria.
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return \Mage2Gen\Module\Api\Data\TestSearchResultsInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    
    public function getList(
        \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
    );

    /**
     * Delete Test
     * @param \Mage2Gen\Module\Api\Data\TestInterface $test
     * @return bool true on success
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    
    public function delete(
        \Mage2Gen\Module\Api\Data\TestInterface $test
    );

    /**
     * Delete Test by ID
     * @param string $testId
     * @return bool true on success
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    
    public function deleteById($testId);
}

Api/Data/TestInterface.php

<?php


namespace Mage2Gen\Module\Api\Data;

interface TestInterface
{

    const TEST = 'Test';
    const TEST_ID = 'test_id';


    /**
     * Get test_id
     * @return string|null
     */
    
    public function getTestId();

    /**
     * Set test_id
     * @param string $test_id
     * @return Mage2Gen\Module\Api\Data\TestInterface
     */
    
    public function setTestId($testId);

    /**
     * Get Test
     * @return string|null
     */
    
    public function getTest();

    /**
     * Set Test
     * @param string $Test
     * @return Mage2Gen\Module\Api\Data\TestInterface
     */
    
    public function setTest($Test);
}

Api/Data/TestSearchResultsInterface.php

<?php


namespace Mage2Gen\Module\Api\Data;

interface TestSearchResultsInterface extends \Magento\Framework\Api\SearchResultsInterface
{


    /**
     * Get Test list.
     * @return \Mage2Gen\Module\Api\Data\TestInterface[]
     */
    
    public function getItems();

    /**
     * Set Test list.
     * @param \Mage2Gen\Module\Api\Data\TestInterface[] $items
     * @return $this
     */
    
    public function setItems(array $items);
}

Setup/InstallSchema.php

<?php


namespace Mage2Gen\Module\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InstallSchema implements InstallSchemaInterface
{

    /**
     * {@inheritdoc}
     */
    public function install(
        SchemaSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $installer = $setup;
        $installer->startSetup();

        $table_mage2gen_test = $setup->getConnection()->newTable($setup->getTable('mage2gen_test'));

        
        $table_mage2gen_test->addColumn(
            'test_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            array('identity' => true,'nullable' => false,'primary' => true,'unsigned' => true,),
            'Entity ID'
        );
        

        
        $table_mage2gen_test->addColumn(
            'Test',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            null,
            ['nullable' => None],
            'Test'
        );
        

        $setup->getConnection()->createTable($table_mage2gen_test);

        $setup->endSetup();
    }
}