0

3 i created custom module how can I insert data from my form to database

app/code/kamar/slider/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="kamar_slider" setup_version="1.0.0">
    </module>
</config>

app/code/kamar/slider/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'kamar_slider',
    __DIR__
);

app/code/kamar/slider/Setup/InstallSchema.php

<?php

namespace kamar\slider\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InstallSchema implements InstallSchemaInterface
{
    /**
     * Function install
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        //START table setup
                $table = $installer->getConnection()->newTable(
                    $installer->getTable('kavinga')
                )
                    ->addColumn(
                    'kid',
                    \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    null,
                    ['identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true,],
                    'Entity ID'
                )->addColumn(
                    'title',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    255,
                    ['nullable' => false,],
                    'Demo Title'
                );

                $installer->getConnection()->createTable($table);
        //        //END   table setup
    }
}

app/code/kamar/slider/etc/adminhtml/menu.xml

   <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">

    <menu>
        <add
        id="kamar_slider::menu"
        title="hassan kamar slider new module"
        module="kamar_slider"
        sortOrder="11"
        resource="Magento_Backend::content"
        />
        <add
                id="kamar_slider::addimage"
                title="add slider "
                module="kamar_slider"
                sortOrder="10"
                parent="kamar_slider::menu"
                action="slider/slider/index"
                resource="Magento_Backend::content"
        />



    </menu>
</config>

app/code/kamar/slider/etc/adminhtml/routes.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="slider" frontName="slider">
            <module name="kamar_slider"/>
        </route>
    </router>
</config>

app/code/kamar/slider/Controller/Adminhtml/Slider/Index.php

<?php

namespace kamar\slider\Controller\Adminhtml\Slider;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\App\Action;

/**
 * Class Index
 * @package kamar\slider\Controller\Adminhtml\Slider\Index
 */
class Index extends Action
{
    /**
     * Index resultPageFactory
     * @var PageFactory
     */
    protected $resultPageFactory;
    protected $_pageFactory;
    protected $_slider;


    /**
     * Index constructor.
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(Context $context,
         PageFactory $resultPageFactory)
    {
        $this->resultPageFactory = $resultPageFactory;
        return parent::__construct($context);
    }

    /**
     * Function execute
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute()
    {


      return $this->resultPageFactory->create();



    }
}

app/code/kamar/slider/view/adminhtml/layout/slider_slider_index.xml

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <body>
            <referenceContainer name="content">
                <block class="Magento\Backend\Block\Template"
                       template="kamar_slider::slider.phtml"/>
            </referenceContainer>
        </body>
    </page>

**app/code/kamar/slider/view/adminhtml/templates/slider.phtml**


    <form class="" action="<?php echo $this->getUrl("slider/index/index")?>" id="form1" method="get" enctype='multipart/form-data'>
        <fieldset class="fieldset">
            <legend class="legend"><span>Test Form For add image </span></legend><br>


            <div class="field note no-label">Write here anything you want.</div>

            <div class="field title">
                <label class="label" for="title"><span>Title</span></label>
                <div class="control">
                    <input name="title" id="title" title="title" value="" class="input-text" type="text">
                </div>
                <div></div>
            </div>



            <div class="field content">
                <label class="label" for="content"><span>Content</span></label>

            </div>
            <div class="field image">
                <label class="label" for="image"><span>Image</span></label>
                <div class="control">
                    <input name="image" id="image" title="Image" value="" class="input-file" type="file">
                </div>
            </div-->
        </fieldset>
        <div class="actions-toolbar">
            <div class="primary">
                <button type="submit" title="Submit" class="action submit primary" >
                    <span>Submit</span>


                </button>
                <div>
                <input name="form1" id="form1" type="hidden" value="true" >
                </div>
            </div>
        </div>
    </form>

app/code/kamar/slider/Model/slider.php

<?php

namespace kamar\slider\Model;

use \Magento\Framework\Model\AbstractModel;

class slider extends AbstractModel
{


    /**
     * Initialize resource model
     * @return void
     */
    public function _construct()
    {
        $this->_init('kamar\slider\Model\ResourceModel\slider');
    }

    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->getId()];
    }

    public function getDefaultValues()
    {
        $values = [];

        return $values;
    }


}

app/code/kamar/slider/Model/ResourceModel/slider.php

<?php

namespace kamar\slider\Model\ResourceModel;

use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class slider extends AbstractDb
{
    public function __construct(
        \Magento\Framework\Model\ResourceModel\Db\Context $context
    )
    {
        parent::__construct($context);
    }


    /**
     * Initialize resource
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init('kavinga', 'kid');
    }


}

app/code/kamar/slider/Model/ResourceModel/slider/Collection.php

<?php

namespace kamar\slider\Model\ResourceModel\slider;

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

class Collection extends AbstractCollection
{
    /**
     * Initialize resource collection
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init('kamar\slider\Model\slider', 'kamar\slider\Model\ResourceModel\slider');
    }
}
| improve this question | | | | |
0

You can create this following module to accept some data from frontend and can insert those data into your custom table follow the below guide to accepting data from the form on Magento frontend

Assuming you have the following module Company/Module.

Create the frontend router

/app/code/Company/Module/etc/frontend/routes.xml

Create a route to manage :

  • GET request wich going to display HTML form template
  • POST request wich going to send form data to Action Controller Class.
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="companymodule" frontName="companymodule">
            <module name="Company_Module"/>
        </route>
    </router>
</config>

Create the layout

/app/code/Company/Module/view/frontend/layout/module_index_booking.xml

Create a basic layout for associate the Block to the form page phtml template

<?xml version="1.0"?>
<page layout="2columns-left" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>HTML title - The booking form page</title>
    </head>
    <body>
        <referenceBlock name="navigation.sections" remove="true" />
        <referenceContainer name="content">
            <block class="Company\Module\Block\Booking" name="companymodule.booking" template="Company_Module::booking.phtml"/>
        </referenceContainer>
    </body>
</page>

Create the Block

/app/code/Company/Module/Block/Booking.php

Create a block with many functions you want for your form.

<?php

namespace Company\Module\Block;

class Booking extends \Magento\Framework\View\Element\Template
{
    /**
     * Construct
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template $context,
        array $data = []
    )
    {
        parent::__construct($context, $data);
       }

    /**
     * Get form action URL for POST booking request
     *
     * @return string
     */
    public function getFormAction()
    {
            // companymodule is given in routes.xml
            // controller_name is folder name inside controller folder
            // action is php file name inside above controller_name folder

        return '/companymodule/controller_name/action';
        // here controller_name is index, action is booking
    }
}

Create the template

/app/code/Company/Module/view/frontend/templates/booking.phtml

Create a template with your HTML form and add the form action corresponding to the routing.

<h1>Booking page</h1>

<form action="<?php echo $block->getFormAction() ?>" method="post">
    <input name="firstname" type="text">
    <input name="lastname" type="text">
    <input name="phone" type="text">
    <input name="bookingTime" type="date">
    <input type="submit" value="Send booking informations">
</form>

Create the Action Controller

/app/code/Company/Module/Controller/Index/Booking.php

Create an Action Controller to manage the requests on the route.

<?php

namespace Company\Module\Controller\Index;

use Magento\Framework\Controller\ResultFactory;

class Booking extends \Magento\Framework\App\Action\Action
{
    /**
     * Booking action
     *
     * @return void
     */
    public function execute()
    {
        // 1. POST request : Get booking data
        $post = (array) $this->getRequest()->getPost();

        if (!empty($post)) {
            // Retrieve your form data
            $firstname   = $post['firstname'];
            $lastname    = $post['lastname'];
            $phone       = $post['phone'];
            $bookingTime = $post['bookingTime'];

            // Doing-something with...

            // Display the succes form validation message
            $this->messageManager->addSuccessMessage('Booking done !');

            // Redirect to your form page (or anywhere you want...)
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
            $resultRedirect->setUrl('/companymodule/index/booking');

            return $resultRedirect;
        }
        // 2. GET request : Render the booking page 
        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }
}

In resuming you will have the following architecture :

app
  ├ code
  |   ├ Company
  |   |   ├ Module
  |   |   |   ├ Block
  |   |   |   |   ├ Booking.php
  |   |   |   ├ Controller
  |   |   |   |   ├ Index
  |   |   |   |   |   ├ Booking.php
  |   |   |   ├ etc
  |   |   |   |   ├ frontend
  |   |   |   |   |   ├ routes.xml
  |   |   |   ├ view
  |   |   |   |   ├ frontend
  |   |   |   |   |   ├ layout
  |   |   |   |   |   |   ├ module_index_booking.xml
  |   |   |   |   |   ├ templates
  |   |   |   |   |   |   ├ booking.phtml

Then run following commands :

php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush

Then you can access to your custom form page: http://localhost/companymodule/index/booking

*Happy coding! *

| improve this answer | | | | |

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.