Magento 2 – Get Customer Gender as Text from Integer Value

blocksmagento2

I want to get customer gender value like Male or Female in magento2?
How to get it in \Magento\Customer\Block\Account\Dashboard\Info block,

I am doing something like this

$block->getCustomer()->getGender()

I referred this link
How to get customer gender value with text in magento2?

I don't want to use ObjectManager just for gender, there must be something via this method $block->getCustomer()->getGender()

Best Answer

Use this below code in your block :

protected $customerSession;

public function __construct(
    ....
    \Magento\Customer\Model\Session $customerSession
    ....
) {
    ....
    $this->customerSession = $customerSession;
    ....
}

public function yourFunction()
{
    //$customerId = 12;
    if($this->customerSession->isLoggedIn()){
        $customer = $this->customerSession->getCustomer();
        $customerId = $customer->getId();
        $genderText = $customer->getAttribute('gender')->getSource()->getOptionText($customer->getData('gender'));
        echo $genderText;
    } else{
        echo 'customer is not logged in';
    }
}
Related Topic