سؤال

I have implemented a system configuration multiselect field (system.xml).

   <field id="foolist" translate="label" type="multiselect" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Allow Foo</label>
                    <source_model>Vendor\Module\Model\Config\Source\Foolist</source_model>
                </field>

with :

<?php

namespace Vendor\Module\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;

class Foolist implements ArrayInterface
{
    public function toOptionArray()
    {

        $arr = array (
            1 => "foo",
            2 => "bar",
            4 => "toto",
            6 => "Bla"
        );

        $ret = [];

        foreach ($arr as $key => $value)
        {

            $ret[] = [
                    'value' => $key,
                    'label' => $value
            ];
        }

        return $ret;
    }

}

I manage to get the memorized selected values using (in Model):

$Entries = $this->_scopeConfig->getValue('section/group/foolist', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

Which will return for example "1,3,4", corresponding to the keys of the foolist field.

Is it possible to access the corresponding values (ie foo, toto and Bla)?

هل كانت مفيدة؟

المحلول

By default you can't. But you need some code for getting this.

Change Foolist class following way:


namespace Vendor\Module\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;

class Foolist implements ArrayInterface
{
    public $arr = array (
        1 => "foo",
        2 => "bar",
        4 => "toto",
        6 => "Bla"
    );

    public function toOptionArray()
    {
        $ret = [];
        foreach ($this->arr as $key => $value) {
            $ret[] = [
                'value' => $key,
                'label' => $value
            ];
        }

        return $ret;
    }

    public function getOriginalOption()
    {
        return $this->arr;
    }
}

Now you can use following code for getting your output result:


public function __construct(
    \Vendor\Module\Model\Config\Source\Foolist $foolist
) {
    $this->foolist = $foolist;
}

and


$entries = $this->_scopeConfig->getValue('section/group/foolist', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
$entries = explode(',', $entries);
$foolist = $this->foolist->getOriginalOption();
$result = array();
foreach($foolist as $key => $value) {
    if(in_array($key, $entries)) {
        $result[] = $value;
    }
}

print_r($result);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top