Jigar KarangiyaJigar Karangiya

How to assign a customer to a company programmatically in Magento 2 B2B?

JK
Jigar Karangiya
· 1 min read
How to assign a customer to a company programmatically in Magento 2 B2B?

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.

php
<?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 !!

Written by Jigar Karangiya, Adobe Commerce & Magento 2 developer.

More about me

Related posts