Magento 2 Get customer ID from session in a block class












9















How to get customer ID from session? I tried this but not work.



protected $_customerBonusPointFactory;
protected $_customerSession;

public function __construct(Session $customerSession, MagentoFrameworkViewElementTemplateContext $context) {
$this->_customerSession = $customerSession;
parent::__construct($context);
}

public function _prepareLayout() {
var_dump($this->_customerSession->getCustomer()->getId());
exit();
return parent::_prepareLayout();
}









share|improve this question




















  • 2





    If customer logged in then you can get customer id otherwise it's return null using '$this->_customerSession->getCustomer()->getId()'

    – Sohel Rana
    Aug 3 '16 at 17:48











  • I have logged in but it returns null. And I'm doing it in the block class.

    – Paul
    Aug 3 '16 at 17:50













  • Which session class you use?

    – Sohel Rana
    Aug 3 '16 at 17:51











  • I just found that $this->session->isLoggedIn() return true in my controller class but return false in my block class. Why?

    – Paul
    Aug 3 '16 at 17:53






  • 3





    Block has to be set cacheable=false see Magento 2 - Get customer ID from session in a block class

    – Lukas Komarek
    Oct 18 '17 at 11:58
















9















How to get customer ID from session? I tried this but not work.



protected $_customerBonusPointFactory;
protected $_customerSession;

public function __construct(Session $customerSession, MagentoFrameworkViewElementTemplateContext $context) {
$this->_customerSession = $customerSession;
parent::__construct($context);
}

public function _prepareLayout() {
var_dump($this->_customerSession->getCustomer()->getId());
exit();
return parent::_prepareLayout();
}









share|improve this question




















  • 2





    If customer logged in then you can get customer id otherwise it's return null using '$this->_customerSession->getCustomer()->getId()'

    – Sohel Rana
    Aug 3 '16 at 17:48











  • I have logged in but it returns null. And I'm doing it in the block class.

    – Paul
    Aug 3 '16 at 17:50













  • Which session class you use?

    – Sohel Rana
    Aug 3 '16 at 17:51











  • I just found that $this->session->isLoggedIn() return true in my controller class but return false in my block class. Why?

    – Paul
    Aug 3 '16 at 17:53






  • 3





    Block has to be set cacheable=false see Magento 2 - Get customer ID from session in a block class

    – Lukas Komarek
    Oct 18 '17 at 11:58














9












9








9


3






How to get customer ID from session? I tried this but not work.



protected $_customerBonusPointFactory;
protected $_customerSession;

public function __construct(Session $customerSession, MagentoFrameworkViewElementTemplateContext $context) {
$this->_customerSession = $customerSession;
parent::__construct($context);
}

public function _prepareLayout() {
var_dump($this->_customerSession->getCustomer()->getId());
exit();
return parent::_prepareLayout();
}









share|improve this question
















How to get customer ID from session? I tried this but not work.



protected $_customerBonusPointFactory;
protected $_customerSession;

public function __construct(Session $customerSession, MagentoFrameworkViewElementTemplateContext $context) {
$this->_customerSession = $customerSession;
parent::__construct($context);
}

public function _prepareLayout() {
var_dump($this->_customerSession->getCustomer()->getId());
exit();
return parent::_prepareLayout();
}






magento2 customer






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 12 '18 at 6:25









Himanshu

827521




827521










asked Aug 3 '16 at 17:38









PaulPaul

1,77652658




1,77652658








  • 2





    If customer logged in then you can get customer id otherwise it's return null using '$this->_customerSession->getCustomer()->getId()'

    – Sohel Rana
    Aug 3 '16 at 17:48











  • I have logged in but it returns null. And I'm doing it in the block class.

    – Paul
    Aug 3 '16 at 17:50













  • Which session class you use?

    – Sohel Rana
    Aug 3 '16 at 17:51











  • I just found that $this->session->isLoggedIn() return true in my controller class but return false in my block class. Why?

    – Paul
    Aug 3 '16 at 17:53






  • 3





    Block has to be set cacheable=false see Magento 2 - Get customer ID from session in a block class

    – Lukas Komarek
    Oct 18 '17 at 11:58














  • 2





    If customer logged in then you can get customer id otherwise it's return null using '$this->_customerSession->getCustomer()->getId()'

    – Sohel Rana
    Aug 3 '16 at 17:48











  • I have logged in but it returns null. And I'm doing it in the block class.

    – Paul
    Aug 3 '16 at 17:50













  • Which session class you use?

    – Sohel Rana
    Aug 3 '16 at 17:51











  • I just found that $this->session->isLoggedIn() return true in my controller class but return false in my block class. Why?

    – Paul
    Aug 3 '16 at 17:53






  • 3





    Block has to be set cacheable=false see Magento 2 - Get customer ID from session in a block class

    – Lukas Komarek
    Oct 18 '17 at 11:58








2




2





If customer logged in then you can get customer id otherwise it's return null using '$this->_customerSession->getCustomer()->getId()'

– Sohel Rana
Aug 3 '16 at 17:48





If customer logged in then you can get customer id otherwise it's return null using '$this->_customerSession->getCustomer()->getId()'

– Sohel Rana
Aug 3 '16 at 17:48













I have logged in but it returns null. And I'm doing it in the block class.

– Paul
Aug 3 '16 at 17:50







I have logged in but it returns null. And I'm doing it in the block class.

– Paul
Aug 3 '16 at 17:50















Which session class you use?

– Sohel Rana
Aug 3 '16 at 17:51





Which session class you use?

– Sohel Rana
Aug 3 '16 at 17:51













I just found that $this->session->isLoggedIn() return true in my controller class but return false in my block class. Why?

– Paul
Aug 3 '16 at 17:53





I just found that $this->session->isLoggedIn() return true in my controller class but return false in my block class. Why?

– Paul
Aug 3 '16 at 17:53




3




3





Block has to be set cacheable=false see Magento 2 - Get customer ID from session in a block class

– Lukas Komarek
Oct 18 '17 at 11:58





Block has to be set cacheable=false see Magento 2 - Get customer ID from session in a block class

– Lukas Komarek
Oct 18 '17 at 11:58










6 Answers
6






active

oldest

votes


















13














It's working copy. You can compare with your block class. Here I use Form as block class



namespace VendorModuleBlock;


class Form extends MagentoFrameworkViewElementTemplate
{
protected $customerSession;

/**
* Construct
*
* @param MagentoFrameworkViewElementTemplateContext $context
* @param MagentoCustomerModelSession $customerSession
* @param array $data
*/
public function __construct(
MagentoFrameworkViewElementTemplateContext $context,
MagentoCustomerModelSession $customerSession,
array $data =
) {
parent::__construct($context, $data);

$this->customerSession = $customerSession;
}

public function _prepareLayout()
{

var_dump($this->customerSession->getCustomer()->getId());
exit();
return parent::_prepareLayout();
}
}





share|improve this answer





















  • 1





    I did exactly the same but it still return null. And $this->customerSession->isLoggedIn() is false always. I do the same in a controller class and it works fine.

    – Paul
    Aug 3 '16 at 18:21











  • Finally, it works. I'm not sure what I have changed.

    – Paul
    Aug 5 '16 at 9:49











  • have you disabled full page cache maybe?

    – davideghz
    Mar 22 '17 at 8:32











  • Yes it was cache I've had same issue <block class="VendorBlockBlaBla" name="block.name" template="Wed2b_Suppliers::template/template.phtml" cacheable="false"/>

    – Juliano Vargas
    Aug 9 '18 at 14:27



















3














When You define block which use session You have to disable cache for it.



 <block class="VendorModuleBlockIndex" name="Name"
template="Vendor_Module::template/path.phtml" cacheable="false">
</block>





share|improve this answer



















  • 1





    this will cause the whole page and every page that use this block will be MISSed by the FPC

    – Doni Wibowo
    May 7 '18 at 9:47













  • @DoniWibowo that is true, but you need to be carefull when caching pages with dynamic data in the first place. You don't want to display the same name for all customers for example.

    – Radu
    Oct 3 '18 at 15:03



















1














It seems to work when you pass the Context object to the parent class before instantiating the customer session :



class History extends MagentoFrameworkViewElementTemplate
{

/**
* @var Session
*/
protected $_session;

public function __construct(
TemplateContext $context,
MagentoCustomerModelSession $session,
array $data
)
{
parent::__construct($context, $data);
$this->_session = $session;
}

public function _prepareLayout()
{

var_dump($this->_session->getCustomerId());
exit();
return parent::_prepareLayout();
}
}





share|improve this answer



















  • 2





    Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference.

    – nshiff
    Apr 4 '17 at 15:22



















1














You need to inject MagentoCustomerModelSession $customerSession, class to get customer ID from customer session.



protected $_customerSession;

public function __construct(
...
MagentoCustomerModelSession $customerSession,
...
) {
...
$this->_customerSession = $customerSession;
...
}

public function getCustomer()
{
echo $this->_customerSession->getCustomer()->getId(); //Print current customer ID

$customerData = $this->_customerSession->getCustomer();
print_r($customerData->getData()); //Print current Customer Data
}


NOTE: You only get customer id if customer logged in and customer session initialized






share|improve this answer

































    0














    While we are injecting customer session in block to retrive logged in customer data and we are not getting customer data from block because Magento 2 reset all the customer sessions when FPC is enabled.



    Please use cacheable="false" for bloick in your layout :



    <referenceContainer name="content"> 
    <block class="ArmanTestBlockList" name="list" template="Arman_Test::list.phtml" cacheable="false">
    </block>
    </referenceContainer>


    In this case, Magento 2 ignore this page from caching.






    share|improve this answer































      0














      If you need only the customer_id then without loading whole object (see method getCustomer method) you can get it by simply using getCustomerId method.



      As getId method also calls getCustomerId method.




      file : vendor/magento/module-customer/Model/Session.php




      /**
      * Retrieve customer model object
      *
      * @return Customer
      * use getCustomerId() instead
      */
      public function getCustomer()
      {
      if ($this->_customerModel === null) {
      $this->_customerModel = $this->_customerFactory->create()->load($this->getCustomerId());
      }

      return $this->_customerModel;
      }


      /**
      * Retrieve customer id from current session
      *
      * @api
      * @return int|null
      */
      public function getCustomerId()
      {
      if ($this->storage->getData('customer_id')) {
      return $this->storage->getData('customer_id');
      }
      return null;
      }

      /**
      * Retrieve customer id from current session
      *
      * @return int|null
      */
      public function getId()
      {
      return $this->getCustomerId();
      }





      share|improve this answer























        Your Answer








        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "479"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f128830%2fmagento-2-get-customer-id-from-session-in-a-block-class%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        13














        It's working copy. You can compare with your block class. Here I use Form as block class



        namespace VendorModuleBlock;


        class Form extends MagentoFrameworkViewElementTemplate
        {
        protected $customerSession;

        /**
        * Construct
        *
        * @param MagentoFrameworkViewElementTemplateContext $context
        * @param MagentoCustomerModelSession $customerSession
        * @param array $data
        */
        public function __construct(
        MagentoFrameworkViewElementTemplateContext $context,
        MagentoCustomerModelSession $customerSession,
        array $data =
        ) {
        parent::__construct($context, $data);

        $this->customerSession = $customerSession;
        }

        public function _prepareLayout()
        {

        var_dump($this->customerSession->getCustomer()->getId());
        exit();
        return parent::_prepareLayout();
        }
        }





        share|improve this answer





















        • 1





          I did exactly the same but it still return null. And $this->customerSession->isLoggedIn() is false always. I do the same in a controller class and it works fine.

          – Paul
          Aug 3 '16 at 18:21











        • Finally, it works. I'm not sure what I have changed.

          – Paul
          Aug 5 '16 at 9:49











        • have you disabled full page cache maybe?

          – davideghz
          Mar 22 '17 at 8:32











        • Yes it was cache I've had same issue <block class="VendorBlockBlaBla" name="block.name" template="Wed2b_Suppliers::template/template.phtml" cacheable="false"/>

          – Juliano Vargas
          Aug 9 '18 at 14:27
















        13














        It's working copy. You can compare with your block class. Here I use Form as block class



        namespace VendorModuleBlock;


        class Form extends MagentoFrameworkViewElementTemplate
        {
        protected $customerSession;

        /**
        * Construct
        *
        * @param MagentoFrameworkViewElementTemplateContext $context
        * @param MagentoCustomerModelSession $customerSession
        * @param array $data
        */
        public function __construct(
        MagentoFrameworkViewElementTemplateContext $context,
        MagentoCustomerModelSession $customerSession,
        array $data =
        ) {
        parent::__construct($context, $data);

        $this->customerSession = $customerSession;
        }

        public function _prepareLayout()
        {

        var_dump($this->customerSession->getCustomer()->getId());
        exit();
        return parent::_prepareLayout();
        }
        }





        share|improve this answer





















        • 1





          I did exactly the same but it still return null. And $this->customerSession->isLoggedIn() is false always. I do the same in a controller class and it works fine.

          – Paul
          Aug 3 '16 at 18:21











        • Finally, it works. I'm not sure what I have changed.

          – Paul
          Aug 5 '16 at 9:49











        • have you disabled full page cache maybe?

          – davideghz
          Mar 22 '17 at 8:32











        • Yes it was cache I've had same issue <block class="VendorBlockBlaBla" name="block.name" template="Wed2b_Suppliers::template/template.phtml" cacheable="false"/>

          – Juliano Vargas
          Aug 9 '18 at 14:27














        13












        13








        13







        It's working copy. You can compare with your block class. Here I use Form as block class



        namespace VendorModuleBlock;


        class Form extends MagentoFrameworkViewElementTemplate
        {
        protected $customerSession;

        /**
        * Construct
        *
        * @param MagentoFrameworkViewElementTemplateContext $context
        * @param MagentoCustomerModelSession $customerSession
        * @param array $data
        */
        public function __construct(
        MagentoFrameworkViewElementTemplateContext $context,
        MagentoCustomerModelSession $customerSession,
        array $data =
        ) {
        parent::__construct($context, $data);

        $this->customerSession = $customerSession;
        }

        public function _prepareLayout()
        {

        var_dump($this->customerSession->getCustomer()->getId());
        exit();
        return parent::_prepareLayout();
        }
        }





        share|improve this answer















        It's working copy. You can compare with your block class. Here I use Form as block class



        namespace VendorModuleBlock;


        class Form extends MagentoFrameworkViewElementTemplate
        {
        protected $customerSession;

        /**
        * Construct
        *
        * @param MagentoFrameworkViewElementTemplateContext $context
        * @param MagentoCustomerModelSession $customerSession
        * @param array $data
        */
        public function __construct(
        MagentoFrameworkViewElementTemplateContext $context,
        MagentoCustomerModelSession $customerSession,
        array $data =
        ) {
        parent::__construct($context, $data);

        $this->customerSession = $customerSession;
        }

        public function _prepareLayout()
        {

        var_dump($this->customerSession->getCustomer()->getId());
        exit();
        return parent::_prepareLayout();
        }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 16 '17 at 20:48









        P0lT10n

        1054




        1054










        answered Aug 3 '16 at 18:10









        Sohel RanaSohel Rana

        20.3k33954




        20.3k33954








        • 1





          I did exactly the same but it still return null. And $this->customerSession->isLoggedIn() is false always. I do the same in a controller class and it works fine.

          – Paul
          Aug 3 '16 at 18:21











        • Finally, it works. I'm not sure what I have changed.

          – Paul
          Aug 5 '16 at 9:49











        • have you disabled full page cache maybe?

          – davideghz
          Mar 22 '17 at 8:32











        • Yes it was cache I've had same issue <block class="VendorBlockBlaBla" name="block.name" template="Wed2b_Suppliers::template/template.phtml" cacheable="false"/>

          – Juliano Vargas
          Aug 9 '18 at 14:27














        • 1





          I did exactly the same but it still return null. And $this->customerSession->isLoggedIn() is false always. I do the same in a controller class and it works fine.

          – Paul
          Aug 3 '16 at 18:21











        • Finally, it works. I'm not sure what I have changed.

          – Paul
          Aug 5 '16 at 9:49











        • have you disabled full page cache maybe?

          – davideghz
          Mar 22 '17 at 8:32











        • Yes it was cache I've had same issue <block class="VendorBlockBlaBla" name="block.name" template="Wed2b_Suppliers::template/template.phtml" cacheable="false"/>

          – Juliano Vargas
          Aug 9 '18 at 14:27








        1




        1





        I did exactly the same but it still return null. And $this->customerSession->isLoggedIn() is false always. I do the same in a controller class and it works fine.

        – Paul
        Aug 3 '16 at 18:21





        I did exactly the same but it still return null. And $this->customerSession->isLoggedIn() is false always. I do the same in a controller class and it works fine.

        – Paul
        Aug 3 '16 at 18:21













        Finally, it works. I'm not sure what I have changed.

        – Paul
        Aug 5 '16 at 9:49





        Finally, it works. I'm not sure what I have changed.

        – Paul
        Aug 5 '16 at 9:49













        have you disabled full page cache maybe?

        – davideghz
        Mar 22 '17 at 8:32





        have you disabled full page cache maybe?

        – davideghz
        Mar 22 '17 at 8:32













        Yes it was cache I've had same issue <block class="VendorBlockBlaBla" name="block.name" template="Wed2b_Suppliers::template/template.phtml" cacheable="false"/>

        – Juliano Vargas
        Aug 9 '18 at 14:27





        Yes it was cache I've had same issue <block class="VendorBlockBlaBla" name="block.name" template="Wed2b_Suppliers::template/template.phtml" cacheable="false"/>

        – Juliano Vargas
        Aug 9 '18 at 14:27













        3














        When You define block which use session You have to disable cache for it.



         <block class="VendorModuleBlockIndex" name="Name"
        template="Vendor_Module::template/path.phtml" cacheable="false">
        </block>





        share|improve this answer



















        • 1





          this will cause the whole page and every page that use this block will be MISSed by the FPC

          – Doni Wibowo
          May 7 '18 at 9:47













        • @DoniWibowo that is true, but you need to be carefull when caching pages with dynamic data in the first place. You don't want to display the same name for all customers for example.

          – Radu
          Oct 3 '18 at 15:03
















        3














        When You define block which use session You have to disable cache for it.



         <block class="VendorModuleBlockIndex" name="Name"
        template="Vendor_Module::template/path.phtml" cacheable="false">
        </block>





        share|improve this answer



















        • 1





          this will cause the whole page and every page that use this block will be MISSed by the FPC

          – Doni Wibowo
          May 7 '18 at 9:47













        • @DoniWibowo that is true, but you need to be carefull when caching pages with dynamic data in the first place. You don't want to display the same name for all customers for example.

          – Radu
          Oct 3 '18 at 15:03














        3












        3








        3







        When You define block which use session You have to disable cache for it.



         <block class="VendorModuleBlockIndex" name="Name"
        template="Vendor_Module::template/path.phtml" cacheable="false">
        </block>





        share|improve this answer













        When You define block which use session You have to disable cache for it.



         <block class="VendorModuleBlockIndex" name="Name"
        template="Vendor_Module::template/path.phtml" cacheable="false">
        </block>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 5 '17 at 12:15









        Marcin ŻurekMarcin Żurek

        311




        311








        • 1





          this will cause the whole page and every page that use this block will be MISSed by the FPC

          – Doni Wibowo
          May 7 '18 at 9:47













        • @DoniWibowo that is true, but you need to be carefull when caching pages with dynamic data in the first place. You don't want to display the same name for all customers for example.

          – Radu
          Oct 3 '18 at 15:03














        • 1





          this will cause the whole page and every page that use this block will be MISSed by the FPC

          – Doni Wibowo
          May 7 '18 at 9:47













        • @DoniWibowo that is true, but you need to be carefull when caching pages with dynamic data in the first place. You don't want to display the same name for all customers for example.

          – Radu
          Oct 3 '18 at 15:03








        1




        1





        this will cause the whole page and every page that use this block will be MISSed by the FPC

        – Doni Wibowo
        May 7 '18 at 9:47







        this will cause the whole page and every page that use this block will be MISSed by the FPC

        – Doni Wibowo
        May 7 '18 at 9:47















        @DoniWibowo that is true, but you need to be carefull when caching pages with dynamic data in the first place. You don't want to display the same name for all customers for example.

        – Radu
        Oct 3 '18 at 15:03





        @DoniWibowo that is true, but you need to be carefull when caching pages with dynamic data in the first place. You don't want to display the same name for all customers for example.

        – Radu
        Oct 3 '18 at 15:03











        1














        It seems to work when you pass the Context object to the parent class before instantiating the customer session :



        class History extends MagentoFrameworkViewElementTemplate
        {

        /**
        * @var Session
        */
        protected $_session;

        public function __construct(
        TemplateContext $context,
        MagentoCustomerModelSession $session,
        array $data
        )
        {
        parent::__construct($context, $data);
        $this->_session = $session;
        }

        public function _prepareLayout()
        {

        var_dump($this->_session->getCustomerId());
        exit();
        return parent::_prepareLayout();
        }
        }





        share|improve this answer



















        • 2





          Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference.

          – nshiff
          Apr 4 '17 at 15:22
















        1














        It seems to work when you pass the Context object to the parent class before instantiating the customer session :



        class History extends MagentoFrameworkViewElementTemplate
        {

        /**
        * @var Session
        */
        protected $_session;

        public function __construct(
        TemplateContext $context,
        MagentoCustomerModelSession $session,
        array $data
        )
        {
        parent::__construct($context, $data);
        $this->_session = $session;
        }

        public function _prepareLayout()
        {

        var_dump($this->_session->getCustomerId());
        exit();
        return parent::_prepareLayout();
        }
        }





        share|improve this answer



















        • 2





          Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference.

          – nshiff
          Apr 4 '17 at 15:22














        1












        1








        1







        It seems to work when you pass the Context object to the parent class before instantiating the customer session :



        class History extends MagentoFrameworkViewElementTemplate
        {

        /**
        * @var Session
        */
        protected $_session;

        public function __construct(
        TemplateContext $context,
        MagentoCustomerModelSession $session,
        array $data
        )
        {
        parent::__construct($context, $data);
        $this->_session = $session;
        }

        public function _prepareLayout()
        {

        var_dump($this->_session->getCustomerId());
        exit();
        return parent::_prepareLayout();
        }
        }





        share|improve this answer













        It seems to work when you pass the Context object to the parent class before instantiating the customer session :



        class History extends MagentoFrameworkViewElementTemplate
        {

        /**
        * @var Session
        */
        protected $_session;

        public function __construct(
        TemplateContext $context,
        MagentoCustomerModelSession $session,
        array $data
        )
        {
        parent::__construct($context, $data);
        $this->_session = $session;
        }

        public function _prepareLayout()
        {

        var_dump($this->_session->getCustomerId());
        exit();
        return parent::_prepareLayout();
        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 7 '16 at 15:19









        ptidusptidus

        366




        366








        • 2





          Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference.

          – nshiff
          Apr 4 '17 at 15:22














        • 2





          Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference.

          – nshiff
          Apr 4 '17 at 15:22








        2




        2





        Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference.

        – nshiff
        Apr 4 '17 at 15:22





        Odd. I observe the same thing. Thank you for the help. I wonder why this makes a difference.

        – nshiff
        Apr 4 '17 at 15:22











        1














        You need to inject MagentoCustomerModelSession $customerSession, class to get customer ID from customer session.



        protected $_customerSession;

        public function __construct(
        ...
        MagentoCustomerModelSession $customerSession,
        ...
        ) {
        ...
        $this->_customerSession = $customerSession;
        ...
        }

        public function getCustomer()
        {
        echo $this->_customerSession->getCustomer()->getId(); //Print current customer ID

        $customerData = $this->_customerSession->getCustomer();
        print_r($customerData->getData()); //Print current Customer Data
        }


        NOTE: You only get customer id if customer logged in and customer session initialized






        share|improve this answer






























          1














          You need to inject MagentoCustomerModelSession $customerSession, class to get customer ID from customer session.



          protected $_customerSession;

          public function __construct(
          ...
          MagentoCustomerModelSession $customerSession,
          ...
          ) {
          ...
          $this->_customerSession = $customerSession;
          ...
          }

          public function getCustomer()
          {
          echo $this->_customerSession->getCustomer()->getId(); //Print current customer ID

          $customerData = $this->_customerSession->getCustomer();
          print_r($customerData->getData()); //Print current Customer Data
          }


          NOTE: You only get customer id if customer logged in and customer session initialized






          share|improve this answer




























            1












            1








            1







            You need to inject MagentoCustomerModelSession $customerSession, class to get customer ID from customer session.



            protected $_customerSession;

            public function __construct(
            ...
            MagentoCustomerModelSession $customerSession,
            ...
            ) {
            ...
            $this->_customerSession = $customerSession;
            ...
            }

            public function getCustomer()
            {
            echo $this->_customerSession->getCustomer()->getId(); //Print current customer ID

            $customerData = $this->_customerSession->getCustomer();
            print_r($customerData->getData()); //Print current Customer Data
            }


            NOTE: You only get customer id if customer logged in and customer session initialized






            share|improve this answer















            You need to inject MagentoCustomerModelSession $customerSession, class to get customer ID from customer session.



            protected $_customerSession;

            public function __construct(
            ...
            MagentoCustomerModelSession $customerSession,
            ...
            ) {
            ...
            $this->_customerSession = $customerSession;
            ...
            }

            public function getCustomer()
            {
            echo $this->_customerSession->getCustomer()->getId(); //Print current customer ID

            $customerData = $this->_customerSession->getCustomer();
            print_r($customerData->getData()); //Print current Customer Data
            }


            NOTE: You only get customer id if customer logged in and customer session initialized







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 22 '17 at 5:18

























            answered Apr 26 '17 at 9:11









            Prince PatelPrince Patel

            13.3k54776




            13.3k54776























                0














                While we are injecting customer session in block to retrive logged in customer data and we are not getting customer data from block because Magento 2 reset all the customer sessions when FPC is enabled.



                Please use cacheable="false" for bloick in your layout :



                <referenceContainer name="content"> 
                <block class="ArmanTestBlockList" name="list" template="Arman_Test::list.phtml" cacheable="false">
                </block>
                </referenceContainer>


                In this case, Magento 2 ignore this page from caching.






                share|improve this answer




























                  0














                  While we are injecting customer session in block to retrive logged in customer data and we are not getting customer data from block because Magento 2 reset all the customer sessions when FPC is enabled.



                  Please use cacheable="false" for bloick in your layout :



                  <referenceContainer name="content"> 
                  <block class="ArmanTestBlockList" name="list" template="Arman_Test::list.phtml" cacheable="false">
                  </block>
                  </referenceContainer>


                  In this case, Magento 2 ignore this page from caching.






                  share|improve this answer


























                    0












                    0








                    0







                    While we are injecting customer session in block to retrive logged in customer data and we are not getting customer data from block because Magento 2 reset all the customer sessions when FPC is enabled.



                    Please use cacheable="false" for bloick in your layout :



                    <referenceContainer name="content"> 
                    <block class="ArmanTestBlockList" name="list" template="Arman_Test::list.phtml" cacheable="false">
                    </block>
                    </referenceContainer>


                    In this case, Magento 2 ignore this page from caching.






                    share|improve this answer













                    While we are injecting customer session in block to retrive logged in customer data and we are not getting customer data from block because Magento 2 reset all the customer sessions when FPC is enabled.



                    Please use cacheable="false" for bloick in your layout :



                    <referenceContainer name="content"> 
                    <block class="ArmanTestBlockList" name="list" template="Arman_Test::list.phtml" cacheable="false">
                    </block>
                    </referenceContainer>


                    In this case, Magento 2 ignore this page from caching.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered May 16 '18 at 5:37









                    Khan armanKhan arman

                    613




                    613























                        0














                        If you need only the customer_id then without loading whole object (see method getCustomer method) you can get it by simply using getCustomerId method.



                        As getId method also calls getCustomerId method.




                        file : vendor/magento/module-customer/Model/Session.php




                        /**
                        * Retrieve customer model object
                        *
                        * @return Customer
                        * use getCustomerId() instead
                        */
                        public function getCustomer()
                        {
                        if ($this->_customerModel === null) {
                        $this->_customerModel = $this->_customerFactory->create()->load($this->getCustomerId());
                        }

                        return $this->_customerModel;
                        }


                        /**
                        * Retrieve customer id from current session
                        *
                        * @api
                        * @return int|null
                        */
                        public function getCustomerId()
                        {
                        if ($this->storage->getData('customer_id')) {
                        return $this->storage->getData('customer_id');
                        }
                        return null;
                        }

                        /**
                        * Retrieve customer id from current session
                        *
                        * @return int|null
                        */
                        public function getId()
                        {
                        return $this->getCustomerId();
                        }





                        share|improve this answer




























                          0














                          If you need only the customer_id then without loading whole object (see method getCustomer method) you can get it by simply using getCustomerId method.



                          As getId method also calls getCustomerId method.




                          file : vendor/magento/module-customer/Model/Session.php




                          /**
                          * Retrieve customer model object
                          *
                          * @return Customer
                          * use getCustomerId() instead
                          */
                          public function getCustomer()
                          {
                          if ($this->_customerModel === null) {
                          $this->_customerModel = $this->_customerFactory->create()->load($this->getCustomerId());
                          }

                          return $this->_customerModel;
                          }


                          /**
                          * Retrieve customer id from current session
                          *
                          * @api
                          * @return int|null
                          */
                          public function getCustomerId()
                          {
                          if ($this->storage->getData('customer_id')) {
                          return $this->storage->getData('customer_id');
                          }
                          return null;
                          }

                          /**
                          * Retrieve customer id from current session
                          *
                          * @return int|null
                          */
                          public function getId()
                          {
                          return $this->getCustomerId();
                          }





                          share|improve this answer


























                            0












                            0








                            0







                            If you need only the customer_id then without loading whole object (see method getCustomer method) you can get it by simply using getCustomerId method.



                            As getId method also calls getCustomerId method.




                            file : vendor/magento/module-customer/Model/Session.php




                            /**
                            * Retrieve customer model object
                            *
                            * @return Customer
                            * use getCustomerId() instead
                            */
                            public function getCustomer()
                            {
                            if ($this->_customerModel === null) {
                            $this->_customerModel = $this->_customerFactory->create()->load($this->getCustomerId());
                            }

                            return $this->_customerModel;
                            }


                            /**
                            * Retrieve customer id from current session
                            *
                            * @api
                            * @return int|null
                            */
                            public function getCustomerId()
                            {
                            if ($this->storage->getData('customer_id')) {
                            return $this->storage->getData('customer_id');
                            }
                            return null;
                            }

                            /**
                            * Retrieve customer id from current session
                            *
                            * @return int|null
                            */
                            public function getId()
                            {
                            return $this->getCustomerId();
                            }





                            share|improve this answer













                            If you need only the customer_id then without loading whole object (see method getCustomer method) you can get it by simply using getCustomerId method.



                            As getId method also calls getCustomerId method.




                            file : vendor/magento/module-customer/Model/Session.php




                            /**
                            * Retrieve customer model object
                            *
                            * @return Customer
                            * use getCustomerId() instead
                            */
                            public function getCustomer()
                            {
                            if ($this->_customerModel === null) {
                            $this->_customerModel = $this->_customerFactory->create()->load($this->getCustomerId());
                            }

                            return $this->_customerModel;
                            }


                            /**
                            * Retrieve customer id from current session
                            *
                            * @api
                            * @return int|null
                            */
                            public function getCustomerId()
                            {
                            if ($this->storage->getData('customer_id')) {
                            return $this->storage->getData('customer_id');
                            }
                            return null;
                            }

                            /**
                            * Retrieve customer id from current session
                            *
                            * @return int|null
                            */
                            public function getId()
                            {
                            return $this->getCustomerId();
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 16 at 10:48









                            Knight017Knight017

                            322111




                            322111






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Magento Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f128830%2fmagento-2-get-customer-id-from-session-in-a-block-class%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                1300-talet

                                1300-talet

                                Display a custom attribute below product name in the front-end Magento 1.9.3.8