Magento 2 Database – How to Save Data to Database

databasemagento2table

I Need to store form data to database, I follow, model/ResourceModel way,

This below my controller code: SetData() method not working.

<?php

namespace ChennaiBox\CustomerAccount\Controller\Profile;

 class Save extends \Magento\Framework\App\Action\Action
 {
protected $storeManager;
protected $subscriberFactory;
protected $_objectManager;
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Customer\Model\Session $customerSession,        
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
    \Magento\Framework\ObjectManagerInterface $objectManager
) {
    $this->storeManager = $storeManager;
    $this->subscriberFactory = $subscriberFactory;
    $this->customerSession = $customerSession;
    $this->_objectManager = $objectManager;
    parent::__construct($context, $customerSession);
}

/**
 * Save newsletter subscription preference action
 *
 * @return void|null
 */
public function execute()
{
    $cutomerEmail =(string)$this->customerSession->getCustomer()->getEmail();
    if ($cutomerEmail === null) {
        $this->messageManager->addError(__('Something went wrong while saving your subscription.'));
    } else {
        try {   

               $post = $this->getRequest()->getPostValue();
               $Format = $this->_objectManager->create('ChennaiBox\CustomerAccount\Model\Format');
               $Format->setCustomerid($cutomerEmail); 
               $Format->setFormat($post['type']);
               $Format->save();
              $this->messageManager->addSuccess(__('Profile has beem saved successfully.'));

                $this->_redirect('customer/account/');

                return;

            } catch (\Exception $e) {
                $this->messageManager->addError(__('Something went wrong while saving your profile.'));
            }
    }
   $this->_redirect('customer/account/');
}

}

This is my Controller File, I defined Construct for Object manager.

My table name is "email_format" and its have two columns, 1.customerid 2. format, Magento2 any other way to save data to database?, how to solve this problem?

Best Answer

Change your code as below:

$Format = $this->_objectManager->create('ChennaiBox\CustomerAccount\Model\Format');

changed to:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$Format = $objectManager->create('ChennaiBox\CustomerAccount\Model\Format');

You have used $this->_objectManager but you have not defined it in construct.