1

I have the following resource model.

namespace Vendor\Gift\Model\ResourceModel;

class GiftInformation extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    protected function _construct()
    {
        $this->_init('gift_products', 'gift_id');
    }

And the following model:

namespace Vendor\Gift\Model;

class Gift extends \Magento\Framework\Model\AbstractModel
{

    public $giftId;

    public function __construct(    
            $giftId = null
    ){
        $this->giftId = $giftId;
        $this->_init('Vendor\Gift\Model\ResourceModel\GiftInformation');
    }

    }
}

When I do

$this->_giftFactory = $this->_giftFactory->create(['giftId'=>$this->giftId]);

I can use $this->_giftFactory->setData([..some data..]) and $this->_giftFactory->getData() methods of the factory, but when I try $this->_giftFactory-save(), so that I can insert a row in my table "gift_products" I receive the following error:

Uncaught Error: Call to a member function dispatch() on null in
/magento_root_dir/vendor/magento/framework/Model/AbstractModel.php:661 
......
... rest of the stack trace, which just leads to the place where I invoke the save() method.

On line 661 in AbstractModel.php I have :

$this->_eventManager->dispatch('model_save_before', ['object' => $this]);

What is the problem here ?

1

The problem here is that you're not declaring the right method in your model.

Instead of

__construct()

It should be:

_construct()

With only one underscore.

Then the function should look like this:

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

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.