I am new to Magento 2 Can anyone help me with how to programmatically create the Inventory source? What is the use of the stock channel?
1 Answer
You can create an inventory source via an UpgradeData.php
script, I'm not sure how familiar you are with upgrade scripts, but there's plenty of documentation and tutorials around that, so I'll just list the upgrade script part.
namespace VENDOR\MODULE_NAME\Setup;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\InventoryApi\Api\Data\SourceInterface;
class UpgradeData implements UpgradeDataInterface
{
/**
* @var ResourceConnection
*/
private $resource;
/**
* UpgradeData constructor.
* @param ResourceConnection $resource
*/
public function __construct(
ResourceConnection $resource
) {
$this->resource = $resource;
}
/**
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
*/
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
$connection = $this->resource->getConnection();
$sourceData = [
SourceInterface::SOURCE_CODE => 'ABCD',
SourceInterface::NAME => 'My New Source',
SourceInterface::ENABLED => 1,
SourceInterface::DESCRIPTION => 'My New Source Description',
SourceInterface::LATITUDE => 41.227791,
SourceInterface::LONGITUDE => -39.927117,
SourceInterface::COUNTRY_ID => 'GB',
SourceInterface::POSTCODE => 'AB1 1AB',
];
$connection->insert($this->resource->getTableName('inventory_source'), $sourceData);
}
}
Then when you run a setup:upgrade, the upgrade script will add the source to your inventory sources.
-
But i need to create the source dynamically while customer account registration– JaisaCommented Aug 3, 2021 at 5:13
-
@Jaisa I need to create a new inventory source programmatically but facing issues when using the above code. did you find the solution? Commented Aug 3, 2021 at 12:56
-
1@Siva Not yet. I need to create a source while saving a customer account.So I did not tried the above one– JaisaCommented Aug 4, 2021 at 18:30
-
@Jaisa Ok. Hope you'll find the solution for your requirement Commented Aug 5, 2021 at 7:19