Skip to content

Magento2.4: How to assign a new source to stock programmatically?

I am trying to assign new sources to stock but it’s not working. I checked the logs and there is no error found. Below is my code. Can anyone please check and suggest me where am I wrong?

 public function assignSourceToStock($stockId, $sourceCode)
    {
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('source_code', $sourceCode)
            ->create();

        $sources = $this->sourceRepository->getList($searchCriteria)->getItems();

        if (!empty($sources)) {
            foreach ($sources as $source) {
                $source->setStockId($stockId);
                $this->sourceRepository->save($source);
            }

            echo "Source '{$sourceCode}' assigned to stock with ID '{$stockId}' successfully.";
        } else {
            echo "Source '{$sourceCode}' not found.";
        }
    }

I am calling this method assignSourceToStock() with the store code and stock id.

Any help will be appreciated.