Hello Devs, In this tutorial we will see how to assign a customer to a company programmatically in Magento 2 B2B.
In Magento 2, the customer-to-company assignment feature allows you to associate customers with specific companies. This functionality is particularly useful for B2B (Business-to-Business) scenarios where you need to manage customer accounts within the context of their respective companies. In this blog post, we will walk you through the process of assigning customers to companies in Magento 2.
You can add customer to company using the function assignCustomer of
Magento\Company\Api\CompanyManagementInterface Interface in Magento 2.
Here is the example code for making this done in your custom class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php namespace VendorName\ModuleName\Helper; use Magento\Company\Api\CompanyManagementInterface; use Psr\Log\LoggerInterface; class CustomClass { public $logger; public $companyRepository; public function __construct( CompanyManagementInterface $companyRepository, LoggerInterface $logger ) { $this->companyRepository = $companyRepository; $this->logger = $logger; } public function assignCompanyToCustomer() { $companyId = 1; $customerId = 20; try { if($companyId && $customerId) { $company = $this->companyRepository->assignCustomer($companyId,$customerId); } } catch (\Exception $e) { $this->logger->critical($e->getMessage()); } return $company; } } |
Now using this you can assign a customer to a company programmatically.
You may also like this :
Get Company using Customer ID programmatically Magento 2 B2B
Get Company Admin using company ID programmatically Magento 2 B2B
how to get shared catalog data by ID in Magento 2?
That’s it for this tutorial, See you in the next tutorial. Keep coding !!