4

I am trying to save data from a custom module with custom table, but the data is not saving.

For this I have written the code below.

setup

<?php

namespace Learning\ContactUS\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface
{


    /**
     * Installs DB schema for a module
     *
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;

        $installer->startSetup();

        $table = $installer->getConnection()
            ->newTable($installer->getTable('contact_us'))
            ->addColumn('contact_us_id',Table::TYPE_SMALLINT,null,['identity' => true, 'nullable' => false, 'primary' => true],'Contact ID')
            ->addColumn('fullname', Table::TYPE_TEXT, 255, ['nullable' => true, 'default' => null])
            ->addColumn('company', Table::TYPE_TEXT, 255, ['nullable' => true, 'default' => null])
            ->addColumn('address', Table::TYPE_TEXT, 255, ['nullable' => false], 'Address')
            ->addColumn('city_state_zip_code', Table::TYPE_TEXT, 255, ['nullable' => false], 'City State Zip Code')
            ->addColumn('country', Table::TYPE_TEXT, 255, ['nullable' => false], 'Country')
            ->addColumn('phone', Table::TYPE_TEXT, 255, ['nullable' => false], 'Phone')
            ->addColumn('email', Table::TYPE_TEXT, 255, ['nullable' => false], 'Email')
            ->addColumn('Subject', Table::TYPE_TEXT, 255, ['nullable' => false], 'Subject')
            ->addColumn('content', Table::TYPE_TEXT, '2M', [], 'Content')
            ->addColumn('department', Table::TYPE_TEXT, 255, ['nullable' => false], 'Department')
            ->addColumn('creation_time', Table::TYPE_DATETIME, null, ['nullable' => false], 'Creation Time')
            ->addColumn('update_time', Table::TYPE_DATETIME, null, ['nullable' => false], 'Update Time')
            ->setComment('Contact US');

        $installer->getConnection()->createTable($table);

        $installer->endSetup();
    }


}

Model

<?php
namespace Learning\ContactUS\Model;

class ContactUS extends \Magento\Framework\Model\AbstractModel
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('Learning\ContactUS\Model\ResourceModel\ContactUS');
    }
}

Model/ResourceModel

<?php
namespace Learning\ContactUS\Model\ResourceModel;

class ContactUS extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{

    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('contactus', 'contact_us_id');
    }

}

Model/ResourceModel/ContactUS/collection.php

<?php
namespace Learning\ContactUS\ResourceModel\ContactUS;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{

    /**
     * @var string
     */
    protected $_idFieldName = 'contact_us_id';

    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('Learning\ContactUS\Model\ContactUS', 'Learning\ContactUS\Model\ResourceModel\ContactUS');
        $this->_map['fields']['contact_us_id'] = 'main_table.contact_us_id';
    }


}

Save.php

<?php
namespace Learning\ContactUS\Controller\Index;


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

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Learning\ContactUS\Model\ContactUsFactory
     */
    protected $contactUsFactory;


    /**
     * @var \Learning\ContactUS\Model\ContactUs
     */
    protected $contactUS;


    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Learning\ContactUS\Model\ContactUsFactory $contactUsFactory
     * @param \Learning\ContactUS\Model\ContactUs $contactUs
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Learning\ContactUS\Model\ContactUsFactory $contactUsFactory,
        \Learning\ContactUS\Model\ContactUs $contactUs
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->contactUsFactory = $contactUsFactory;
        $this->contactUS = $contactUs;
        parent::__construct($context);
    }
    /**
     * Default customer account page
     *
     * @return void
     */
    public function execute()
    {

        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        try{

            $request = $this->getRequest()->getParams();
            $full_name = $request['fullname'];
            $company = $request['company'];
            $address = $request['address'];
            $city_state = $request['city_state'];
            $country = $request['country_id'];
            $telephone = $request['telephone'];
            $email = $request['email'];
            $subject = $request['subject'];
            $comment = $request['comment'];
            $sales = $request['sales'];

            $this->contactUS->setFullname($full_name);
            $this->contactUS->setCompany($company);
            $this->contactUS->setAddress($address);
            $this->contactUS->setCityStateZipCode($city_state);
            $this->contactUS->setCountry($country);
            $this->contactUS->setPhone($telephone);
            $this->contactUS->setEmail($email);
            $this->contactUS->setSubject($subject);
            $this->contactUS->setContent($comment);
            $this->contactUS->setDepartment($sales);

            $this->contactUsFactory->create()->save($this->contactUS);


            $message = __('Thank you for Contact US one of the Employee will Contact you');
            $this->messageManager->addSuccessMessage($message);

            $this->resultPageFactory->create();
            return $resultRedirect->setPath('contactus/index/index');

        }catch (\Exception $e){
            $this->messageManager->addException($e, __('We can\'t submit your request, Please try again.'));
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            return $resultRedirect->setPath('contactus/index/index');
        }

    }

}
?>

Any help on this?

2
  • Did you run upgrade command after writing the code? Dec 8 '16 at 7:13
  • check my updated answer Dec 8 '16 at 7:42
6

Replace below code:

            $this->contactUS->setFullname($full_name);
            $this->contactUS->setCompany($company);
            $this->contactUS->setAddress($address);
            $this->contactUS->setCityStateZipCode($city_state);
            $this->contactUS->setCountry($country);
            $this->contactUS->setPhone($telephone);
            $this->contactUS->setEmail($email);
            $this->contactUS->setSubject($subject);
            $this->contactUS->setContent($comment);
            $this->contactUS->setDepartment($sales);

            $this->contactUsFactory->create()->save($this->contactUS);

To:

 $contactUs = $this->contactUsFactory->create();
        $contactUs->setFullname($full_name);
        $contactUs->setCompany($company);
        $contactUs->setAddress($address);
        $contactUs->setCityStateZipCode($city_state);
        $contactUs->setCountry($country);
        $contactUs->setPhone($telephone);
        $contactUs->setEmail($email);
        $contactUs->setSubject($subject);
        $contactUs->setContent($comment);
        $contactUs->setDepartment($sales);
        $contactUs->save();

EDIT:

Your namespace wrong for collection

namespace Learning\ContactUS\ResourceModel\ContactUS;

change to

namespace Learning\ContactUS\Model\ResourceModel\ContactUS;
1
  • Yes I forgot to add the Model in Namespace. Now working fine. Thank you.
    – Bojjaiah
    Dec 8 '16 at 8:28
4

try it like this:

<?php
namespace Learning\ContactUS\Controller\Index;


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

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Learning\ContactUS\Model\ContactUsFactory
     */
    protected $contactUsFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Learning\ContactUS\Model\ContactUsFactory $contactUsFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Learning\ContactUS\Model\ContactUsFactory $contactUsFactory,
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->contactUsFactory = $contactUsFactory;
        parent::__construct($context);
    }
    /**
     * Default customer account page
     *
     * @return void
     */
    public function execute()
    {

        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        try{

            $request = $this->getRequest()->getParams();
            $full_name = $request['fullname'];
            $company = $request['company'];
            $address = $request['address'];
            $city_state = $request['city_state'];
            $country = $request['country_id'];
            $telephone = $request['telephone'];
            $email = $request['email'];
            $subject = $request['subject'];
            $comment = $request['comment'];
            $sales = $request['sales'];

            $contactUs = $this->contactUsFactory->create();
            $contactUs->setFullname($full_name);
            $contactUs->setCompany($company);
            $contactUs->setAddress($address);
            $contactUs->setCityStateZipCode($city_state);
            $contactUs->setCountry($country);
            $contactUs->setPhone($telephone);
            $contactUs->setEmail($email);
            $contactUs->setSubject($subject);
            $contactUs->setContent($comment);
            $contactUs->setDepartment($sales);

            $contactUs->save();


            $message = __('Thank you for Contact US one of the Employee will Contact you');
            $this->messageManager->addSuccessMessage($message);

            $this->resultPageFactory->create();
            return $resultRedirect->setPath('contactus/index/index');

        }catch (\Exception $e){
            $this->messageManager->addException($e, __('We can\'t submit your request, Please try again.'));
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            return $resultRedirect->setPath('contactus/index/index');
        }

    }

}
5
  • Base table or view not found: 1146 Table demo.contactus doesn't exist. Error is came.
    – Bojjaiah
    Dec 8 '16 at 7:20
  • this means you did not create the table or you didn't configure your resource model properly to use that table.
    – Marius
    Dec 8 '16 at 7:21
  • created table also from my demo database. see my thread updated. help me where I went wrong?
    – Bojjaiah
    Dec 8 '16 at 7:25
  • it's working fine. but i'm not getting this "$this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);" what is the meaning of this? Mar 9 '18 at 13:59
  • Instantiates a class that implements the logger interface and logs a critical error in case there was a problem.
    – Marius
    Mar 9 '18 at 16:26

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.