Magento 2.1.2 Ui-组件窗体从多个下拉菜单中选择元素


10

我有两个下拉菜单,其中一个是“ 小时”,另一个是“ 分钟”。我设法显示了几个小时的下拉菜单在此处输入图片说明

但是任何人都可以提供帮助-如何以Ui组件形式在数小时之内显示下拉菜单,而不是数小时?就像图片中的那个一样。在此处输入图片说明

<field name="start_date">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">NameSpace\ModuleName\Model\Xyz\Source\Hours</item>                
        <item name="config" xsi:type="array">
            <item name="label" xsi:type="string" translate="true">Monday Opening Time</item>
            <item name="visible" xsi:type="boolean">true</item>
            <item name="dataType" xsi:type="string">number</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="source" xsi:type="string">item</item>
            <item name="dataScope" xsi:type="string">start_date</item>
            <item name="sortOrder" xsi:type="number">220</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>      
</field>

我的模型返回小时值

public function getHours()
{
    $availableOptions = [
        '0' => '00',
        '1' => '01',
        '2' => '02',
        '3' => '03',
        '4' => '04',
        '5' => '05',
        '6' => '06',
        '7' => '07',
        '8' => '08',
        '9' => '09',
        '10' => '10',
        '11' => '11',
        '12' => '12',
        '13' => '13',
        '14' => '14',
        '15' => '15',
        '16' => '16',
        '17' => '17',
        '18' => '18',
        '19' => '19',
        '20' => '20',
        '21' => '21',
        '22' => '22',
        '23' => '23',
    ];
    return $availableOptions;
}

Answers:


3

这是通过制作自定义ui组件来实现的方法。它要求背景字段为varchar。

在中定义ui组件Your_Module/view/base/web/js/form/element/time.js

define([
    'Magento_Ui/js/form/element/abstract'
], function (AbstractElement) {
    'use strict';

    return AbstractElement.extend({
        defaults: {
            elementTmpl: 'Your_Module/form/time'
        },

        initialize: function () {
            this._super();

            this.hours = '00';
            this.minutes = '00';

            this.observe(['hours', 'minutes']);

            var value = this.value();

            this.hours(value.slice(0,2));
            this.minutes(value.slice(2));
        },

        userChanges: function () {
            this._super();

            this.value(this.hours() + this.minutes());
        },

        hoursOpts: (function () {
            var opts = [];

            for (var i=0; i<24; i++) {
                opts.push({
                    label: i.toString(),
                    value: ('0' + i).slice(-2)
                })
            }

            return opts;
        })(),

        minutesOpts: (function () {
            var opts = [];

            for (var i=0; i<60; i++) {
                opts.push({
                    label: ('0' + i).slice(-2),
                    value: ('0' + i).slice(-2)
                })
            }

            return opts;
        })()
    });
});

和模板,位于Your_Module/view/base/web/template/form/time.html

<select class="admin__control-select"
        data-bind="
        optgroup: hoursOpts,
        optionsValue: 'value',
        optionsText: 'label',
        value: hours,
        event: {change: userChanges}"/>

<select class="admin__control-select"
        data-bind="
        optgroup: minutesOpts,
        optionsValue: 'value',
        optionsText: 'label',
        value: minutes,
        event: {change: userChanges}"/>

像这样在表单XML中使用它:

<field name="start_date">
        <argument name="data" xsi:type="array">
             <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Monday Opening Time</item>
                <item name="component" xsi:type="string">Your_Module/js/form/element/time</item>
                <item name="visible" xsi:type="boolean">true</item>
                <item name="dataType" xsi:type="string">text</item>
                <item name="formElement" xsi:type="string">input</item>
                <item name="source" xsi:type="string">item</item>
                <item name="dataScope" xsi:type="string">start_date</item>
                <item name="sortOrder" xsi:type="number">220</item>
                <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
          </item>
        </argument>      
    </field>

这两个下拉列表中的值将合并以生成一个'0130'表示时间的字符串1:30,因此您的数据类型必须为varchar,否则将删除开头的“ 0”。


我听了您说的话,就像奇迹一样运作:)
Verdu

如何将xml用于是/否项目?
Jafar Pinjar

0

我使用自定义表单元素来实现它。

namespace VendorName\ModuleName\Block\Widget\Form\Element;

use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\Data\Form\Element\Factory as ElementFactory;
use Magento\Framework\Data\Form\Element\CollectionFactory;
use Magento\Framework\Escaper;

/**
 * Class Time.
 */
class Time extends AbstractElement
{
    /**
     * Constructor.
     *
     * @param ElementFactory    $elementFactory
     * @param CollectionFactory $collectionFactory
     * @param Escaper           $escaper
     * @param array             $data
     */
    public function __construct(
        ElementFactory $elementFactory,
        CollectionFactory $collectionFactory,
        Escaper $escaper,
        array $data = []
    ) {
        parent::__construct($elementFactory, $collectionFactory, $escaper, $data);

        $this->setType('time');
    }

    /**
     * {@inheritdoc}
     */
    public function getElementHtml()
    {
        $this->addClass('select admin__control-select');

        $defaultValues = [
            'time'   => '00:00:00',
            'hour'   => '00',
            'minute' => '00',
            'second' => '00',
        ];

        $values = $this->getValue();
        if (!$values) {
            $values = $defaultValues;
        } else {
            $time = explode(':', $values);
            $values = [
                'time'   => $values,
                'hour'   => $time[0],
                'minute' => $time[1],
                'second' => $time[2],
            ];
        }

        // value container element
        $html = '<input type="hidden" id="' . $this->getHtmlId() . '" name="' . $this->getName()
            . '" value="' . $values['time'] . '" '. $this->_getUiId() . '/>' . PHP_EOL
        ;

        // hours control
        $html .= '<select style="width:80px" id="' . $this->getHourControlHtmlId() . '" '
            . $this->serialize($this->getControlHtmlAttributes()) . ' title="' . __('hours') . '" '
            . $this->_getUiId('hour') . '>' . PHP_EOL
        ;
        for ($i = 0; $i < 24; $i++) {
            $hour = str_pad($i, 2, '0', STR_PAD_LEFT);
            $html .= '<option'
                . ' value="' . $hour . '"'
                . ($values['hour'] == $i ? ' selected="selected"' : '') . '>'
                . $hour
                . '</option>' . PHP_EOL
            ;
        }
        $html .= '</select>' . PHP_EOL;

        // minutes control
        $html .= ':&nbsp;<select style="width:80px" id="' . $this->getMinuteControlHtmlId() . '" '
            . $this->serialize($this->getControlHtmlAttributes()) . ' title="' . __('minutes') . '" '
            . $this->_getUiId('minute') . '>' . PHP_EOL
        ;
        for ($i = 0; $i < 60; $i++) {
            $minute = str_pad($i, 2, '0', STR_PAD_LEFT);
            $html .= '<option'
                . ' value="' . $minute . '"'
                . ($values['minute'] == $i ? ' selected="selected"' : '') . '>'
                . $minute
                . '</option>' . PHP_EOL
            ;
        }
        $html .= '</select>' . PHP_EOL;

        // seconds control
        $html .= ':&nbsp;<select style="width:80px" id="' . $this->getSecondControlHtmlId() . '" '
            . $this->serialize($this->getControlHtmlAttributes()) . ' title="' . __('seconds') . '" '
            . $this->_getUiId('second') . '>' . PHP_EOL
        ;
        for ($i = 0; $i < 60; $i++) {
            $second = str_pad($i, 2, '0', STR_PAD_LEFT);
            $html .= '<option'
                . ' value="' . $second . '"'
                . ($values['hour'] == $i ? ' selected="selected"' : '') . '>'
                . $second
                . '</option>' . PHP_EOL
            ;
        }
        $html .= '</select>' . PHP_EOL;

        $html .= $this->getAfterElementHtml();

        $html .= $this->getAfterElementJs();

        return $html;
    }

    /**
     * Get after element JS.
     *
     * @return string
     */
    public function getAfterElementJs()
    {
        $js = '
            <script type="text/javascript">
                require(["jquery"], function ($) {
                    var onTimeContainerChange = function () {
                        var time      = $("#' . $this->getHtmlId() . '").val();
                        var timeArray = time.split(":");

                        $("#' . $this->getHourControlHtmlId() . '").val(timeArray[0]);
                        $("#' . $this->getMinuteControlHtmlId() . '").val(timeArray[1]);
                        $("#' . $this->getSecondControlHtmlId() . '").val(timeArray[2]);
                    };
                    $(document).ready(onTimeContainerChange);
                    $("#' . $this->getHtmlId() . '").change(onTimeContainerChange);

                    var onTimeControlChange = function () {
                        var time = $("#' . $this->getHourControlHtmlId() . '").val()
                            + ":" + $("#' . $this->getMinuteControlHtmlId() . '").val()
                            + ":" + $("#' . $this->getSecondControlHtmlId() . '").val()
                        ;

                        $("#' . $this->getHtmlId() . '").val(time);
                    }
                    $("'
                        . '#' . $this->getHourControlHtmlId() . ','
                        . '#' . $this->getMinuteControlHtmlId() . ','
                        . '#' . $this->getSecondControlHtmlId()
                    . '").change(onTimeControlChange);
                });
            </script>
        ';

        return $js;
    }

    /**
     * Get hour control html id prefix.
     *
     * @return string
     */
    protected function getHourControlHtmlId()
    {
        return $this->getHtmlId() . '_hour_control';
    }

    /**
     * Get minute control html id prefix.
     *
     * @return string
     */
    protected function getMinuteControlHtmlId()
    {
        return $this->getHtmlId() . '_minute_control';
    }

    /**
     * Get second control html id prefix.
     *
     * @return string
     */
    protected function getSecondControlHtmlId()
    {
        return $this->getHtmlId() . '_second_control';
    }

    /**
     * Get control html attributes.
     *
     * @return array
     */
    protected function getControlHtmlAttributes()
    {
        $propertiesToClear = ['title'];
        $htmlAttributes    = $this->getHtmlAttributes();

        return array_diff($htmlAttributes, $propertiesToClear);
    }
}

对其进行自定义以满足您的要求,例如,删除第二个字段。

如何使用:

use VendorName\ModuleName\Block\Widget\Form\Element\Time as TimeElement;

$form->addType('custom_time', TimeElement::class);
$form->addField(
    '[id_of_your_field]',
    'custom_time',
    [
        ... // data
    ]
);

感谢@Rendy Eko Prastiyo,您使用块完成了此操作-我正在通过Ui Components实现。
Verdu

我认为这是不可能的。甚至Magento Catalog也使用表单修饰符来实现产品编辑后端的weightproduct_has_weight列的内联模式。请参阅Magento\Catalog\Ui\DataProvider\Product\Form\Modifier::customizeWeightField
伦迪·埃科·普拉斯蒂约

好 !看来,我们应该通过块来实现它;你的方式!这本来是更好,如果我们能够利用这段时间选择器,这是在Magento 2个文档提到,但实现不可devdocs.magento.com/guides/v2.0/pattern-library/...
Verdu
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.