Question

I am just trying to get the customer session in my custom controller class and it always returns NULL.

What is wrong with Magento? It doesn't work as expected, I am spending days not minutes for a small changes...

Here is my custom controller class.

class Referral extends \Magento\Customer\Controller\AbstractAccount {

    protected $customerRepository;

    protected $dataObjectHelper;
    protected $session;
    protected $resultPageFactory;

    public function __construct(
        Context $context,
        \Magento\Customer\Model\Session $customerSession,
        PageFactory $resultPageFactory,
        CustomerRepositoryInterface $customerRepository,
        DataObjectHelper $dataObjectHelper
    ) {
        $this->session            = $customerSession;
        $this->resultPageFactory  = $resultPageFactory;
        $this->customerRepository = $customerRepository;
        $this->dataObjectHelper   = $dataObjectHelper;
        parent::__construct( $context );
    }

    public function execute() {
        $resultPage = $this->resultPageFactory->create();

        $block = $resultPage->getLayout()->getBlock( 'customer_account_dashboard_referral_edit' );
        if ( $block ) {
            $block->setRefererUrl( $this->_redirect->getRefererUrl() );
        }

        $data = $this->session->getCustomerFormData(true);
        $customerId = $this->session->getCustomerId();
        var_dump($customerId);
        exit;

        $customerDataObject = $this->customerRepository->getById( $customerId );
        if ( ! empty( $data ) ) {
            $this->dataObjectHelper->populateWithArray(
                $customerDataObject,
                $data,
                \Magento\Customer\Api\Data\CustomerInterface::class
            );
        }
        $resultPage->getConfig()->getTitle()->set( __( 'Referral Settings' ) );

        return $resultPage;
    }
}

In that case it returns NULL, I have found only one way to get real id

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->create("Magento\Customer\Model\Session");

In this case it works, and I can get customer id, but why??? What is the purpose of all these dependency injections and other features, it even doesn't work in a simple case...

Please explain what is wrong ?

Was it helpful?

Solution

I think you need do it :

PS: "purpose of all these dependency injections" use Factory ."

Example :

...
protected $sessionFactory;
...
public function __construct(
        ...
        \Magento\Customer\Model\SessionFactory $sessionFactory,
       ...
    ) {
        $this->sessionFactory = $sessionFactory;
        ...
    }

    public function execute() {

        ...
        $sessionModel = $this->sessionFactory->create();
        $customerId = $sessionModel->getCustomer()->getId();
        ...
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top