问题
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