Magento 2将数据插入数据库

问题描述:

我最近在Magento 2中创建了一个模块.现在我从数据库的前端phtml文件中获取数据.代码如下.

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.

这是我的索引操作代码,在其中我创建了objectManagger对象,并使用objectManager成功将数据添加到数据库中.

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();
   }
}