Magento2 – How to Save Data to Database

databasemagento2

I am trying to save form submitted details to database in magento2 but it is not working. i have tried different options that given by stackoverflow answers but none of them works for me.
my controller file is given below

<?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Suyati\Scontact\Controller\Index;

class Post extends \Suyati\Scontact\Controller\Index
{
    /**
     * Post user question
     *
     * @return void
     * @throws \Exception
     */
    public function execute()
    {
        $post = $this->getRequest()->getPostValue();
        if (!$post) {
            $this->_redirect('*/*/');
            return;
        }

        $this->inlineTranslation->suspend();
        try {
            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($post);

            $error = false;

            if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['comment']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                $error = true;
            }
            if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
                $error = true;
            }
            if ($error) {
                throw new \Exception();
            }

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

            $Format = $objectManager->create('Suyati\Scontact\Model\Contacts');
            $Format->setName(trim($post['name'])); 
            $Format->setEmail(trim($post['Email']));
            $Format->save();*/

            $model = $this->_objectManager->create('Suyati\Scontact\Model\Contacts');
            $model->setData($post);
            $model->save();
            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $transport = $this->_transportBuilder
                ->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope))
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
                ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
                ->setReplyTo($post['email'])
                ->getTransport();

            $transport->sendMessage();
            $this->inlineTranslation->resume();
            $this->messageManager->addSuccess(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->_redirect('scontact/index');
            return;
        } catch (\Exception $e) {
            $this->inlineTranslation->resume();
            $this->messageManager->addError(
                __('We can\'t process your request right now. Sorry, that\'s all we know.')
            );
            $this->_redirect('scontact/index');
            return;
        }
    }
}

Resource model

<?php

namespace Suyati\Scontact\Model\Resource;

class Contacts extends \Magento\Framework\Model\Resource\Db\AbstractDb
{
public function _construct()
{
    $this->_init('suyati_contacts', 'contacts_id');
}
}

Resource collection

<?php


namespace Suyati\Scontact\Model\Resource\Contacts;

class Collection extends \Magento\Framework\Model\Resource\Db\Collection\AbstractCollection
{
public function _construct()
{
    $this->_init('Suyati\Scontact\Model\Contacts', 'Suyati\Scontact\Model\Resource\Contacts');
}
}

Best Answer

If your are using front-end, you need to extend the Front controller with

\Magento\Framework\App\Action\Action

Model extend \Magento\Framework\Model\AbstractModel

Resource Model extend \Magento\Framework\Model\ResourceModel\Db\AbstractDb

Collection extend \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection

Follow the working reference code and check your post data carefully.

class Post extends \Magento\Framework\App\Action\Action
{

    public function __construct(
        \Magento\Framework\App\Action\Context $context

    ) {
        parent::__construct($context);
    }   
    public function execute()
    {
$data = $this->getRequest()->getPostValue();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();       
$question = $objectManager->create('Suyati\Scontact\Model\Contacts');
$question->setData($data);
//$question->setEmail('test@test.com');
//$question->setQuery('Question Description');
$question->save();
$this->messageManager->addSuccess( __('Thanks for your valuable feedback.') );
//$this->messageManager->addSuccess('Query subbmitted successfully.');
$this->_redirect('*/*/');
return;



    }
}

Use constructor instead of Object Manager to create instances.

Hope this helps.