I'm using Magento 2 CE Version 2.1.0
I'm making a custom module. For developing custom module i'm taking reference of Magento CMS Module {folder path}\magento2\vendor\magento\module-cms
I have below code while INSERT data in the database.
{folder path}\magento2\app\code\Custom\Module\Controller\Adminhtml\Posts\Save.php
public function execute() {
$data = $this->getRequest()->getPostValue();
$resultRedirect = $this->resultRedirectFactory->create();
if ($data) {
$model = $this->_objectManager->create('Custom\Module\Model\Posts');
$id = $this->getRequest()->getParam('posts_id');
if ($id) {
$model->load($id);
}
$model->setData($data);
$this->_eventManager->dispatch(
'module_posts_prepare_save', ['post' => $model, 'request' => $this->getRequest()]
);
try {
$model->save();
echo "Done";
exit;
$this->messageManager->addSuccess(__('You saved this Post.'));
$this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
return $resultRedirect->setPath('*/*/edit', ['posts_id' => $model->getId(), '_current' => true]);
}
return $resultRedirect->setPath('*/*/');
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\RuntimeException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addException($e, __('Something went wrong while saving the post.'));
}
$this->_getSession()->setFormData($data);
return $resultRedirect->setPath('*/*/edit', ['posts_id' => $this->getRequest()->getParam('posts_id')]);
}
return $resultRedirect->setPath('*/*/');
}
I have enabled DB Query Log. {folder path}\magento2\var\debug\db.log. Instead of INSERT query, it's executing UPDATE query.
It always print UPDATE query in the log file, so INSERT query is not executing. Don't know what's wrong.
Temporarily i'm doing this, but it's not perfect solution. Issue with INSERT only, Update/Edit is working fine
if ($id) {
$model->save();
} else {
// START MANUAL SAVE DATA
$this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection');
$connection = $this->_resources->getConnection();
$themeTable = $this->_resources->getTableName('<table_name>');
$sql = "<INSERT QUERY>");";
$connection->query($sql);
// END MANUAL SAVE DATA
}