Magento – Magento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module

magento2magento2.3multi-source-inventoryproduct-attribute

I want to get all the location names from the Multi Source Inventory (MSI). How could I get a collection of all locations in my custom module?

Here I want to create a new multi-select product attribute name "place", which has the values of all source names as its attribute values.

i.e. if there are 3 sources "US, UK, IN" then attribute has the same values "US, UK, IN" in product form.

How could I achieve this functionality? Do anyone have an idea about
it?

I have attribute script as below:

$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

    $eavSetup->addAttribute(Product::ENTITY, 'place',
        [
            'group' => 'General',
            'sort_order' => 30,
            'type' => 'text',
            'backend' => '\Module\Name\Model\Backend\Place',
            'frontend' => '',
            'class' => '',
            'label' => 'Place',
            'input' => 'multiselect',
            'source' => '',
            'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
            'visible' => true,
            'required' => true,
            'user_defined' => false,
            'default' => '',
            'searchable' => true,
            'filterable' => true,
            'comparable' => false,
            'visible_on_front' => true,
            'used_in_product_listing' => true,
            'unique' => false
        ]
    );

Thanks in advance.

Best Answer

Try this, it's working for me.

global $objectManager;        

$sourceList = $objectManager->get('\Magento\Inventory\Model\ResourceModel\Source\Collection');
$sourceListArr = $sourceList->load();
$i=1;

$sourceList = array();
foreach ($sourceListArr as $sourceItemName) {
    $sourceCode = $sourceItemName->getSourceCode();
    $sourceName = $sourceItemName->getName();

    $sourceList['sourcecount'] = $i;
    $sourceList['sourceCode'] = $sourceCode;
    $sourceList['sourceName'] = $sourceName;

    $sourceAllList[] = $sourceList;

    $i++;
}

print_r($sourceAllList);

//Output will be

Array
(
    [0] => Array
        (
            [sourcecount] => 1
            [sourceCode] => default
            [sourceName] => Default Source
        )

    [1] => Array
        (
            [sourcecount] => 2
            [sourceCode] => CAN
            [sourceName] => Canada
        )

    [2] => Array
        (
            [sourcecount] => 3
            [sourceCode] => USA
            [sourceName] => United State
        )

)
Related Topic