다중 선택 UI 구성 요소의 기본값 설정


13

내 magento 2 설치에 사용자 지정 엔터티가 있습니다.
이 엔티티의 필드 중 하나는 multiselect 유형이며 모든 국가의 목록을 포함합니다.
관리자 양식에 ui-components를 사용하고 있습니다.
선택에 약 200 개의 레코드가 있기 때문에 사용하기 쉽지 않기 때문에 다중 선택 필드를 원하지 않습니다.
그래서 제품 추가 / 편집 관리자 섹션의 카테고리 필드와 유사한 멋진 다중 선택 중 하나를 만들었습니다.
더 좋아 보이지만 기본값을 설정할 수 없습니다.
다음은 구성입니다 ( default구성 항목 에 유의하십시오).

<field name="affected_countries" formElement="select" component="Magento_Ui/js/form/element/ui-select" sortOrder="100">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="source" xsi:type="string">article</item>
            <item name="filterOptions" xsi:type="boolean">true</item>
            <item name="chipsEnabled" xsi:type="boolean">true</item>
            <item name="disableLabel" xsi:type="boolean">true</item>
            <item name="default" xsi:type="string">RO,MD</item>
        </item>
    </argument>
    <settings>
        <elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
        <dataType>text</dataType>
        <label translate="true">Affected Countries</label>
        <dataScope>affected_countries</dataScope>
        <componentType>field</componentType>
    </settings>
    <formElements>
        <select>
            <settings>
                <options class="Magento\Config\Model\Config\Source\Locale\Country"/>
            </settings>
        </select>
    </formElements>
</field>

결과는 다음과 같습니다.

그리고 기본 필드에 두 가지 값이 선택 될 것으로 기대합니다.

요소를 간단한 다중 선택으로 바꾸면 잘 작동합니다.

<field name="affected_countries" formElement="multiselect" sortOrder="100">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="source" xsi:type="string">article</item>
            <item name="default" xsi:type="string">RO,MD</item>
        </item>
    </argument>
    <settings>
        <dataType>text</dataType>
        <label translate="true">Affected Countries</label>
        <dataScope>affected_countries</dataScope>
    </settings>
    <formElements>
        <multiselect>
            <settings>
                <options class="Magento\Config\Model\Config\Source\Locale\Country"/>
            </settings>
        </multiselect>
    </formElements>
</field>

default설정 을 위해이 형식으로 묶었습니다.

<item name="default" xsi:type="string">RO,MD</item>

그리고 이것도 :

<item name="default" xsi:type="array">
    <item name="MD" xsi:type="string">MD</item>
    <item name="RO" xsi:type="string">RO</item>
</item>

또한 태그 select와 태그 multiselect내부에서 시도했습니다 formElements.
모든 시도가 실패로 끝났습니다.

여기에 지시 된default 대로 다른 유형의 필드에서 설정을 사용하면 (텍스트, 선택, 날짜 등 ...) 잘 작동합니다.

멋진 선택에 대한 제안이 있으십니까? 내가 놓친 것?

참고 : 양식을 채우는 데이터 공급자에서 기본값을 제공 할 수 있다는 것을 알고 있지만 추악하게 보이고 확장 가능하지 않고 나머지 필드와 일치하지 않으므로이를 피하려고합니다.


옵션의 ID를 사용해 보셨습니까?
— Adrian Z.

MD와 RO는 옵션의 ID입니다. 내가 말했듯이, 동일한 기본값을 사용하는 일반 다중 선택에서 작동합니다
— Marius

<items name = "default"xsi : type = "array"> </ items>
— Idham Choudry

@IdhamChoudry 나는 이미 그것을 시도했다. 그것은 질문에서 그렇게 말합니다.
— Marius

1
@LazyCoder이 질문에 내 질문을 살펴보십시오 <options class="Magento\Config\Model\Config\Source\Locale\Country"/>. 값이있는 배열을 반환하는 \Magento\Framework\Option\ArrayInterface메소드 를 구현 하고 구현하는 비슷한 클래스가 필요 toOptionArray합니다. 배열의 각 요소는 다음과 같아야합니다.['value' => ..., 'label' => ...]
— Marius

답변:


1

나는 사용자 정의 카테고리에서 일했지만이 방법에서는 데이터베이스를 통해 국가 데이터를 제공 하고이 코드에서 아이디어를 얻어야하며 magento 데이터를 확장하여 Db 또는 정적 데이터의 데이터를 제공 할 수 있습니다.

XML 코드

    <field name="country_id">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Vendor\Module\Model\Config\Source\CountriesTree</item>
        <item name="config" xsi:type="array">
            <item name="label" xsi:type="string" translate="true">Country</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</item>
            <item name="elementTmpl" xsi:type="string">ui/grid/filters/elements/ui-select</item>
            <item name="dataScope" xsi:type="string">category_id</item>
            <item name="filterOptions" xsi:type="boolean">true</item>
            <item name="chipsEnabled" xsi:type="boolean">true</item>
            <item name="showCheckbox" xsi:type="boolean">true</item>
            <item name="disableLabel" xsi:type="boolean">true</item>
            <item name="multiple" xsi:type="boolean">true</item>
            <item name="levelsVisibility" xsi:type="number">1</item>
            <item name="sortOrder" xsi:type="number">30</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">false</item>
            </item>
            <item name="listens" xsi:type="array">
                <item name="index=create_category:responseData" xsi:type="string">setParsed</item>
                <item name="newOption" xsi:type="string">toggleOptionSelected</item>
            </item>
        </item>
    </argument>
</field>

코피 그 코드

<?php

namespace Vendor\Module\Model\Config\Source;

class CountriesTree implements \Magento\Framework\Option\ArrayInterface
{

protected $_countryCollectionFactory;

protected $_options;

protected $_childs;


public function __construct(
    \Vendor\Module\Model\ResourceModel\Country\CollectionFactory 
 $countryCollectionFactory
) {
    $this->_countryCollectionFactory = $countryCollectionFactory;
}

public function toOptionArray()
{
    if ($this->_options === null) {
        $this->_options = $this->_getOptions();
    }
    return $this->_options;
}

protected function _getOptions($itemId = 0)
{
    $childs =  $this->_getChilds();
    $options = [];

    if (isset($childs[$itemId])) {
        foreach ($childs[$itemId] as $item) {
            $data = [
                'label' => $item->getCountry_title(),
                'value' => $item->getCountry_id(),
            ];

             if (isset($childs[$item->getCountry_id()])) {
                 $data['optgroup'] = $this->_getOptions($item->getCountry_id());
             }

            $options[] = $data;
        }
    }

    return $options;
}

protected function _getChilds()
{
    if ($this->_childs === null) {
        $this->_childs =  $this->_countryCollectionFactory->create()
            ->getGroupedChilds();
    }
    return $this->_childs;
}
}

출력은 다음과 같습니다 여기에 이미지 설명을 입력하십시오


아 ...하지만이 질문은 7 개월 전에 요청되었습니다 :(
— sheraz khan

값은 이미 db에서 가져 왔습니다. 기본값을 미리 선택하기 위해 db에 저장된 내용을 편집하지 않을 때 "화면 추가"만 있으면됩니다. 나는 이것이 내 문제를 해결한다고 생각하지 않는다. 또한 나무와 같은 구조가 필요하지 않습니다. 나는 평범한 국가 목록을 가지고 있습니다.
— Marius

예, 우리는 기본 데이터를 사용해야합니다. 제 경우에는 dataprovider를 작성하지만 귀하의 경우에는 효율적인 접근 방식이 아닙니다. XML을 통한 귀하의 경우에는 적합합니다
— sheraz khan
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.