2

Can anyone help me to save form values & submit to grid and database ?

closed as too broad by Jai, Priyank, Dhiren Vasoya, Murtuza Zabuawala, Piyush Jun 4 '18 at 4:49

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • Can you explain more details? – Khoa TruongDinh Jun 2 '18 at 9:17
  • i have a two custom fields in frontend after submit, need to save in db and admin section grid – shivashankar m Jun 2 '18 at 9:19
  • Thanks for the answer but i need a frontend form submit to admin grid – shivashankar m Jun 2 '18 at 10:31
5

For save record in Database :

=> Create a /app/code/Company/Blog/Setup/InstallSchema.php file :

<?php

namespace Company\Blog\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
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $tableName = $installer->getTable('company_blog');
        // Check if the table already exists
        if ($installer->getConnection()->isTableExists($tableName) != true) {
            // Create company_blog table
            $table = $installer->getConnection()
                ->newTable($tableName)
                ->addColumn(
                    'id',
                    Table::TYPE_INTEGER,
                    null,
                    [
                        'identity' => true,
                        'unsigned' => true,
                        'nullable' => false,
                        'primary' => true
                    ],
                    'ID'
                )
                ->addColumn(
                    'blog_title',
                    Table::TYPE_TEXT,
                    null,
                    ['nullable' => false, 'default' => ''],
                    'Title'
                )
                ->addColumn(
                    'blog_content',
                    Table::TYPE_TEXT,
                    null,
                    ['nullable' => false, 'default' => ''],
                    'Content'
                )
                ->addColumn(
                    'user_email',
                    Table::TYPE_TEXT,
                    null,
                    ['nullable' => false, 'default' => ''],
                    'Email'
                ) 
                ->addColumn(
                    'created_date',
                    Table::TYPE_DATETIME,
                    null,
                    ['nullable' => false],
                    'Created Date'
                )
                ->addColumn(
                    'status',
                    Table::TYPE_SMALLINT,
                    null,
                    ['nullable' => false, 'default' => '0'],
                    'Status'
                )

                ->setComment('Company Blog')
                ->setOption('type', 'InnoDB')
                ->setOption('charset', 'utf8');
            $installer->getConnection()->createTable($table);
        }

        $installer->endSetup();
    }
}

=> Create a model file /app/code/Company/Blog/Model/Blog.php :

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Company\Blog\Model;
use Magento\Framework\Model\AbstractModel;

class Blog extends \Magento\Framework\Model\AbstractModel {

    protected function _construct() {
        $this->_init('Company\Blog\Model\ResourceModel\Blog');
    }
}

=> Create a resource model file /app/code/Company/Blog/Model/ResourceModel/Blog.php :

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Company\Blog\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Blog extends AbstractDb
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('company_blog', 'id');
    }
}

=> Create a collection file /app/code/Company/Blog/Model/ResourceModel/Blog/Collection.php :

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Company\Blog\Model\ResourceModel\Blog;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection{
    protected function _construct()
    {
        $this->_init('Company\Blog\Model\Blog', 'Company\Blog\Model\ResourceModel\Blog');
    }
}

=> Create /app/code/Company/Blog/Controller/Index/Save.php Controller :

<?php
namespace Company\Blog\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Company\Blog\Model\BlogFactory;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Session\SessionManagerInterface;

class Save extends Action
{

    protected $_modelBlogFactory;
    protected $resultPageFactory;
    protected $_sessionManager;

    public function __construct(
        Context $context,
        BlogFactory $modelBlogFactory,
        PageFactory  $resultPageFactory,
        SessionManagerInterface $sessionManager
    )
    {
        parent::__construct($context);
        $this->_modelBlogFactory = $modelBlogFactory;
        $this->resultPageFactory = $resultPageFactory;
        $this->_sessionManager = $sessionManager;
    }

    public function execute()
    {   
        $resultRedirect     = $this->resultRedirectFactory->create();
        $BlogModel          = $this->_modelBlogFactory->create();
        $data               = $this->getRequest()->getPost(); 
        $date               = date('Y-m-d h:i:sa'); 

        $BlogModel->setData('blog_title', $data['blog_title']);
        $BlogModel->setData('blog_content', $data['blog_content']);
        $BlogModel->setData('user_email', $data['user_email']);
        $BlogModel->setData('created_date', $date);
        $BlogModel->setData('status', $data['status']);

        $BlogModel->save();

        $this->_redirect('blog/index');
        $this->messageManager->addSuccess(__('The data has been saved.'));
    }
}

=> Follow the steps to display data in grid :

/app/code/Company/Blog/etc/adminhtml/menu.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Backend/etc/menu.xsd">
    <menu>
        <add id="Company_Blog::view" title="Company Blog" module="Company_Blog" sortOrder="1" resource="Company_Blog::view"/>

        <add id="Company_Blog::display" title="Blog Post" translate="title" module="Company_Blog" sortOrder="20" parent="Company_Blog::content_blog" action="blog/grid/index" resource="Company_Blog::display"/>
    </menu>
</config>

/app/code/Company/Blog/etc/adminhtml/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="admin">
        <route id="blog" frontName="blog">
            <module name="Company_Blog" before="Magento_Adminhtml" />
        </route>
    </router>
</config>

/app/code/Company/Blog/Controller/Adminhtml/Grid/Index.php

<?php
namespace Company\Blog\Controller\Adminhtml\Grid;

use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\App\Action;
class Index extends Action
{

    protected $resultPageFactory;


    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;

    }


    public function execute()
    {

        $resultPage = $this->resultPageFactory->create();
        $resultPage->setActiveMenu('Company_Blog::display');
        $resultPage->addBreadcrumb(__('CMS'), __('CMS'));
        $resultPage->addBreadcrumb(__('Manage Grid View'), __('Manage Grid View'));
        $resultPage->getConfig()->getTitle()->prepend(__('Manage  Blog'));

        return $resultPage;
    }
}

/app/code/Company/Blog/Controller/Adminhtml/Grid/Grid.php

<?php
/**
 *
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Company\Blog\Controller\Adminhtml\Grid;

class Grid extends  \Magento\Backend\App\Action
{
    /**
     * Queue list Ajax action
     *
     * @return void
     */
    public function execute()
    {
       $this->_view->loadLayout(false);
        $this->_view->getLayout()->getMessagesBlock()->setMessages($this->messageManager->getMessages(true));
        $this->_view->renderLayout();
    }
}

/app/code/Company/Blog/Block/Adminhtml/Grid.php

<?php
namespace Company\Blog\Block\Adminhtml;

class Grid extends \Magento\Backend\Block\Widget\Container
{

    protected $_template = 'grid/view.phtml';

    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        array $data = []
    ) {

        parent::__construct($context, $data);
    }

    protected function _prepareLayout()
    {

        $addButtonProps = [
            'id' => 'add_new_grid',
            'label' => __('Add New'),
            'class' => 'add',           
            'button_class' => '',
            'class_name' => 'Magento\Backend\Block\Widget\Button\SplitButton',
            'options' => $this->_getAddButtonOptions(),
        ];
        $this->buttonList->add('add_new', $addButtonProps);

        $this->setChild(
            'grid',
           $this->getLayout()->createBlock('Company\Blog\Block\Adminhtml\Grid\Grid', 'grid.view.grid')
        );
        return parent::_prepareLayout();
    }


    protected function _getAddButtonOptions()
    {

        $splitButtonOptions[] = [
            'label' => __('Add New'),
            'onclick' => "setLocation('" . $this->_getCreateUrl() . "')"
        ]; 
        return $splitButtonOptions;
    }


    protected function _getCreateUrl()
    {
        return $this->getUrl(
            'blog/*/new'
        );
    }


    public function getGridHtml()
    {
        return $this->getChildHtml('grid');
    }
}

=> For preparing columns in grid :

/app/code/Company/Blog/Block/Adminhtml/Grid/Grid.php

<?php
namespace Company\Blog\Block\Adminhtml\Grid;

class Grid extends \Magento\Backend\Block\Widget\Grid\Extended
{
    protected $moduleManager;

    protected $_blogFactory; 

    protected $_status;   
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Company\Blog\Model\BlogFactory $blogFactory,
        \Company\Blog\Model\Status $status,
        \Magento\Framework\Module\Manager $moduleManager,
        array $data = []
    ) {

        $this->_blogFactory = $blogFactory;
        $this->_status = $status;
        $this->moduleManager = $moduleManager;
        parent::__construct($context, $backendHelper, $data);
    } 

    protected function _construct()
    {
        parent::_construct();
        $this->setId('gridGrid');
        $this->setDefaultSort('id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        $this->setVarNameFilter('grid_record');

    } 

    protected function _prepareCollection()
    {

        $collection = $this->_blogFactory->create()->getCollection();
        $this->setCollection($collection);
        parent::_prepareCollection();

        return $this;
    }

    protected function _prepareColumns()
    {

         $this->addColumn(
            'id',
            [
                'header' => __('ID'),
                'type' => 'number',
                'index' => 'id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );

        $this->addColumn(
            'blog_title',
            [
                'header' => __('Title'),
                'index' => 'blog_title',                
                'class' => 'xxx'
            ]
        );

        $this->addColumn(
            'user_email',
            [
                'header' => __('User'),
                'index' => 'user_email',                
                'class' => 'xxx'
            ]

        );


        $this->addColumn(
            'status',
            [
                'header' => __('Status'),
                'index' => 'status',
                'type' => 'options',                
                'options' => $this->_status->getOptionArray()
            ]
        );


        $this->addColumn(
            'created_date',
            [
                'header' => __('Created At'),
                'index' => 'created_date'
            ]
        );


        $this->addColumn(
            'edit',
            [
                'header' => __('Edit'),
                'type' => 'action',
                'getter' => 'getId',
                'actions' => [
                    [
                        'caption' => __('Edit'),
                        'url' => [
                            'base' => 'blog/*/edit'
                        ],
                        'field' => 'id'
                    ]
                ],
                'filter' => false,
                'sortable' => false,
                'index' => 'stores',
                'header_css_class' => 'col-action',
                'column_css_class' => 'col-action'
            ]
        );

        $this->addColumn(
            'delete',
            [
                'header' => __('Delete'),
                'type' => 'action',
                'getter' => 'getId',
                'actions' => [
                    [
                        'caption' => __('Delete'),
                        'url' => [
                            'base' => 'blog/*/delete'
                        ],
                        'field' => 'id'
                    ]
                ],
                'filter' => false,
                'sortable' => false,
                'index' => 'stores',
                'header_css_class' => 'col-action',
                'column_css_class' => 'col-action'
            ]
        );




        $block = $this->getLayout()->getBlock('grid.bottom.links');
        if ($block) {
            $this->setChild('grid.bottom.links', $block);
        }

        return parent::_prepareColumns();
    }


    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('id');
        $this->getMassactionBlock()->setFormFieldName('id');

        $this->getMassactionBlock()->addItem(
            'delete',
            [
                'label' => __('Delete'),
                'url' => $this->getUrl('blog/*/massDelete'),
                'confirm' => __('Are you sure?')
            ]
        );

        $statuses = $this->_status->toOptionArray();

        array_unshift($statuses, ['label' => '', 'value' => '']);
        $this->getMassactionBlock()->addItem(
            'status',
            [
                'label' => __('Change status'),
                'url' => $this->getUrl('blog/*/massStatus', ['_current' => true]),
                'additional' => [
                    'visibility' => [
                        'name' => 'status',
                        'type' => 'select',
                        'class' => 'required-entry',
                        'label' => __('Status'),
                        'values' => $statuses
                    ]
                ]
            ]
        );


        return $this;
    }


    public function getGridUrl()
    {
        return $this->getUrl('blog/*/grid', ['_current' => true]);
    }


    public function getRowUrl($row)
    {
        return $this->getUrl(
            'blog/*/edit',
            ['id' => $row->getId()]
        );
    }
}

=> For get status value in grid :

/app/code/Company/Blog/Model/Status.php

<?php

namespace Company\Blog\Model;

class Status implements \Magento\Framework\Option\ArrayInterface
{

    const STATUS_ENABLED = 1;

    const STATUS_DISABLED = 0;


    public function toOptionArray()
    {
        $result = [];

        foreach (self::getOptionArray() as $index => $value) {
            $result[] = ['value' => $index, 'label' => $value];
        }

        return $result;
    }


    public static function getOptionArray()
    {
        return [self::STATUS_ENABLED => __('Enabled'), self::STATUS_DISABLED => __('Disabled')];
    }


    public function getAllOptions()
    {
        $result = [];

        foreach (self::getOptionArray() as $index => $value) {
            $result[] = ['value' => $index, 'label' => $value];
        }

        return $result;
    }


    public function getOptionText($optionId)
    {
        $options = self::getOptionArray();

        return isset($options[$optionId]) ? $options[$optionId] : null;
    }
}

Last steps are files is view layout xml, here also we have to layout for index and grid

/app/code/Company/Blog/view/adminhtml/layout/blog_grid_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="formkey"/>
    <update handle="blog_grid_block"/>
    <body>
        <referenceContainer name="content">
            <block class="Company\Blog\Block\Adminhtml\Grid" name="adminhtml.blog.grid.container"/>
        </referenceContainer>
    </body>
</page>

/app/code/Company/Blog/view/adminhtml/layout/blog_grid_grid.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/layout_generic.xsd">
    <update handle="formkey"/>
    <container name="root" label="Root">
        <block class="Company\Blog\Block\Adminhtml\Grid\Grid" name="admin.grid.grid"/>
    </container>
</layout>

/app/code/Company/Blog/view/adminhtml/templates/grid/view.phtml

<?php echo $block->getGridHtml() ?>

clear cache and you can see grid page

  • Hi @Emipro tech Thanks for the answer but i need a frontend form submit to admin grid – – shivashankar m Jun 2 '18 at 10:31
  • Your form data submit in database and fetch that record in admin grid. Right? – Emipro Technologies Pvt. Ltd. Jun 2 '18 at 10:40
  • ok thanks i will try it and get back to you – shivashankar m Jun 2 '18 at 10:41

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