【问题标题】:Magento 2 insert data into databaseMagento 2 将数据插入数据库
【发布时间】:2018-01-31 17:39:05
【问题描述】:

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

 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

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

【问题讨论】:

  • 请关注stackoverflow.com/questions/31920769/…,你会找到你的解决方案。
  • 如果您使用我的参考链接找到了解决方案,我应该将其发布为答案吗?
  • 但它给了我可恢复的错误:
  • 可恢复的错误:传递给 Magecomp\Firstmodule\Controller\Index\Index::__construct() 的参数 1 必须是 Magento\Framework\Model\Context 的实例
  • 你能编辑答案并将你的控制器的代码放在这里吗?

标签: magento magento2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-21
    • 2013-02-02
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2017-01-14
    相关资源
    最近更新 更多