Magento 2 insert data into database

不羁岁月 提交于 2019-12-25 06:46:56

问题


I recently created a module in Magento 2. Now I get the data from the database in front-end phtml file.The code is given below.

 try
{
    $question = $this->_objectManager->create('Magecomp\Firstmodule\Model\Firstmodule');
    $question->setTitle('SimpleQuestion');
    $question->save();
}
catch(Exception $e)
{
     echo $e->getMessage();
}

But I get following Error :

 Notice: Undefined property: Magecomp\FirstModule\Block\FirstModule::$_objectManager in C:\xampp\htdocs\magento2\lib\internal\Magento\Framework\View\TemplateEngine\Php.php on line 113

Please help me to get the object of model and then insert data into table.


回答1:


This is my index action code in which i create a object of objectManagger and successfully add data into database using objectManager.

namespace Test\Firstmodule\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{

    public function execute()
   {
        $model = $this->_objectManager->create('Test\FirstModule\Model\Firstmodule');
        $model->setTitle('What is Question ?');
        $model->save();
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
   }
}


来源:https://stackoverflow.com/questions/31988661/magento-2-insert-data-into-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!