Magento 2 Customer Attribute – How to Get Customer Gender Options

customercustomer-attributemagento2

I want to display select input field which contain customer gender options in my custom layout block in magento 2 ? how can i do this?

/Vendor/Module/Block/Customer.php

public function getCustomerGenderOptions(){
  //how?
}

/Vendor/Module/view/frontend/templates/customer.phtml

<select name="gender">
 <?php foreach ($block->getCustomerGenderOptions() as $genderOption): ?>
    <option value="<?= $genderOption['value'] ?>"><?= $genderOption['label'] ?></option>
 <?php endforeach; ?>
</select>

Best Answer

Use Below code

<?php

namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Backend\Block\Template\Context;;
use Magento\Eav\Model\Config;

class Customer extends Template
{    
   protected $eavConfig;

   public function __construct(
        Context $context,       
        Config $eavConfig
    )
    {    
        $this->eavConfig = $eavConfig;
        parent::__construct($context);

    }

    public function getCustomerGenderOptions(){
        $attribute = $this->eavConfig->getAttribute('customer','gender');
        $options = $attribute->getSource()->getAllOptions();
        return $options;
    }
}
Related Topic