Retrieves Assigned Sources links that are assigned to specific stocks in Multi-Source Inventory Magento 2.
You can check assigned sources for the stock from admin panel, Stores -> Inventory -> Stock
Edit any stocks from the grid, Go to Sources Tab, You can see a list of assigned sources for a given stock.
You can get all the assigned source using programmatically by GetStockSourceLinksInterface class.
Full Interface Path:
Magento\InventoryApi\Api\GetStockSourceLinksInterface
Code snippet to fetch a list of assigned source for stock,
<?
namespace Jesadiya\AssignedSource\Model;
use Exception;
use Psr\Log\LoggerInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\InventoryApi\Api\GetStockSourceLinksInterface;
use Magento\InventoryApi\Api\Data\StockSourceLinkInterface;
class AssignedSourceList
{
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var GetStockSourceLinksInterface
*/
private $getStockSourceLinks;
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(
SearchCriteriaBuilder $searchCriteriaBuilder,
GetStockSourceLinksInterface $getStockSourceLinks,
LoggerInterface $logger
) {
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->getStockSourceLinks = $getStockSourceLinks;
$this->logger = $logger;
}
/**
* Retrieves links that are assigned to $stockId
*
* @param int $stockId
* @return StockSourceLinkInterface[]
*/
public function getAssignedSource(int $stockId): array
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter(StockSourceLinkInterface::STOCK_ID, $stockId)
->create();
$result = [];
foreach ($this->getStockSourceLinks->execute($searchCriteria)->getItems() as $link) {
$result[$link->getSourceCode()] = $link;
}
return $result;
}
}
Call function to fetch assigned source result,
$stockId = (int)1;
$result = $this->getAssignedSource($stockId);
foreach ($result as $source) {
var_dump($source->getData());
}
Output:
'link_id' => string '1' (length=1) 'stock_id' => string '1' (length=1) 'source_code' => string 'default' (length=7) 'priority' => string '1' (length=1)
You can fetch a list of assigned sources for a stock as a resultant array. I have given result for Default Stock of Native Magento.
If Stock has multiple assigned sources, Output will display multiple source results.
