Option Providers for Select and Multiselect Fields - Sintraconsulting/pimcore-product-sync-plugin GitHub Wiki

In some cases we may not want to have static values for a select field, and we prefer dynamic values instead. Pimcore allow to generate a dynamic option provider for such these fields.

First of all, we need to define our option provider, creating an optionprovider.yml file:

services:
    
    optionsproviders.systemlanguagesoptionprovider :
        class: SintraPimcoreBundle\OptionsProviders\SystemLanguagesOptionProvider 
        public: true

Subsequently, add that file to Extension file for Dependency Injection.

class SintraPimcoreExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        [...]
        
        $loader->load('optionprovider.yml');
    }
}

The class specified in the optionprovider.yml file should implement the SelectOptionsProviderInterface or the MultiSelectOptionsProviderInterface. Option providers must return a key-value pair array; the value will be stored as field valure in database, the key will be shown on interface. In the following example, we can easily see how to retrieve all the languages defined in the system settings:

namespace SintraPimcoreBundle\OptionsProviders;

use Pimcore\Model\DataObject\ClassDefinition\DynamicOptionsProvider\MultiSelectOptionsProviderInterface;

class SystemLanguagesOptionProvider implements MultiSelectOptionsProviderInterface{

    public function hasStaticOptions($context, $fieldDefinition): bool {
        return true;
    }
    
    public function getOptions($context, $fieldDefinition): array {
        $fields = array();
        
        $config = \Pimcore\Config::getSystemConfig();
        $language = $config->general->language;
        $validLanguages = explode(",",$config->general->validLanguages);
        
        foreach ($validLanguages as $lang) {
            $fields[] = array(
                "key" => locale_get_display_name($lang,$language),
                "value" => $lang
            );
        }
        
        return $fields;
    }

}

In class definition, add option provider class reference to the interested field.

⚠️ **GitHub.com Fallback** ⚠️