0

Magento CE 2.2.0; I created CRUD for model 'people' and save data in to database by controller for testing.

While i try to save by using controllor Add:

$_person = $this->_objectManager->create(\MagePro\Contacts\Model\People::class);
$_person->setName($person[PeopleTable::NAME]);
$_person->setSex($person[PeopleTable::SEX]);
$_person->save();

This process will meet error:

Magento\Framework\Exception\LocalizedException: Invalid method 
MagePro\Contacts\Model\People::_getResource in /home/dev- 
72/Work/Magento/Web/www/vendor/magento/framework/DataObject.php:395
Stack trace:
#0 /home/dev- 72/Work/Magento/Web/www/vendor/magento/framework/Model/AbstractModel.php(647): Magento\Framework\DataObject->__call('_getResource', Array)
#1 /home/dev-72/Work/Magento/Web/www/app/code/MagePro/Contacts/Controller/People/Add.php(44): Magento\Framework\Model\AbstractModel->save()
#2 /home/dev-72/Work/Magento/Web/www/app/code/MagePro/Contacts/Controller/People/Add.php(25): MagePro\Contacts\Controller\People\Add->generatePerson('name', 'sex')
#3 /home/dev-72/Work/Magento/Web/www/generated/code/MagePro/Contacts/Controller/People/Add/Interceptor.php(24): MagePro\Contacts\Controller\People\Add->execute()
#4 /home/dev-72/Work/Magento/Web/www/vendor/magento/framework/App/Action/Action.php(107): MagePro\Contacts\Controller\People\Add\Interceptor->execute()

People Model:

<?php
namespace MagePro\Contacts\Model;
use Magento\Framework\Model\AbstractModel;

class People extends AbstractModel
{
    public function __construct()
    {
       $this->_init(\MagePro\Contacts\Model\ResourceModel\People::class);
    }
}

People Resource Model:

<?php
namespace MagePro\Contacts\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use MagePro\Contacts\Model\ConstantValue\DataTable as TablePeople;

class People extends AbstractDb
{
    public function _construct()
    {
       $this->_init(TablePeople::TABLE_PEOPLE, TablePeople::ID);
    }
}

Constant People Table:

<?php
namespace MagePro\Contacts\Model\ConstantValue;

class DataTable
{
    const TABLE_PEOPLE = 'tb_people';
    const ID = 'id';
    const NAME = 'name';
    const SEX = 'sex';
}

InstallSchema

class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
{
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
    $setup->startSetup();
    $this->createPeopleTable($setup);
    $setup->endSetup();
}

private function createPeopleTable($setup)
{
    if ($this->isExist($setup, PeopleTable::TABLE_PEOPLE)) {
        return;
    }

    $table = $setup->getConnection()->newTable($setup->getTable(PeopleTable::TABLE_PEOPLE)
    )->addColumn(
        PeopleTable::ID,
        DDL::TYPE_INTEGER,
        null,
        ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true]

    )->addColumn(
        PeopleTable::NAME,
        DDL::TYPE_TEXT,
        null,
        ['identity' => false, 'unsigned' => true, 'nullable' => true, 'primary' => false]

    )->addColumn(
        PeopleTable::SEX,
        DDL::TYPE_TEXT,
        null,
        ['identity' => false, 'unsigned' => true, 'nullable' => true, 'primary' => false]

    )->setComment(
        'Contacts Table'
    )->setOption(
        'type', 'InnoDB'
    )->setOption('charset', 'utf8');

    return $setup->getConnection()->createTable($table);
}

private function isExist($setup, $tableName)
{
    if($setup->getConnection()->isTableExists($setup->getTable($tableName))){
        return true;
    }
    return false;
}

}
  • Check my answer, Let me know if you have any queries. – Vivek May 26 '18 at 9:51
1

While you provided limited code i can't look into this, But here you go.

Setup/InstallSchema.php

public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
{
    $installer = $setup;
    $installer->startSetup();
    if (!$installer->tableExists('your_table_name')) {
        $table = $installer->getConnection()->newTable(
            $installer->getTable('your_table_name')
        )
            ->addColumn(
                'entity_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                [
                    'identity' => true,
                    'nullable' => false,
                    'primary'  => true,
                    'unsigned' => true,
                ],
                'EntityId'
            )
            ->addColumn(
                'status',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                '255',
                [],
                'Status'
            )
            ->setComment('Your Comment');
        $installer->getConnection()->createTable($table);
    }
    $installer->endSetup();
}

../Model/YourTableName.php

 class YourTableName extends \Magento\Framework\Model\AbstractModel implements TimelineInterface
{
const CACHE_TAG = 'your_table_name';

protected $_cacheTag = 'your_table_name';

protected $_eventPrefix = 'your_table_name';

protected function _construct()
{
    $this->_init('{Vendor}\{Module}\Model\ResourceModel\YourTableName');
}

public function getEntityId()
{
    return $this->getData(self::ENTITY_ID);
}

public function setEntityId($entityId)
{
    return $this->setData(self::ENTITY_ID, $entityId);
}

public function getStatus()
{
    return $this->getData(self::STATUS);
}

public function setStatus($status)
{
    return $this->setData(self::STATUS, $status);
}

public function getIdentities()
{
    return [self::CACHE_TAG . '_' . $this->getId()];
}

public function getDefaultValues()
{
    $values = [];

    return $values;
}
}

../Model/ResourceModel/YourTableName.php

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

public function __construct(
    \Magento\Framework\Model\ResourceModel\Db\Context $context
)
{
    parent::__construct($context);
}

protected function _construct()
{
    $this->_init('your_table_name', 'entity_id');
}

}

../Model/ResourceModel/YOurrTableName/Collection.php

class Collection extends 
\Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'entity_id';
protected $_eventPrefix = 'your_table_name_collection';
protected $_eventObject = 'your_table_name_collection';

protected function _construct()
{
    $this->_init('{Vendor}\{Module}\Model\YourTableName', '{Vendor}\{Module}\Model\ResourceModel\YourTableName');
}

}

After follow above steps : Run s:up, s:s:d -f, 'c:f'

Than after add some collumns in your table

../Controller/YourTableName/Index.php

class Index extends \Magento\Framework\App\Action\Action
{
 protected $_pageFactory;

protected $_postFactory;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $pageFactory,
    \{Vendor}\{Module}\Model\YourTableNameFactory $timelineFactory
    )
{
    $this->_pageFactory = $pageFactory;
    $this->_postFactory = $timelineFactory;
    return parent::__construct($context);
}


public function execute()
{


    $post = $this->_postFactory->create();
    $collection = $post->getCollection();
    foreach($collection as $item){
        echo "<pre>";
        print_r($item->getData());
        echo "</pre>";
    }
    exit();*/

    return $this->_pageFactory->create();
}
}

Hope it will help you.

For more you can check below references.

https://www.mageplaza.com/magento-2-module-development/how-to-create-crud-model-magento-2.html

Happy Programming.. !!

1

Change resource model to

app\code\MagePro\Contacts\Model\ResourceModel\People.php

<?php

namespace MagePro\Contacts\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use MagePro\Contacts\Model\ConstantValue\DataTable as TablePeople;

class People extends AbstractCollection
{
    protected $_idFieldName = 'id';

    public function _construct()
    {
       $this->_init(TablePeople::TABLE_PEOPLE, TablePeople::ID);
    }
}

Now run command

php bin/magento setup:di:compile php bin/magento cache:flush

  • Follow the answer I will show this error. 'Uncaught Error: Call to a member function dispatch() on null in /home/dev-72/Work/Magento/Web/www/vendor/magento/framework/Model/AbstractModel.php:693\nStack trace:\n#0 /home/dev-72/Work/Magento/Web/www/vendor/magento/framework/Model/ResourceModel/Db/AbstractDb.php(406): Magento\\Framework\\Model\\AbstractModel->beforeSave()\n..' – Bong Channarith May 27 '18 at 2:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.