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 ?