2

In magento 2, how to get a custom attribute option value in select field in checkout page

enter image description here

app/code/Cm/CustomerAttribute/Model/Plugin/Checkout/LayoutProcessor.php

    <?php
namespace Cm\CustomerAttribute\Model\Plugin\Checkout;
class LayoutProcessor
{
    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {

        $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
        ['shippingAddress']['children']['shipping-address-fieldset']['children']['custom_field'] = [
            'component' => 'Magento_Ui/js/form/element/abstract',
            'config' => [
                'customScope' => 'shippingAddress.custom_attributes',
                'template' => 'ui/form/field',
                'elementTmpl' => 'ui/form/element/select',
                'options' => [],
                'id' => 'custom-field'
            ],
            'dataScope' => 'shippingAddress.custom_attributes.custom_field',
            'label' => 'Custom Field',
            'provider' => 'checkoutProvider',
            'visible' => true,
            'validation' => [],
            'sortOrder' => 250,
            'id' => 'custom-field',
            'options' => [
                    [
                        'value' => '',
                        'label' => 'Please select'
                    ],
                    [
                        'value' => '1',
                        'label' => 'One'
                    ],
                    [
                        'value' => '2',
                        'label' => 'Two'
                    ],
                    [
                        'value' => '3',
                        'label' => 'Three'
                    ]
                ]
        ];


        return $jsLayout;
    }
}

Please some one help me to get a attribute option

3
  • got any solution ? Commented Sep 27, 2019 at 5:30
  • Yes , finally i found a solution wait i will posted as a answer Commented Sep 27, 2019 at 5:35
  • i updated the answer @manish Commented Sep 27, 2019 at 5:49

2 Answers 2

4

code:

      <?php 
    namespace Cm\CustomerAttribute\Plugin\Checkout\Block\Checkout;

    class LayoutProcessor
    {
        protected $customerSession;
        protected $resultPageFactory;
        public function __construct(\Cm\CustomerAttribute\Helper\Customerattribute $helper,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
        \Magento\Customer\Model\Session $customerSession)
        {
            $this->helper = $helper;
            $this->customerRepositoryInterface = $customerRepositoryInterface;
            $this->customerSession = $customerSession;
        }
        public function afterProcess(
            \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
            $jsLayout
        ) {
            $attributeCollection = $this->helper->getUserDefinedAttribures();

           if ($attributeCollection->getSize() > 0) 
           {
             foreach ($attributeCollection as $attribute)    
             {
            if ($this->helper->isAttribureForCheckoutRegister($attribute->getAttributeCode()))
            {
            $frontEndLabel = $attribute->getStoreLabel($this->helper->getStoreId());

            $customAttributeCode = $attribute->getAttributeCode();
              $customerAttr = NULL;

          if($this->customerSession->isLoggedIn()) {
            $customerId =$this->customerSession->getCustomer()->getId();
             $customer =$this->customerRepositoryInterface->getById($customerId);
             if($myCustomAttribute = $customer->getCustomAttribute($customAttributeCode)) {
                     $customerAttr = $myCustomAttribute->getValue();
              }     
            }
            else
            {
              $customerAttr =NULL;
            }
            $sortOrder = $attribute->getSortOrder();
            $fieldRequiredClass = ($attribute->getIsRequired()) ? 'true' : '' ;
            if($fieldRequiredClass == '')
            {
                $fieldRequiredClass = false;
            }
            $fieldFrontendClass = ($attribute->getFrontendClass()) ? $attribute->getFrontendClass() : '';
            $fieldInput =$attribute->getFrontendInput();
            $attributeId = $attribute->getAttributeId();
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

            $attributeOptionAll = $objectManager->create(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class)
                                        ->setPositionOrder('asc')
                                        ->setAttributeFilter($attributeId)
                                        ->setStoreFilter()
                                        ->load();
            $opt_val = array();
            $allOptions=array();


            foreach ($attributeOptionAll->getData() as $key => $v) 
            {
              // $allid = $v['attribute_id'];
              $opt_val['value'] = $v['option_id'];
              $opt_val['label'] = $v['value'];
              $allOptions[] = $opt_val;
            }



            $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
            ['shippingAddress']['children']['shipping-address-fieldset']['children'][$customAttributeCode] = $this->addNewField($customAttributeCode,$frontEndLabel,$fieldRequiredClass, $fieldFrontendClass, $fieldInput,  $allOptions, $customerAttr, $sortOrder );


            }
          }
        }
        return $jsLayout;
        }

        private function addNewField($customAttributeCode, $frontEndLabel, $fieldRequiredClass,  $fieldFrontendClass, $fieldInput, $allOptions, $customerAttr , $sortOrder )
        {
            if($fieldInput == 'text')
            {
                $fieldInputType = 'input';
                $fieldAbstract =  'abstract';
                $fieldVisible = true;
            }
            elseif ($fieldInput == 'date') {
               $fieldInputType = 'date'; 
               $fieldAbstract =  'date';
              $fieldVisible = true;

            }
            elseif ($fieldInput == 'select') {
               $fieldInputType = 'select'; 
               $fieldAbstract =  'select';
               $fieldVisible = true;

            }
            elseif ($fieldInput == 'multiselect') {
               $fieldInputType = 'input'; 
               $fieldAbstract =  'abstract';
               $fieldVisible = false;
            }
            elseif ($fieldInput == 'boolean') {
               $fieldInputType = 'select'; 
               $fieldAbstract =  'select';
               $fieldVisible = true;
               $allOptions = [
                     ['value' => '0', 'label' => 'No'],
                     ['value' => '1', 'label' => 'Yes']
                   ];
            }
             elseif ($fieldInput == 'textarea') {
               $fieldInputType = 'textarea'; 
               $fieldAbstract =  'textarea';
               $fieldVisible = true;

            }
            $customField = [
                'component' => 'Magento_Ui/js/form/element/'.$fieldAbstract.'',
                'config' => [
                    'customScope' => 'shippingAddress.custom_attributes',
                    'customEntry' => null,
                    'template' => 'ui/form/field',
                    'elementTmpl' => 'ui/form/element/'.$fieldInputType.'',

                ],
                'dataScope' => 'shippingAddress.custom_attributes' . '.' . $customAttributeCode,
                'label' => $frontEndLabel,
                'provider' => 'checkoutProvider',
                'sortOrder' => $sortOrder,
                'validation' => [$fieldFrontendClass => true , 
                    'required-entry' => $fieldRequiredClass],
                'options' =>  $allOptions,
                'filterBy' => null,
                'customEntry' => null,
                'visible' => $fieldVisible,
                'value' => $customerAttr
            ];

             return $customField;
        }

}

Note:

change 'component' => 'Magento_Ui/js/form/element/abstract', into 'component' => 'Magento_Ui/js/form/element/select',

2
  • Thanks Its working :) Commented Sep 27, 2019 at 8:57
  • Happy coding :) @Manish Commented Sep 27, 2019 at 8:59
2

I had the same problem.

The component option of your custom_field must be declare as "Magento_Ui/js/form/element/select" instead of "Magento_Ui/js/form/element/abstract".

Regards.

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.