Magento如何创建使用表单组件的模块

1.创建基本简单模块

首先创建文件夹结构

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

创建文件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>

创建前端路由器配置文件 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.创建表和资源模型

创建安装文件夹添加InstallSchema文件 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.创建控制器

在这里,我创建两个动作索引并提交 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.创建布局和模板

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
}

最后打开终端转到magento root path运行此命令

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

现在您可以访问[Your Magent Root Url] / routername /

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论