1

I just want to save data in the database but the data calculated in controller so is it possible to store the data in database using the model in the controller.

  • 1
    yes you can save data from controller without calculation from model – Rakesh Jesadiya Jul 1 '16 at 10:55
  • @Rakesh please help me out with an example brother how to use that. – Ankush Chauhan Jul 1 '16 at 10:57
  • you can do code same as model inside controller – Rakesh Jesadiya Jul 1 '16 at 11:00
1

You can use objectManager to instantiate a model, then you can set the data and save.

for example, within your controller's execute method:

$id = $this->getRequest()->getParam('id');
if ($id) {
   $model = $this->_objectManager->create('Path\To\Model');
   $model->load($id);
   $model->setData('name', 'value');
   try {
      $model->save();
   } catch (\Exception $e) {
      //handle exception
   }
}
  • 1
    Do not user object manager directly. Use Path\To\ModelFactory instead. – Marius Jul 1 '16 at 11:05
  • Both methods will work. Core modules use objectManager for their CRUD controllers. – Aaron Allen Jul 1 '16 at 11:59
  • I didn't say it doesn't work. I just said it is wrong. If you find it in the core it means that part didn't get refactored yet. It is a very bad practice to use object manager outside factories and proxies. – Marius Jul 1 '16 at 12:45
1

Here is an example on how to use models with the help of class constructor:

namespace YOUR\MODULE\Controller\CONTROLLER;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
/* OR next for backend controller
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;*/

use PATH\TO\ModelFactory;

class ActionName extends Action
{
    protected $_modelFactory;

    public function __construct(
        Context $context,
        ModelFactory $modelFactory
    ) {
        $this->_modelFactory = $modelFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $model = $this->_modelFactory->create();
        // ...
    }
}

After changes made in controller, you need to do after-compilation with the help of the following command:

php bin/magento setup:di:compile

Regards, Plumrocket Team

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.