스크래치에서 magento 2로 커스텀 모듈 개발을 만드는 방법은 무엇입니까?


15

magento 2에서 처음부터 사용자 정의 모듈 개발을 작성하는 방법은 다음과 같습니다.

1. 모듈을 만드는 방법

2. 데이터베이스 설치 및 업그레이드 방법

3. 모듈, 뷰 및 컨트롤러 레이어 생성 방법

4. 모든 모듈 구성 요소의 통합을 테스트하는 방법

6. Magento CLI 명령 생성 방법

7. Magento 2에서 예약 된 작업을 구성하는 방법

8. 메뉴 항목을 만드는 방법

9. ACL 리소스를 만드는 방법

  1. 사용자 정의 테이블을 사용하여 Magento에서 웹 API를 구현하는 방법

11. 관리자에서 사용자 지정 그리드를 만드는 방법

  1. UI 구성 요소를 사용하여 양식을 만들고 그리드로 저장 및 리디렉션하는 방법

모든 사람과 소스 코드를 공유하고 싶습니다


귀하의 질문은 무엇인가? 무엇이 문제 니?
Sohel Rana

@SohelRana 선생님, 저는 magento 2를 처음 사용합니다. 기본적으로 새로운 후보자는 사용자 정의 모듈 개발 중에 많은 문제를 겪으므로 누군가에게 도움이 될 소스 코드를 공유하는 것으로 생각했습니다. 나에게 제안이 있으시면 알려주십시오.
Pramod Kharade

@PramodKharade 귀하의 질문의 명확성을 높이고이 스택에서 더 큰 명성을 얻으려면 이러한 각 점을 별도의 질문으로 묻고 대답하는 것이 좋습니다. 귀하의 답변은 많은 문제를 해결하기 위해 내가 찾던 것과 정확히 같지만 stackexchange 검색 엔진을 사용하여 찾기가 매우 어렵습니다.
Joshua 홍수

@JoshuaFlood 감사합니다. 다음에 나는 별도의 질문과 대답으로 새로운 개념을 생각해 낼 것입니다. 다른 독자에게 도움이되도록 ans에 투표하십시오.
Pramod Kharade

404를 받고 있는데 다른 단계가 필요합니까?
Vivek Pandian

답변:


18

네임 스페이스 : Mastering \ Itdesire

1. 모듈을 만드는 방법

마스터 링 /Itdesire/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="Mastering_Itdesire" setup_version="1.0.1">
            <sequence>
                <module name="Magento_Catalog"/>
            </sequence>
        </module>
    </config>

마스터 링 /Itdesire/registration.php

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

2. 데이터베이스 설치 및 업그레이드 방법 :

스키마 설치 :

마스터 링 /Itdesire/Setup/InstallSchema.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of InstallSchema
 *
 * @author pramod
 */
namespace Mastering\Itdesire\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
{
    /**
     * {@inheritdoc}
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $table = $setup->getConnection()->newTable(
            $setup->getTable('mastering_itdesire_item')
        )->addColumn(
            'id',
            Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'nullable' => false, 'primary' => true],
            'Item ID'
        )->addColumn(
            'name',
            Table::TYPE_TEXT,
            255,
            ['nullable' => false],
            'Item Name'
        )->addIndex(
            $setup->getIdxName('mastering_itdesire_item', ['name']),
            ['name']
        )->setComment(
            'itdesire Items'
        );
        $setup->getConnection()->createTable($table);

        $setup->endSetup();
    }
}

데이터 설치 :

마스터 링 /Itdesire/Setup/InstallData.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Mastering\Itdesire\Setup;

/**
 * Description of InstallData
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    /**
     * {@inheritdoc}
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $setup->getConnection()->insert(
            $setup->getTable('mastering_itdesire_item'),
            [
                'name' => 'Item 1'
            ]
        );

        $setup->getConnection()->insert(
            $setup->getTable('mastering_itdesire_item'),
            [
                'name' => 'Item 2'
            ]
        );

        $setup->endSetup();
    }
}

업그레이드 스키마 :

마스터 링 /Itdesire/Setup/UpgradeSchema.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Mastering\Itdesire\Setup;

/**
 * Description of UpgradeSchema
 *
 * @author pramod
 */
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * {@inheritdoc}
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        if (version_compare($context->getVersion(), '1.0.1', '<')) {
            $setup->getConnection()->addColumn(
                $setup->getTable('mastering_itdesire_item'),
                'description',
                [
                    'type' => Table::TYPE_TEXT,
                    'nullable' => true,
                    'comment' => 'Item Description'
                ]
            );
        }

        $setup->endSetup();
    }
}

업그레이드 데이터 :

마스터 링 /Itdesire/Setup/UpgradeData.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Mastering\Itdesire\Setup;

/**
 * Description of UpgradeData
 *
 * @author pramod
 */
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;

class UpgradeData implements UpgradeDataInterface
{
    /**
     * {@inheritdoc}
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        if (version_compare($context->getVersion(), '1.0.1', '<')) {
            $setup->getConnection()->update(
                $setup->getTable('mastering_itdesire_item'),
                [
                    'description' => 'Default description'
                ],
                $setup->getConnection()->quoteInto('id = ?', 1)
            );
        }

        $setup->endSetup();
    }
}

3. 모델, 뷰 및 컨트롤러 레이어 생성 방법

컨트롤러 :

마스터 링 / 아이디어 / 컨트롤러 /Adminhtml/Index/Index.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Index
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Controller\Adminhtml\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action;
class Index extends Action{
    //put your code here
    public function execute() {
        /** @var \Magento\Framework\Controller\Result\Raw $result */
        $result = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $result->setContents('Hello Admins!');
        return $result;
    }

}

마스터 링 / 아이디어 / 컨트롤러 / 인덱스 /Index.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Index
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
class Index extends Action{
    //put your code here
    public function execute() {
        /** @var \Magento\Framework\Controller\Result\Raw $result */
        /*
        $result = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $result->setContents('Hello World!');
        return $result; */
      return $this->resultFactory->create(ResultFactory::TYPE_PAGE);
    }

}

마스터 링 /Itdesire/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="mastering" frontName="mastering">
            <module name="Mastering_Itdesire"/>
        </route>
    </router>
</config>

마스터 링 /Itdesire/view/frontend/layout/mastering_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 name="mastering_hello" class="Mastering\Itdesire\Block\Hello" template="hello.phtml"/>
        </referenceContainer>
    </body>
</page>

모델, 자원 모델 및 API :

마스터 링 / 아이디어 / 모델 /ResourceModel/Item/Collection.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Collection
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Model\ResourceModel\Item;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Mastering\Itdesire\Model\Item;
use Mastering\Itdesire\Model\ResourceModel\Item as ItemResource;
class Collection extends AbstractCollection {
    protected $_idFieldName = 'id';

    protected function _construct()
    {
        $this->_init(Item::class, ItemResource::class);
    }
}

마스터 링 / 아이디어 / 모델 /ResourceModel/Item.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Item
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Item extends AbstractDb {
   protected function _construct()
    {
        $this->_init('mastering_itdesire_item', 'id');
    }

}

마스터 링 / 아이디어 / 모델 /Config.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Mastering\Itdesire\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;

/**
 * Description of Config
 *
 * @author pramod
 */
class Config {
    const XML_PATH_ENABLED = 'mastering/general/enabled';

    private $config;

    public function __construct(ScopeConfigInterface $config)
    {
        $this->config = $config;
    }

    public function isEnabled()
    {
        return $this->config->getValue(self::XML_PATH_ENABLED);
    }
}

마스터 링 / 아이디어 / 모델 /Item.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Item
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Model;
use Magento\Framework\Model\AbstractModel;
class Item extends AbstractModel{
    //put your code here
    protected function _construct() {
        $this->_init(\Mastering\Itdesire\Model\ResourceModel\Item::class);
    }
}

마스터 링 / 아이디어 / 모델 /ItemRepository.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Mastering\Itdesire\Model;

/**
 * Description of ItemRepository
 *
 * @author pramod
 */
use Mastering\Itdesire\Api\ItemRepositoryInterface;
use Mastering\Itdesire\Model\ResourceModel\Item\CollectionFactory;
class ItemRepository implements ItemRepositoryInterface {
    private $collectionFactory;

    public function __construct(CollectionFactory $collectionFactory) {
        $this->collectionFactory = $collectionFactory;
    }

    public function getList() {
        return $this->collectionFactory->create()->getItems();
    }

}

보기 :

마스터 링 / 아이디어 / 블록 /Hello.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Hello
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Block;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Mastering\Itdesire\Model\ResourceModel\Item\Collection;
use Mastering\Itdesire\Model\ResourceModel\Item\CollectionFactory;
class Hello extends Template{
    //put your code here
    private $collectionFactory;
    public function __construct(Context $context,
            CollectionFactory $collectionFactory,
            array $data = array()) {
        $this->collectionFactory = $collectionFactory;
        parent::__construct($context, $data);
    }

   /**
     * @return \Mastering\Itdesire\Model\Item[]
     */
    public function getItems()
    {
        return $this->collectionFactory->create()->getItems();
    }
}

마스터 링 /Itdesire/view/frontend/templates/hello.phtml

<?php 
/***
 * @var \Mastering\Itdesire\Block\Hello $block
 * ***/

?>
<?php foreach ($block->getItems() as $item){

    ?>
<p>
    <?php echo $item->getName();?>: <?php echo $item->getDescription();?>
</p>
<?php } ?>

4. Magento CLI 명령 생성 방법 :

마스터 링 / 아이디어 / 콘솔 / 명령 /AddItem.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AddItem
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Mastering\Itdesire\Model\ItemFactory;
use Magento\Framework\Console\Cli;

class AddItem extends Command{

    const INPUT_KEY_NAME ="name";
    const INPUT_KEY_DESCRIPTION ="description";
    private $itemFactory;

    public function __construct(ItemFactory $itemFactory) {
        $this->itemFactory = $itemFactory;
        parent::__construct();
    }

    protected function configure() {
        $this->setName("itdesire:item:add")
                ->addArgument(
                               self::INPUT_KEY_NAME,
                               InputArgument::REQUIRED,
                               'Input Name'
                             )->addArgument(
                                     self::INPUT_KEY_DESCRIPTION,
                                     InputArgument::OPTIONAL,
                                     "Input Description"
                            );
        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        $item = $this->itemFactory->create();
        $item->setName($input->getArgument(self::INPUT_KEY_NAME));
        $item->setDescription($input->getArgument(self::INPUT_KEY_DESCRIPTION));
        $item->setIsObjectNew(true);
        $item->save();
        return Cli::RETURN_SUCCESS;
    }
}

5. Magento 2에서 예약 된 작업을 구성하는 방법 :

마스터 링 / 아이디어 / 크론 /AddItem.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of addItem
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Cron;
use Mastering\Itdesire\Model\ItemFactory;
use Mastering\Itdesire\Model\Config;
class AddItem {
    private $itemFactory;
    private  $config;
    public function __construct(ItemFactory $itemFactory,Config $config) {
        $this->itemFactory = $itemFactory;
        $this->config = $config;
    }

    public function execute()
    {
        if($this->config->isEnabled()){
            $this->itemFactory->create()
            ->setName('Scheduled item')
            ->setDescription('Created at ' . time())
            ->save();
        }

    }
}

마스터 링 /Itdesire/etc/config.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <mastering>
            <general>
                <enabled>0</enabled>
                <cron_expression>* * * * *</cron_expression>
            </general>
        </mastering>
    </default>
</config>

마스터 링 /Itdesire/etc/crontab.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="masteringAddItem" instance="Mastering\Itdesire\Cron\AddItem" method="execute">
            <config_path>mastering/general/cron_expression</config_path>
        </job>
    </group>
</config>

마스터 링 /Itdesire/etc/adminhtml/system.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="mastering" translate="label" sortOrder="10000">
            <label>Mastering</label>
        </tab>
        <section id="mastering" translate="label" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
            <label>Mastering</label>
            <tab>mastering</tab>
            <resource>Mastering_Itdesire::mastering</resource>
            <group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
                <label>Item creation by schedule</label>
                <field id="enabled" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
                    <label>Enabled</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="cron_expression" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0" canRestore="1">
                    <label>Add Item Cron Expression</label>
                </field>
            </group>
        </section>
    </system>
</config>

6. 메뉴 항목을 만드는 방법 :

마스터 링 /Itdesire/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="Mastering_Itdesire::mastering" title="Mastering"
                 module="Mastering_Itdesire" resource="Mastering_Itdesire::mastering"
                 translate="title" sortOrder="900" action="mastering"/>
        </menu>
    </config>

7. ACL 리소스를 만드는 방법 :

마스터 링 / 아이디어 /etc/acl.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Masteting_Itdesire::mastering" title="Mastering"
                          translate="title" sortOrder="900"/>
            </resource>
        </resources>
    </acl>
</config>

8. 사용자 정의 테이블을 사용하여 Magento에서 웹 API를 구현하는 방법 :

마스터 링 /Itdesire/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandList">
        <arguments>
           <argument name="commands" xsi:type="array">
                <item name="masteringAddItem" xsi:type="object">Mastering\Itdesire\Console\Command\AddItem</item>
            </argument>
        </arguments>
    </type>
    <preference type="Mastering\Itdesire\Model\Item" for="Mastering\Itdesire\Api\Data\ItemInterface"/>
    <preference type="Mastering\Itdesire\Model\ItemRepository" for="Mastering\Itdesire\Api\ItemRepositoryInterface"/>
</config>

마스터 링 /Itdesire/etc/webapi.xml

<?xml version="1.0"?>
<routes>
    <route url="/V1/mastering" method="GET">
        <service class="Mastering\Itdesire\Api\ItemRepositoryInterface" method="getList"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

여기에 이미지 설명을 입력하십시오

여기에 이미지 설명을 입력하십시오 여기에 이미지 설명을 입력하십시오

여기에 이미지 설명을 입력하십시오 여기에 이미지 설명을 입력하십시오


2
또한 여기에 모든 소스 코드를 얻을 수 있습니다 github.com/pramodkharade/Magento2
프라 모드 Kharade

@Pramod :) 안녕하세요. 훌륭한 답변! 나는 여전히 내 특정 문제에 대해 조금 혼란 스럽습니다. 매주 다른 무작위 제품에 할인 코드를 할당하는 것이 목표라면 동일한 솔루션을 구현해야합니까? 아니면 API를 사용하지 않고 해당주의 제품에 대한 데이터를 저장하고 검색 할 수 있습니까? 내 질문은 여기 있습니다 : magento.stackexchange.com/questions/212734/… 다시 한번 감사드립니다!
Joshua 홍수

@PramodKharade으로 menu_factory 모델에 존재하지 않는
마수드 샤이 크에게

내가 실행하면 업그레이드 명령은 오류가 발생했습니다 [ReflectionException은] 클래스 마스터 \ Itdesire \ 콘솔 \ 명령 \ AddItem을가 @PramodKharade 존재하지 않습니다
마수드 샤이 크

그러나 당신은 코드의 작동을 설명하지 않았습니다 :(
Rahul Singh

5

11. 사용자 정의 그리드 위의 파일 길이를 초과하는 관리자 권한으로 계속 진행하십시오 .

마스터 링 /Itdesire/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandList">
        <arguments>
           <argument name="commands" xsi:type="array">
                <item name="masteringAddItem" xsi:type="object">Mastering\Itdesire\Console\Command\AddItem</item>
            </argument>
        </arguments>
    </type>
    <preference type="Mastering\Itdesire\Model\Item" for="Mastering\Itdesire\Api\Data\ItemInterface"/>
    <preference type="Mastering\Itdesire\Model\ItemRepository" for="Mastering\Itdesire\Api\ItemRepositoryInterface"/>
    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="mastering_item_grid_data_source" xsi:type="string">Mastering\Itdesire\Model\ResourceModel\Item\Grid\Collection</item>
            </argument>
        </arguments>
    </type>
</config>

마스터 링 /Itdesire/view/adminhtml/ui_component/mastering_item_grid.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">mastering_item_grid.mastering_item_grid_data_source</item>
            <item name="deps" xsi:type="string">mastering_item_grid.mastering_item_grid_data_source</item>
        </item>
        <item name="spinner" xsi:type="string">mastering_item_columns</item>
        <item name="buttons" xsi:type="array">
            <item name="add" xsi:type="array">
                <item name="name" xsi:type="string">add</item>
                <item name="label" xsi:type="string" translate="true">Add Item</item>
                <item name="class" xsi:type="string">primary</item>
                <item name="url" xsi:type="string">*/item/new</item>
            </item>
        </item>
    </argument>
    <dataSource name="mastering_item_grid_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider</argument>
            <argument name="name" xsi:type="string">mastering_item_grid_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="update_url" xsi:type="url" path="mui/index/render"/>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
                </item>
            </argument>
        </argument>
    </dataSource>
    <listingToolbar name="listing_top">
        <bookmark name="bookmarks"/>
        <columnsControls name="columns_controls"/>
        <exportButton name="export_button"/>
        <filterSearch name="fulltext"/>
        <filters name="listing_filters"/>
        <paging name="listing_paging"/>
        <frontendLink name="frontend_link"/>
    </listingToolbar>
    <columns name="mastering_item_columns">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="childDefaults" xsi:type="array">
                    <item name="fieldAction" xsi:type="array">
                        <item name="provider" xsi:type="string">mastering_item_grid.mastering_item_grid.mastering_item_columns.actions</item>
                        <item name="target" xsi:type="string">applyAction</item>
                        <item name="params" xsi:type="array">
                            <item name="0" xsi:type="string">view</item>
                            <item name="1" xsi:type="string">${ $.$data.rowIndex }</item>
                        </item>
                    </item>
                </item>
            </item>
        </argument>
        <selectionsColumn name="ids">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="indexField" xsi:type="string">id</item>
                </item>
            </argument>
        </selectionsColumn>
        <column name="name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Name</item>
                </item>
            </argument>
        </column>
        <column name="description">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Description</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

마스터 링 /Itdesire/view/adminhtml/layout/mastering_index_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">
            <uiComponent name="mastering_item_grid"/>
        </referenceContainer>
    </body>
</page>

마스터 링 / 아이디어 / 모델 /ResourceModel/Item/Grid/Collection.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Collection
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Model\ResourceModel\Item\Grid;
use Magento\Framework\Data\Collection\Db\FetchStrategyInterface as FetchStrategy;
use Magento\Framework\Data\Collection\EntityFactoryInterface as EntityFactory;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Psr\Log\LoggerInterface as Logger;

class Collection extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{
    public function __construct(
        EntityFactory $entityFactory,
        Logger $logger,
        FetchStrategy $fetchStrategy,
        EventManager $eventManager,
        $mainTable = 'mastering_itdesire_item',
        $resourceModel = 'Mastering\Itdesire\Model\ResourceModel\Item'
    ) {
        parent::__construct(
            $entityFactory,
            $logger,
            $fetchStrategy,
            $eventManager,
            $mainTable,
            $resourceModel
        );
    }
}

여기에 이미지 설명을 입력하십시오

12. UI 구성 요소를 사용하여 양식을 작성하고 그리드로 저장 및 리디렉션하는 방법

마스터 링 /Itdesire/view/adminhtml/layout/mastering_item_new.xml

<?xml version="1.0"?>
<page layout="admin-2columns-left" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <uiComponent name="mastering_item_form"/>
        </referenceContainer>
    </body>
</page>

마스터 링 /Itdesire/view/adminhtml/ui_component/mastering_item_form.xml

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">mastering_item_form.mastering_item_form_data_source</item>
            <item name="deps" xsi:type="string">mastering_item_form.mastering_item_form_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">General</item>
        <item name="layout" xsi:type="array">
            <item name="type" xsi:type="string">tabs</item>
            <item name="navContainerName" xsi:type="string">left</item>
        </item>
        <item name="buttons" xsi:type="array">
            <item name="save" xsi:type="array">
                <item name="name" xsi:type="string">save</item>
                <item name="label" xsi:type="string" translate="true">Save</item>
                <item name="class" xsi:type="string">primary</item>
                <item name="url" xsi:type="string">*/*/save</item>
            </item>
        </item>
    </argument>
    <dataSource name="mastering_item_form_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Mastering\Itdesire\Ui\DataProvider</argument>
            <argument name="name" xsi:type="string">mastering_item_form_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="collectionFactory" xsi:type="object">Mastering\Itdesire\Model\ResourceModel\Item\CollectionFactory</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="submit_url" xsi:type="url" path="mastering/item/save"/>
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
    </dataSource>
    <fieldset name="general">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">General</item>
            </item>
        </argument>
        <field name="name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Name</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
        <field name="description">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Description</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="formElement" xsi:type="string">input</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

마스터 링 / 아이디어 /Ui/DataProvider.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DataProvider
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Ui;
use Magento\Ui\DataProvider\AbstractDataProvider;

class DataProvider extends AbstractDataProvider
{
    protected $collection;

    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        $collectionFactory,
        array $meta = [],
        array $data = []
    ) {
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
        $this->collection = $collectionFactory->create();
    }

    public function getData()
    {
        $result = [];
        foreach ($this->collection->getItems() as $item) {
            $result[$item->getId()]['general'] = $item->getData();
        }
        return $result;
    }
}

마스터 링 / 아이디어 / 컨트롤러 /Adminhtml/Item/NewAction.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of NewAction
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Controller\Adminhtml\Item;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action;

class NewAction extends Action
{
    public function execute()
    {
        return $this->resultFactory->create(ResultFactory::TYPE_PAGE);
    }
}

마스터 링 / 아이디어 / 컨트롤러 /Adminhtml/Item/Save.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Save
 *
 * @author pramod
 */
namespace Mastering\Itdesire\Controller\Adminhtml\Item;

use Mastering\Itdesire\Model\ItemFactory;
use Magento\Backend\App\Action;

class Save extends Action
{
    private $itemFactory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        ItemFactory $itemFactory
    ) {
        $this->itemFactory = $itemFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->itemFactory->create()
            ->setData($this->getRequest()->getPostValue()['general'])
            ->save();
        return $this->resultRedirectFactory->create()->setPath('mastering/index/index');
    }
}

여기에 이미지 설명을 입력하십시오


1
안녕하세요 @ Pramod Kharade :). 첫 번째 답변이 8 단계로 올라간 것을 알았지 만이 답변은 11 단계에서 계속됩니다. 단계가 누락되었거나 오타가 있습니까?
Joshua 홍수

안녕하세요 그리드 열에서 편집 및 삭제 작업을 어떻게 추가 할 수 있습니까?
Ashna

예, 추가 할 수 있습니다.
Pramod Kharade
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.