How to create Customer attribute programmatically in magento 2?

Let’s we Create a simple Mobile number Customer attribute in magento 2. We need to create simple module for add new customer attribute in magento 2.

Create registration.php file to register our module. File Path, app/code/Rbj/CustomerAttribute/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Rbj_CustomerAttribute',
    __DIR__
);

Create module.xml file defined our module setup version to setup_module table. Create module.xml file defined our module setup version to setup_module table. File Path, app/code/Rbj/CustomerAttribute/etc/module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
  <module name="Rbj_CustomerAttribute" setup_version="1.0.0">
    <sequence>
      <module name="Magento_Customer"/>
    </sequence>
  </module>
</config>

We need to define our mobile customer attribute into extension_attributes.xml file. File path,app/code/Rbj/CustomerAttribute/etc/extension_attributes.xml 

Pass Classname inside for attribute in below xml as Magento\Customer\Api\Data\CustomerInterface because Its base Customer interface for create customer attribute in Magento 2. Set attribute code as your customer attribute code and define type as string.

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Customer\Api\Data\CustomerInterface">
        <attribute code="mobile" type="string"/>
    </extension_attributes>
</config>

 

For Create Customer attibute we need to define InstallData.php file to add entry in database of our attribute.
File Path, app/code/Rbj/CustomerAttribute/Setup/InstallData.php

<?php

namespace Rbj\CustomerAttribute\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;

class InstallData implements InstallDataInterface
{

    private $customerSetupFactory;

    /**
     * Constructor
     *
     * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'mobile', [
            'type' => 'varchar', // type of attribute
            'label' => 'Mobile Number',
            'input' => 'text', // input type
            'source' => '',
            'required' => false, // if you want to required need to set true
            'visible' => true,
            'position' => 500, // position of attribute
            'system' => false,
            'backend' => ''
        ]);
        
        /* Specify which place you want to display customer attribute */
        $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'mobile')
        ->addData(['used_in_forms' => [
                'adminhtml_customer',
                'adminhtml_checkout',
                'customer_account_create',
                'customer_account_edit'
            ]
        ]);
        $attribute->save();
    }
}

Now Run the upgrade command to install our module.
You need to run command using SSh from the root of your Magento instance,

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento indexer:reindex
php bin/magento cache:flush

Now you can check your new mobile number attribute at admin panel.
Login with admin credential,
Go To, Customers -> All Customers -> Edit any Customer.

 

How to get order item collection by item id magento 2?

You can get item collection data by Item id in magento 2 by using below code snippet, Create Block file,

<?php
namespace Rbj\Training\Block;

class Item extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template $context,
        \Magento\Sales\Api\OrderItemRepositoryInterface $orderItemRepository,
        array $data = []
    ) {
        $this->orderItemRepository = $orderItemRepository;
        parent::__construct($context, $data);
    }

    /* get order Item collection */
    public function getOrderItem($itemIid)
    {
        $itemCollection = $this->orderItemRepository->get($itemId);
        return $itemCollection;
    }
}

Call function from Template file,

$itemId = 10; // order item id
$getItemCollection = $block->getOrderItem($itemId);
echo $getItemCollection->getOrderId();
echo "<pre>";print_r($getItemCollection->debug());

 

How to create order programmatically in magento 2?

Magento 2 You can create order programmatically by simple coding.

You need to Create custom quote for order and based on that you can convert the quote to Order in Magento 2 by a simple code.

Create order information from the template file to helper file.

<?php
$orderInfo =[
    'currency_id'  => 'USD',
    'email'        => 'rakesh.jesadiya@testttttttt.com', //customer email id
    'address' =>[
        'firstname'    => 'Rakesh',
        'lastname'     => 'Testname',
        'prefix' => '',
        'suffix' => '',
        'street' => 'B1 Abcd street',
        'city' => 'Los Angeles',
        'country_id' => 'US',
        'region' => 'California',
        'region_id' => '12', // State region id
        'postcode' => '45454',
        'telephone' => '1234512345',
        'fax' => '12345',
        'save_in_address_book' => 1
    ],
    'items'=>
        [
            ['product_id'=>'1','qty'=>1], //simple product
            ['product_id'=>'67','qty'=>2,'super_attribute' => array(93=>52,142=>167)] //configurable product, pass super_attribte for configurable product
        ]
];
$helper = $this->helper('Rbj\Training\Helper\Data');
$orderData = $helper->createOrder($orderInfo);

?>

In above order info, We take customer basic details and Items info.
We have taken a simple and configurable product item. For configurable product, We need to pass super_attribute array value. For Test purpose, I have taken Magento Sample data configurable and simple product id.

For Configurable, 93 is Color attribute id where 52 is Gray option id.
142 is size attribute id where 167 is for XS size option id, you need to pass the dynamic value for a configurable product.

Create helper file,

Let’s say Data.php file location at, app/code/Rbj/Training/Helper/Data.php

<?php
/**
 * ExtendedRma Helper
 */
namespace Rbj\Training\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Quote\Model\QuoteFactory $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender

    ) {
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->productRepository = $productRepository;
        $this->customerRepository = $customerRepository;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->orderSender = $orderSender;
        parent::__construct($context);
    }
    /*
    * create order programmatically
    */
    public function createOrder($orderInfo) {
        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderInfo['email']);// load customet by email address
        if(!$customer->getId()){
            //For guest customer create new cusotmer
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderInfo['address']['firstname'])
                    ->setLastname($orderInfo['address']['lastname'])
                    ->setEmail($orderInfo['email'])
                    ->setPassword($orderInfo['email']);
            $customer->save();
        }
        $quote=$this->quote->create(); //Create object of quote
        $quote->setStore($store); //set store for our quote
        /* for registered customer */
        $customer= $this->customerRepository->getById($customer->getId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); //Assign quote to customer

        //add items in quote
        foreach($orderInfo['items'] as $item){
            $product=$this->productRepository->getById($item['product_id']);
            if(!empty($item['super_attribute']) ) {
                /* for configurable product */
                $buyRequest = new \Magento\Framework\DataObject($item);
                $quote->addProduct($product,$buyRequest);
            } else {
                /* for simple product */
                $quote->addProduct($product,intval($item['qty']));
            }
        }

        //Set Billing and shipping Address to quote
        $quote->getBillingAddress()->addData($orderInfo['address']);
        $quote->getShippingAddress()->addData($orderInfo['address']);

        // set shipping method
        $shippingAddress=$quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)
                        ->collectShippingRates()
                        ->setShippingMethod('flatrate_flatrate'); //shipping method, please verify flat rate shipping must be enable
        $quote->setPaymentMethod('checkmo'); //payment method, please verify checkmo must be enable from admin
        $quote->setInventoryProcessed(false); //decrease item stock equal to qty
        $quote->save(); //quote save 
        // Set Sales Order Payment, We have taken check/money order
        $quote->getPayment()->importData(['method' => 'checkmo']);
 
        // Collect Quote Totals & Save
        $quote->collectTotals()->save();
        // Create Order From Quote Object
        $order = $this->quoteManagement->submit($quote);
        /* for send order email to customer email id */
        $this->orderSender->send($order);
        /* get order real id from order */
        $orderId = $order->getIncrementId();
        if($orderId){
            $result['success']= $orderId;
        }else{
            $result=['error'=>true,'msg'=>'Error occurs for Order placed'];
        }
        return $result;
    }

You got a result as array for success order place, Array ( [success] => ‘OrderId’ )