Magento 2 将数据插入数据库

Magento 2 insert data into database

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

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

但我得到以下错误:

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

请帮我获取模型的对象,然后将数据插入table。

这是我的索引操作代码,我在其中创建了一个 objectManagger 对象并使用 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();
   }
}