5

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 
}
  • I believe posts_id should be automatically created, what if you skip/comment these lines: $id = $this->getRequest()->getParam('posts_id'); if ($id) { $model->load($id); } – Rakesh Shewale Aug 22 '16 at 6:51
  • Nope. Checked. That's not the case. It's same code as CMS Module. I just changed as per my modules requirement for configuration – Ankit Shah Aug 22 '16 at 7:43
2

i was facing same problem while trying to save data but further i use this code to save and it was working fine.

public function execute()
{
    $data = $this->getRequest()->getPostValue();

    if (!$data) {
        $this->_redirect('<module_name>/<controller_name>/new');
        return;
    }
    try {
        $rowData = $this->_objectManager->create('<vendor_name>\<module_name>\Model\<model_name>');


        if (isset($data['item_id']) && $data['item_id'] == '') {
            unset($data['item_id']);
        }

        $rowData->setData($data);

        $rowData->save();

        $this->messageManager->addSuccess(__('Item has been successfully saved.'));
    } catch (Exception $e) {
        $this->messageManager->addError(__($e->getMessage()));
    }
    $this->_redirect('*/*/');
}

Thanks. :)

|improve this answer|||||
  • This is Default Magento 2 Way but it's not working in my case. – Ankit Shah Oct 6 '16 at 1:17
-1

create a Controller action for the module.

namespace <Namespace>\<Modulename>\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}

Let’s Create a simple Block file for our Module

<?php
namespace <Namespace>\<Modulename>\Block;
class <Blockname> extends \Magento\Framework\View\Element\Template
{
public function _prepareLayout()
{
return parent::_prepareLayout();
}
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.