0

I'm creating a rest API and I need to add a custom columns to the customer_entity table and save the value in that fields within API request.

Сreated new attributes in the customer_entity table using UpgradeSchema:

public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
    $installer = $setup;

    $installer->startSetup();

    if (version_compare($context->getVersion(), '1.0.0', '<=')) {
        $installer->getConnection()->addColumn(
            $installer->getTable('customer_entity'),
            'phone',
            [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                'nullable' => true,
                'length' => 100,
                'comment' => 'Phone'
            ]
        );

        $installer->getConnection()->addColumn(
            $installer->getTable('customer_entity'),
            'full_name',
            [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                'nullable' => true,
                'length' => 100,
                'comment' => 'Full Name'
            ]
        );
    }

    $installer->endSetup();
}

The above code created two new fields in customer_entity table. And now I have a function that accepts data from the rest api request and creates a customer, customer is created with this code, but it does not save values to customer_entity table for phone and full_name fields.

use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\CustomerInterfaceFactory;

public function __construct(
    CustomerRepositoryInterface $customerRepository,
    CustomerInterfaceFactory $customerInterfaceFactory,

) {
    $this->customerRepository = $customerRepository;
    $this->customerInterfaceFactory = $customerInterfaceFactory;
}

public function createCustomer( string $fullName, string $phone, string $password )
{
    try {
        $customer = $this->customerInterfaceFactory->create();
        $customer->setEmail(uniqid( '', true ) . '@auto.gmail.com');

        $customer->setFirstname($fullName);
        $customer->setLastname($fullName);


        // Set custom attributes
        $customer->setCustomAttribute('phone', $phone);
        $customer->setCustomAttribute('full_name', $fullName);

        // Save customer
        $customer = $this->customerRepository->save($customer, $password);

        return 'Customer created successfully ' . $customer->getId();
    } catch (LocalizedException $e) {
        return 'Error creating customer: ' . $e->getMessage();
    }
}

If you know, please tell me how I can put a value in a customer custom attributes when creating a customer.

1 Answer 1

0

I will share my code for your related issue. please understand and try to it. my code is to get data API from third-party Guzzle and that value is saved in the "customer_entity" table.

/var/www/html/myproject/app/code/Vendor/Module/etc/webapi.xml

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">

<route method="GET" url="/V1/faqdata/getguzzledata/">
    <service class="Vendor\Module\Api\FaqInterface" method="getApiData"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

<route method="POST" url="/V1/faqdata/innsertguzzledata/">
    <service class="Vendor\Module\Api\FaqInterface" method="setData"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>
/var/www/html/myproject/app/code/Vendor/Module/Api/FaqInterface.php
<?php
    
namespace Vendor\Module\Api;

interface FaqInterface
{
    public function getApiData();

    /**
     * @return string
     */

    public function setData($data);
}

/var/www/html/myproject/app/code/Vendor/Module/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Vendor\Module\Api\FaqInterface.php" type="Vendor\Module\Model\Api\Faq"/>
</config>

/var/www/html/myproject/app/code/Vendor/Module/Model/Api/Faq.php

<?php 
 namespace Vendor\Module\Model\Api;

 use Magento\Framework\Exception\StateException;
 use GuzzleHttp\Client;
 use GuzzleHttp\ClientFactory;
 use GuzzleHttp\Exception\GuzzleException;
 use GuzzleHttp\Psr7\Response;
 use GuzzleHttp\Psr7\ResponseFactory;
 use Magento\Framework\Serialize\Serializer\Json;
 use Magento\Framework\Webapi\Rest\Request;

class Faq implements \Vendor\Module\Api\FaqInterface
{

private $customerFactory;
protected $response = ['success' => false];
protected $messageManager;
/**
 * API request URL
 */
const API_REQUEST_URI = 'https://dummyjson.com/';

/**
 * API request endpoint
 */
const API_REQUEST_ENDPOINT = 'users';

/**
 * @var ResponseFactory
 */
private $responseFactory;

/**
 * @var ClientFactory
 */
private $clientFactory;
/**
 * @var Json
 */
private $json;

/**
 * GitApiService constructor
 *
 * @param ClientFactory $clientFactory
 * @param ResponseFactory $responseFactory
 * @param Json $json
 */

public function __construct(
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Framework\Message\ManagerInterface $messageManager,
ClientFactory $clientFactory,
ResponseFactory $responseFactory,
Json $json

)
{
    $this->messageManager = $messageManager;
    $this->clientFactory = $clientFactory;
    $this->responseFactory = $responseFactory;
    $this->customerFactory  = $customerFactory;
    $this->json = $json;
}


/**
 * Fetch some data from API
 */
public function getApiData()
{
    $response = $this->doRequest(static::API_REQUEST_ENDPOINT);
    $status = $response->getStatusCode(); // 200 status code
    $responseBody = $response->getBody();
    $responseContent = $responseBody->getContents(); // here you will have the API response in JSON format
    $var = [];
    if($status == 200){
        $products = $this->json->unserialize($responseContent);
        foreach ($products['users'] as $key => $product){
            $var[] = [
                'firstName' => $product['firstName'],
                'lastName' => $product['lastName'],
                'maidenName' => $product['maidenName'],
                'email' => $product['email'],
                'birthDate' => $product['birthDate'],
                'gender' => $product['gender']
            ];

            // $var['firstName'] = $product['firstName'];
            // $var['lastName'] = $product['lastName'];
            // $var['maidenName'] = $product['maidenName'];
           
            // $var['email'] = $product['email'];
            // $var['birthDate'] = $product['birthDate'];
            // $var['cardExpire'] = $product['bank']['cardExpire'];
            // $var['cardNumber'] = $product['bank']['cardNumber'];
            // $var['cardType'] = $product['bank']['cardType'];
            // $var['currency'] = $product['bank']['currency'];
            // $var['company-address'] = $product['company']['address']['address'];
            // $var['postalCode'] = $product['company']['address']['postalCode'];
        }   
    }
    return $var;
}



/**
 * Do API request with provided params
 *
 * @param string $uriEndpoint
 * @param array $params
 * @param string $requestMethod
 *
 * @return Response
 */
private function doRequest(
    string $uriEndpoint,
    array $params = [],
    string $requestMethod = Request::HTTP_METHOD_GET
): Response {
    /** @var Client $client */
    $client = $this->clientFactory->create(['config' => [
        'base_uri' => self::API_REQUEST_URI
    ]]);

    try {
        $response = $client->request(
            $requestMethod,
            $uriEndpoint,
            $params
        );
    } catch (GuzzleException $exception) {
        /** @var Response $response */
        $response = $this->responseFactory->create([
            'status' => $exception->getCode(),
            'reason' => $exception->getMessage()
        ]);
    }

    return $response;
}


/**
 * Fetch some data from API
 */
public function setData($data)
{
    $test = $this->getApiData();
    
    try {
        foreach($test as $check){
            
           
            $insertData = $this->customerFactory->create();
            $insertData->setFirstname($check['firstName']);
            $insertData->setLastname($check['lastName']);
            $insertData->setMiddlename($check['maidenName']);
            $insertData->setEmail($check['email']);
            $insertData->setDob($check['birthDate']);
            if($check['gender'] == "male"){
                $insertData->setGender(1);
            }
            elseif($check['gender'] == "female") {
                $insertData->setGender(2);
            }
            $insertData->save();
        }
        $response = ['success' => true, 'message' => 'successfully saved'];
    } catch (\Exception $e) {
        $response = ['success' => false, 'message' => $e->getMessage()];
    }
    return $response;
}
}

I will share the below screenshot for Postman API get data.

enter image description here

backend side customer image before

enter image description here

database screenshot before save the data. enter image description here

insert data in Postman successfully

enter image description here

after api response is successful the Magento backend side saves data.

enter image description here

After API response save the data customer_entity table.

enter image description here

I will share all my backend and API data and my database screenshot share. i hope you that is help for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.