Magento 2 : How to get collection of all sources "MSI (multi source inventory)?
-
19-02-2021 - |
Question
I have created a custom module and on my custom page, I want the collection of all the sources available on my website. Let's assume I have created 3 sources from backend like "US", "UK", "INDIA". Now, I want the collection of all resources available on my website
How could I achieve this functionality?
Thanks in advance!
Solution
Try following way:
use Magento\Framework\Api\SearchCriteriaBuilderFactory;
use Magento\InventoryApi\Api\SourceRepositoryInterface;
/**
* @var SourceRepositoryInterface
*/
private $sourceRepository;
/**
* @var SearchCriteriaBuilderFactory
*/
private $searchCriteriaBuilderFactory;
/**
* Place constructor.
*
* @param SourceRepositoryInterface $sourceRepository
* @param SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory
*/
public function __construct(
SourceRepositoryInterface $sourceRepository,
SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory
) {
$this->sourceRepository = $sourceRepository;
$this->searchCriteriaBuilderFactory = $searchCriteriaBuilderFactory;
}
/**
* {@inheritdoc}
* @codeCoverageIgnore
*/
public function getAllOptions()
{
if (!$this->_options) {
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->searchCriteriaBuilderFactory->create();
$searchCriteria = $searchCriteriaBuilder->create();
$sources = $this->sourceRepository->getList($searchCriteria)->getItems();
foreach ($sources as $source) {
$this->_options[] = [
'value' => $source->getCountryId(),
'label' => $source->getCountryId()
];
}
}
return $this->_options;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange