Làm cách nào để tạo nút trong phần cấu hình Magento 2?


11

Làm cách nào để thêm nút trong phần cấu hình phụ trợ Magento 2 và gọi một phương thức PHP đơn giản khi nhấp vào nút?

Cuộc gọi phương thức này có thể là một cuộc gọi AJAX.

Câu trả lời:


18

Chúng tôi sẽ mô tả giải pháp bằng cách sử dụng mô-đun Mua cũng khác của chúng tôi làm ví dụ, trong đó MageWorx - tên nhà cung cấp và Ngoài ra - một tên mô-đun:

Trước tiên, bạn cần thêm nút của bạn dưới dạng một trường trong tệp cấu hình. (mageworx_collect làm ví dụ):

ứng dụng / mã / MageWorx / CũngB'd / etc / adminhtml / system.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */
 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="mageworx" sortOrder="2001">
            <label>MageWorx</label>
        </tab>
        <section id="mageworx_alsobought" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="0">
            <label>Also Bought</label>
            <tab>mageworx</tab>
            <resource>MageWorx_AlsoBought::config</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General</label>
                <field id="mageworx_collect" translate="label comment" type="button" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0">
                    <frontend_model>MageWorx\AlsoBought\Block\System\Config\Collect</frontend_model>
                    <label>Collect all available data (in separate table)</label>
                </field>
            </group>
        </section>
    </system>
</config>

Để vẽ nút trường này, mô hình frontend MageWorx\AlsoBought\Block\System\Config\Collectsẽ được sử dụng. Tạo ra nó:

ứng dụng / mã / MageWorx / Cũng mua / Chặn / Hệ thống / Cấu hình / Thu thập.php

<?php
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace MageWorx\AlsoBought\Block\System\Config;

use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;

class Collect extends Field
{
    /**
     * @var string
     */
    protected $_template = 'MageWorx_AlsoBought::system/config/collect.phtml';

    /**
     * @param Context $context
     * @param array $data
     */
    public function __construct(
        Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    /**
     * Remove scope label
     *
     * @param  AbstractElement $element
     * @return string
     */
    public function render(AbstractElement $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }

    /**
     * Return element html
     *
     * @param  AbstractElement $element
     * @return string
     */
    protected function _getElementHtml(AbstractElement $element)
    {
        return $this->_toHtml();
    }

    /**
     * Return ajax url for collect button
     *
     * @return string
     */
    public function getAjaxUrl()
    {
        return $this->getUrl('mageworx_alsobought/system_config/collect');
    }

    /**
     * Generate collect button html
     *
     * @return string
     */
    public function getButtonHtml()
    {
        $button = $this->getLayout()->createBlock(
            'Magento\Backend\Block\Widget\Button'
        )->setData(
            [
                'id' => 'collect_button',
                'label' => __('Collect Data'),
            ]
        );

        return $button->toHtml();
    }
}
?>

Đây là một mô hình lĩnh vực điển hình. Nút được vẽ bằng getButtonHtml()phương pháp. Sử dụng getAjaxUrl()phương pháp để có được một URL.

Sau đó, bạn sẽ cần mẫu:

ứng dụng / mã / MageWorx / CũngB'd / view / adminhtml / samples / system / config / coll.phtml

<?php
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */
?>
<?php /* @var $block \MageWorx\AlsoBought\Block\System\Config\Collect */ ?>

<script>
    require([
        'jquery',
        'prototype'
    ], function(jQuery){

        var collectSpan = jQuery('#collect_span');

        jQuery('#collect_button').click(function () {
            var params = {};
            new Ajax.Request('<?php echo $block->getAjaxUrl() ?>', {
                parameters:     params,
                loaderArea:     false,
                asynchronous:   true,
                onCreate: function() {
                    collectSpan.find('.collected').hide();
                    collectSpan.find('.processing').show();
                    jQuery('#collect_message_span').text('');
                },
                onSuccess: function(response) {
                    collectSpan.find('.processing').hide();

                    var resultText = '';
                    if (response.status > 200) {
                        resultText = response.statusText;
                    } else {
                        resultText = 'Success';
                        collectSpan.find('.collected').show();
                    }
                    jQuery('#collect_message_span').text(resultText);

                    var json = response.responseJSON;
                    if (typeof json.time != 'undefined') {
                        jQuery('#row_mageworx_alsobought_general_collect_time').find('.value .time').text(json.time);
                    }
                }
            });
        });

    });
</script>

<?php echo $block->getButtonHtml() ?>
<span class="collect-indicator" id="collect_span">
    <img class="processing" hidden="hidden" alt="Collecting" style="margin:0 5px" src="<?php echo $block->getViewFileUrl('images/process_spinner.gif') ?>"/>
    <img class="collected" hidden="hidden" alt="Collected" style="margin:-3px 5px" src="<?php echo $block->getViewFileUrl('images/rule_component_apply.gif') ?>"/>
    <span id="collect_message_span"></span>
</span>

Bạn sẽ phải viết lại một phần của mã theo nhu cầu của bạn nhưng tôi sẽ để nó làm ví dụ. Phương thức yêu cầu Ajax onCreateonSuccessphải phù hợp với nhu cầu của bạn. Ngoài ra, bạn có thể loại bỏ các <span class="collect-indicator" id="collect_span">yếu tố. Chúng tôi sử dụng nó để hiển thị tải (spinner) và kết quả của hành động.

Ngoài ra, bạn sẽ cần một bộ điều khiển, trong đó tất cả các hoạt động cần thiết sẽ được xử lý và bộ định tuyến.

ứng dụng / mã / MageWorx / CũngB'd / etc / adminhtml / Rout.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */
 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="mageworx_alsobought" frontName="mageworx_alsobought">
            <module name="MageWorx_AlsoBought" before="Magento_Backend" />
        </route>
    </router>
</config>

ứng dụng / mã / MageWorx / CũngB'd / Trình điều khiển / adminhtml / Hệ thống / Cấu hình / Sưu tập.php

<?php
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace MageWorx\AlsoBought\Controller\Adminhtml\System\Config;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use MageWorx\AlsoBought\Helper\Data;

class Collect extends Action
{

    protected $resultJsonFactory;

    /**
     * @var Data
     */
    protected $helper;

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param Data $helper
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        Data $helper
    )
    {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->helper = $helper;
        parent::__construct($context);
    }

    /**
     * Collect relations data
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        try {
            $this->_getSyncSingleton()->collectRelations();
        } catch (\Exception $e) {
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
        }

        $lastCollectTime = $this->helper->getLastCollectTime();
        /** @var \Magento\Framework\Controller\Result\Json $result */
        $result = $this->resultJsonFactory->create();

        return $result->setData(['success' => true, 'time' => $lastCollectTime]);
    }

    /**
     * Return product relation singleton
     *
     * @return \MageWorx\AlsoBought\Model\Relation
     */
    protected function _getSyncSingleton()
    {
        return $this->_objectManager->get('MageWorx\AlsoBought\Model\Relation');
    }

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('MageWorx_AlsoBought::config');
    }
}
?>

PS Đây là ví dụ làm việc kể từ MageWorx của chúng tôi Những người khác cũng mua module. Nếu bạn muốn nghiên cứu nó, bạn có thể tải xuống miễn phí.


Tôi đã sử dụng câu trả lời của bạn, nhưng làm thế nào để tôi gọi các hàm được định nghĩa trong Controller/Adminhtml/System/Config/Collection.php?
Condor

1

Bạn cũng kiểm tra nó trong nút nhà cung cấp / magento / mô-đun-khách hàng / etc / adminhtml / system.xml cho nút. Mã dưới đây kiểm tra nó trong đường dẫn trên. Tạo frontend_model như nhà cung cấp này / magento / mô-đun khách hàng / Chặn / adminhtml / System / Config / Validatevat.php .

<group id="store_information">
     <field id="validate_vat_number" translate="button_label" sortOrder="62" showInDefault="1" showInWebsite="1" showInStore="0">
           <button_label>Validate VAT Number</button_label>
           <frontend_model>Magento\Customer\Block\Adminhtml\System\Config\Validatevat</frontend_model>
     </field>
</group>

Đường dẫn trên để bạn tham khảo. Bây giờ tạo thích hợp cho mô-đun của riêng bạn.


1

Để thêm một nút trong cấu hình hệ thống và chạy một chức năng tùy chỉnh, bạn cần tạo frontend_modelđể hiển thị nút của mình. Trong mẫu của frontend_model, bạn có thể viết logic ajax của bạn.

Đây là một ví dụ:

System.xml

Path: /root_path/magento2/app/code/Skumar/Sync/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="skumar" translate="label" sortOrder="1000">
        <label>Skumar Extensions</label>
    </tab>
    <section id="sync" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
        <label>Sync</label>
        <tab>skumar</tab>
        <resource>Skumar_Sync::config</resource>
        <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Configuration</label>
            <field id="build_indexes" translate="label comment tooltip" type="button" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="0">
                <label>Build Search Indexes</label>
                <frontend_model>Skumar\Sync\Block\System\Config\Synchronize</frontend_model>
            </field>
        </group>
    </section>
</system>
</config>

Mô hình Frontend

Lớp này sẽ chịu trách nhiệm hiển thị nút html. getButtonHtml()Chức năng sẽ tạo nút html.

Path: /{root_path}/magento2/app/code/Skumar/Sync/Block/System/Config/Synchronize.php

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Skumar\Sync\Block\System\Config;

/**
 * Synchronize button renderer
 */
class Synchronize extends \Magento\Config\Block\System\Config\Form\Field
{
    /**
     * @var string
     */
    protected $_template = 'Skumar_Sync::system/config/synchronize.phtml';

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    /**
     * Remove scope label
     *
     * @param  \Magento\Framework\Data\Form\Element\AbstractElement $element
     * @return string
     */
    public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }

    /**
     * Return element html
     *
     * @param  \Magento\Framework\Data\Form\Element\AbstractElement $element
     * @return string
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        return $this->_toHtml();
    }

    /**
     * Return ajax url for synchronize button
     *
     * @return string
     */
    public function getAjaxSyncUrl()
    {
        return $this->getUrl('sync/system_config/synchronize');
    }

    /**
     * Generate synchronize button html
     *
     * @return string
     */
    public function getButtonHtml()
    {
        $button = $this->getLayout()->createBlock(
            'Magento\Backend\Block\Widget\Button'
        )->setData(
            [
                'id' => 'synchronize_button',
                'label' => __('Synchronize'),
            ]
        );

        return $button->toHtml();
    }
}

Ở đây, chúng tôi có frontend_modelnút kết xuất. Bây giờ, chúng ta cần tạo một lớp trình điều khiển sẽ xử lý yêu cầu ajax của chúng ta.

Đồng bộ hóa.php

Path: /{root_path}/magento2/app/code/Skumar/Sync/Controller/Adminhtml/System/Config/Synchronize.php

<?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Skumar\Sync\Controller\Adminhtml\System\Config;

use \Magento\Catalog\Model\Product\Visibility;

class Synchronize extends \Magento\Backend\App\Action
{
    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $_logger;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->_logger = $logger;
        parent::__construct($context);
    }


    /**
     * Synchronize
     *
     * @return void
     */
    public function execute()
    {
        $this->_logger->debug('Sync Starts!!');
        // do whatever you want to do
    }
}

Chúng tôi có một chức năng getAjaxSyncUrl()trong frontend_modelđó sẽ trả về url của bộ điều khiển này. Ngoài ra, có một biến $_templatetrong frontend_modelđó giữ đường dẫn tệp mẫu của chúng tôi cho trình kết xuất của chúng tôi.

đồng bộ hóa.

Path: /{root_path}/magento2/app/code/Skumar/Sync/view/adminhtml/templates/system/config/synchronize.phtml

<?php /* @var $block \Skumar\Sync\Block\System\Config\Synchronize */ ?>
<script>
require([
    'jquery',
    'prototype',
], function(jQuery){
    function syncronize() {
        params = {
        };

        new Ajax.Request('<?php /* @escapeNotVerified */ echo $block->getAjaxSyncUrl() ?>', {
            loaderArea:     false,
            asynchronous:   true,
            parameters:     params,
            onSuccess: function(transport) {
                var response = JSON.parse(transport.responseText);
            }
        });
    }

    jQuery('#synchronize_button').click(function () {
        syncronize();
    });
});
</script>

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

Bạn có thể thấy trong mẫu, khi nhấp vào nút, nó sẽ kích hoạt yêu cầu ajax đến bộ điều khiển được xác định trong forntend_model.

Tôi mong nó sẽ có ích.


1

Bạn cần xác định tùy frontend_modelchỉnh cho trường kết xuất tùy chỉnh trong cấu hình. Bạn có thể nhận trợ giúp từ liên kết này .


1

Để tạo một nút trong phần cấu hình phụ trợ, bạn cần thực hiện các bước sau:

Bước 1: Thêm một trường là nút trong tệp system.xmlnhư các tập lệnh này:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="namespace" translate="label" sortOrder="400">
            <label>Namspace Module</label>
        </tab>
        <section id="section" translate="label" type="text" sortOrder="300" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>Section Name</label>
            <tab>tab</tab>
            <resource>Namespace_Module::resource</resource>
            <group id="group_id" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Group Label</label>
                <field id="button" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                    <button_label>Button</button_label>
                    <frontend_model>Namspace\Module\Block\System\Config\Button</frontend_model>
                </field>
            </group>
        </section>
    </system>
</config>

Bước 2: Tạo nút hệ thống Block:

Tạo tập tin Namspace\Module\Block\System\Config\Button.php:

<?php

namespace Namespace\Module\Block\System\Config;


use Magento\Backend\Block\Template\Context;
use Magento\Customer\Model\Session;
use Magento\Framework\ObjectManagerInterface;

class Button extends \Magento\Config\Block\System\Config\Form\Field {

    /**
     * Path to block template
     */
    const CHECK_TEMPLATE = 'system/config/button.phtml';

    public function __construct(Context $context,
                                $data = array())
    {
        parent::__construct($context, $data);
    }

    /**
     * Set template to itself
     *
     * @return $this
     */
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        if (!$this->getTemplate()) {
            $this->setTemplate(static::CHECK_TEMPLATE);
        }
        return $this;
    }

    /**
     * Render button
     *
     * @param  \Magento\Framework\Data\Form\Element\AbstractElement $element
     * @return string
     */
    public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        // Remove scope label
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }

    protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        $this->addData(
            [
                'url' => $this->getUrl(),
                'html_id' => $element->getHtmlId(),
            ]
        );

        return $this->_toHtml();
    }

    protected function getUrl()
    {
        return "url"; //This is your real url you want to redirect when click on button
    }

} 

Bước 3: Tạo tập tin view/adminhtml/templates/system/config/button.phtml:

<div class="pp-buttons-container">
    <p>
        <button id="<?php echo $block->getHtmlId() ?>" onclick="setLocation('<?php /* @escapeNotVerified */ echo $block->getUrl() ?>')" type="button">
            <?php /* @escapeNotVerified */ echo __('Click Here') ?>
        </button>
    </p>
</div>
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.