0

I want to know how I can create a module that uses the Form Component. Nothing advanced, I just want to know how to make a simple form that can read and write entries from a database, for example a form where you can register and output users. I can't find any good examples. Any guides or tips are very welcomed.

1

1. Creating Basic simple Module

First create folder structure

[Magentoroot]/app/code/Company/Module/

Create files app/code/Company/Module/registration.php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Company_Module',
    __DIR__
);

app/code/Company/Module/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Company_Module" setup_version="1.0.0"></module>
</config>

creating frontend router configuration file app/code/Company/Module/etc/frontend/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="standard">
        <route id="routername" frontName="routername">
            <module name="Company_Module" />
        </route>
    </router>
</config>

2. Creating Table and resource model

create Setup folder add InstallSchema file app/code/Company/Module/Setup/InstallSchema.php

<?php
namespace Company\Module\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;

class InstallSchema implements InstallSchemaInterface
{
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $table = $installer->getConnection()->newTable(
            $installer->getTable('table_name')
        )->addColumn(
            'id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'nullable' => false, 'primary' => true],
            'ID'
        )->addColumn(
            'column1',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => true],
            'column1'
        )->addColumn(
            'column2',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => true],
            'column2'
        )->addColumn(
            'column3',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => true],
            'column3'    
        )->setComment(
            'Your table name'
        );
        $installer->getConnection()->createTable($table);
        $installer->endSetup();
    }
}

app/code/Company/Module/Model/Mymodel.php

<?php
namespace Company\Module\Model;

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

app/code/Company/Module/Model/ResourceModel/Mymodel.php

<?php
namespace Company\Module\Model\ResourceModel;

class Mymodel extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        // table name and primary key
        $this->_init('table_name', 'id');
    }
}

app/code/Company/Module/Model/ResourceModel/Mymodel/Collection.php

<?php
namespace Company\Module\Model\ResourceModel\Mymodel;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('Company\Module\Model\Mymodel', 'Company\Module\Model\ResourceModel\Mymodel');
        $this->_map['fields']['page_id'] = 'main_table.page_id';
    }

}

3. Creating Controllers

Here i create two action index and submit app/code/Company/Module/Controller/Index/Index.php

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

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;


class Index extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
    protected $session;
    public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory, Session $customerSession )
    {
        $this->_resultPageFactory = $resultPageFactory;
        $this->session = $customerSession;
        parent::__construct($context);
    }

    public function execute()
    {
        // echo "test"; die;
        $resultPage = $this->_resultPageFactory->create();
        return $resultPage;
    }
}

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

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

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;

class Submit extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
    protected $session;
    protected $_objectManager;

    public function __construct(
        Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        Session $customerSession,
        \Magento\Framework\ObjectManagerInterface $objectManager )
    {
        $this->_resultPageFactory = $resultPageFactory;
        $this->session = $customerSession;
        $this->_objectManager = $objectManager;
        parent::__construct($context);
    }

    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        $model = $this->_objectManager->create('Company\Module\Model\Mymodel');
        $model->setData($data);
        try {
            $model->save();
            $this->messageManager->addSuccess(__('Data Successfully Added.'));
        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
        }
        $resultRedirect = $this->resultRedirectFactory->create();
        return $resultRedirect->setPath('*/*/index');
    }
}

1. Creating layout and templates

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

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Company\Module\Block\Myblock" name="my_first_form" template="index.phtml"  />
        </referenceContainer>
    </body>
</page>

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

<h1>My First Form</h1>

<form action="<?php echo $this->getUrl('*/*/submit') ?>" method="post">

    column1 <input name="column1" type="text">
    column2 <input name="column2" type="text">
    column3 <input name="column3" type="text">
    <input type="submit" value="submit">
</form>

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

<?php
namespace Company\Module\Block;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Myblock extends \Magento\Framework\View\Element\Template
{
    //add your block files
}

Finally Open your terminal goto your magento root path run this command

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

Now you can access you [Your Magent Root Url]/routername/

  • I get SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mag2new.test_table' doesn't exist, query was: DESCRIBE test_table when trying to submit. Any tips? – Oscar Apr 3 '18 at 7:54
  • table not created , while running setup:upgrade are you get any error? – mohan Apr 3 '18 at 9:20
  • Nope, no errors. I did setup:db-data, setup:db-schema and cleaned the cache as well without any success. Also tried removing the module in the setup_module table. – Oscar Apr 3 '18 at 9:34

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.