Magento 2 – How to get multiselect option in system configuration using system.xml.

Using below demo we can get multiselect option using system.xml.
For Example, We will get all Customer group of a system and display all the customer group by system.xml in System -> Configuration Section of admin.
Create system.xml file,
Path,   app/code/<Vendorname>/<Modulename>/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>
        <section id="catalog">
            <group id="customer_group" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <field id="list" translate="label" type="multiselect" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Customer Groups</label>
                    <source_model>Vendorname\Modulename\Model\Adminhtml\System\Config\Source\Customer\Group</source_model>
                    <can_be_empty>1</can_be_empty>
                </field>
            </group>
        </section>
    </system>
</config>

You need to get the collection of all customer group using a Model file. Create Model file in your module. You can define your model php file using source_model tag in system.xml file.

Create Group.php file,
Path, app/code/<Vendorname>/<Modulename>/Model/Adminhtml/System/Config/Source/Customer/Group.php

<?php
namespace Vendorname\Modulename\Model\Adminhtml\System\Config\Source\Customer;

class Group implements \Magento\Framework\Option\ArrayInterface
{
    public function __construct(\Magento\Customer\Model\ResourceModel\Group\CollectionFactory $groupCollectionFactory)
    {
        $this->_groupCollectionFactory = $groupCollectionFactory;
    }

    /**
     * @return array
     */
    public function toOptionArray()
    {
        if (!$this->_options) {
            $this->_options = $this->_groupCollectionFactory->create()->loadData()->toOptionArray();
        }
        return $this->_options;
    }
}

Clear Cache using php bin/magento cache:flush

Now You can get the list of customer group in your section with multi-select option.
If you want to get the list of all selected option in PHP file,

<?php
namespace Vendorname\Modulename\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function __construct(
        \Magento\Framework\App\Helper\Context $context
    ) {
        $this->scopeConfig = $context->getScopeConfig();
        parent::__construct($context);
    }
    /**
     * Get Customer group selected list
     */
    public function getCustomerGroupList() {
        $list = $this->scopeConfig->getValue("catalog/customer_group/list",
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        return $list !== null ? explode(',', $list) : [];
    }

Using the above way you can list of all customer group selected in a Configuration section. The result will be a value of all selected customer group with comma separated.

Convert number into currency format using Magento 2.

We can simply convert a plain number into price format with a currency symbol. We can get round price of current given price as well as get current store currency symbol by Magento\Framework\Pricing\PriceCurrencyInterface class interface. We can Get Formatted Price With Currency using below code snippets.

Using Objectmanager,

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$priceHelper = $objectManager->create('Magento\Framework\Pricing\PriceCurrencyInterface'); // Pricing Interface
$price =  50; //Your Custom Price
echo $formattedPrice = $priceHelper->convertAndFormat($price); // $50.00
echo $formattedPrice = $priceHelper->round($price); //50
echo $formattedPrice = $priceHelper->getCurrencySymbol(); // $
?>

Proper way using Block PHP file and call function in a template file, Create Block file in your module and pass Dependency as Pricecurrencyinterface

<?php
namespace Rbj\Currency\Block;

class Currency extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
        array $data = []
    ) {
        $this->priceCurrency = $priceCurrency;
        parent::__construct($context, $data);
    }

    /**
     * Get current store currency symbol with price
     * $price price value
     * true includeContainer
     * Precision value 2
     */
    public function getCurrencyFormat($price)
    {
        $price = $this->priceCurrency->format($price,true,2);
        return $price;
    }
    /**
     * Get round price without currency symbol
     */
    public function getRoundPrice($price)
    {
        $price = $this->priceCurrency->round($price);
        return $price;
    }
    /**
     * Get current store CurrencySymbol
     */
    public function getCurrencySymbol()
    {
        $symbol = $this->priceCurrency->getCurrencySymbol();
        return $symbol;
    }

Call function from template file,

<?php
// Get currency symbol with price format
echo $currencyFormat = $this->getCurrencyFormat(50.0000); //output $50.00
// Get round value of number
echo $roundPrice = $this->getRoundPrice(20.0000); //output 20 (without currency symbol)
echo $roundPrice = $this->getRoundPrice(20.5000); //output 20.5
// Get Currency symbol of current store
echo $roundPrice = $this->getCurrencySymbol(); //output $

 

Magento 2 – How to get all options of specific attribute type?

In Magento 2 we can get all options of specific EAV entity types attribute. In Magento 2 There are many native EAV Entity Types are available.

You can get all options of specific attribute, Let’s we take a catalog_product Entity Type.
We take Color attribute from Catalog_Product Eav Entity Types. Fetch all the options of color attribute.
Create Block file,

<?php
namespace Rbj\AttributeOption\Block

class Option extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Eav\Model\Config $eavConfig,
        array $data = []
    ) {
        $this->eavConfig = $eavConfig;
        parent::__construct($context, $data);
    }

    /**
     * Entity Type Catalog
     * Attribute code color
     * @return array
     */
    public function getOptionList()
    {
        $attribute = $this->eavConfig->getAttribute('catalog_product', 'color');
        return $attribute->getSource()->getAllOptions();
    }
}

Call Function From Template file,

$result = $block->getOptionList();
foreach($result as $option) {
    echo $option['value']. '=>' .$option['label'];echo "<br />";
}
echo "<pre>";print_r($result);

The result looks like,

Array
(
    [0] => Array
        (
            [label] =>
            [value] =>
        )

    [1] => Array
        (
            [value] => 49
            [label] => Black
        )

    [2] => Array
        (
            [value] => 50
            [label] => Blue
        )

    [3] => Array
        (
            [value] => 51
            [label] => Brown
        )

    [4] => Array
        (
            [value] => 52
            [label] => Gray
        )
        ....