Magento 2 – Fix Fatal Error in Custom Model Save

magento2

I am creating a simple frontend magento 2 module to take input from user and save output in database.

Here is what i have tried.

Index.php — (Index controller index action)

namespace Companyname\Faq\Controller;
use Magento\Framework\App\RequestInterface;

class Index extends \Magento\Framework\App\Action\Action
{
    public function __construct(\Magento\Framework\App\Action\Context $context) {
        parent::__construct($context);
    }

    /**
     * Dispatch request
     *
     * @param RequestInterface $request
     * @return \Magento\Framework\App\ResponseInterface
     * @throws \Magento\Framework\Exception\NotFoundException
     */
    public function dispatch(RequestInterface $request) {
        return parent::dispatch($request);
    }
}

Add.php — (Index controller add action)

<?php

namespace Companyname\Faq\Controller\Index;

class Add extends \Companyname\Faq\Controller\Index {
    public function execute() {
    try {
        $params = $this->getRequest()->getPostValue();               

        $faq = $this->_objectManager->create('Companyname\Faq\Model\Faq');
        $faq->setData($params);     
        $faq->save();
    } catch (\Exception $e) {
            $this->_redirect('*/*/');
            return;
        }
    }

}

?>

Companyname\Faq\Model\Faq.php

namespace Companyname\Faq\Model;

class Faq extends \Magento\Framework\Model\AbstractModel {
    public function __construct() {
    $this->_init('Companyname\Faq\Model\Resource\Faq');
    }
}

Companyname\Faq\Model\Resource\Faq.php

namespace Companyname\Faq\Model\Resource;

class Faq extends \Magento\Framework\Model\Resource\Db\AbstractDb {
    protected function _construct() {
    $this->_init('faq', 'faq_id');
    }
}

i get post data properly and the model also loads correctly with this line – $this->_objectManager->create('Companyname\Faq\Model\Faq');

However, when it tries to save the data, an error gets generated. Fatal error: Call to a member function dispatch() on a non-object in \lib\internal\Magento\Framework\Model\AbstractModel.php on line 663

After a little debugging, i found that it is not getting eventManager inside \lib\internal\Magento\Framework\Model\AbstractModel.php in this line – $this->_eventManager->dispatch('model_load_before', $params);

Any clues as to what i am doing wrong ?

Best Answer

Problem in method __construct. You need to call _construct (one underlinen), not __construct, like

namespace Companyname\Faq\Model;

class Faq extends \Magento\Framework\Model\AbstractModel {
    public function _construct() {
           $this->_init('Companyname\Faq\Model\Resource\Faq');
    }
}

I think we need to have better name for this "pseudo constructor" method

Related Topic