Come accedere all'ID cliente

Sep 04 2020

Sto cercando di ottenere l'ID cliente di un cliente connesso ma sembra che non funzioni

nel mio blocco

<?php
namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Backend\Block\Template\Context;

class Rfq extends \Magento\Framework\View\Element\Template
{    
    protected $_customerSession; public function __construct(Context $context,
        \Magento\Customer\Model\Session $customerSession, array $data = [])
    {
        parent::__construct($context, $data);
        $this->_customerSession = $customerSession;   
    }

            public function getCustomerId()
                    {
                         if($this->_customerSession->isLoggedIn()): return $this->_customerSession->getCustomer()->getId();                        
                         endif;
                    }

            public function execute()
            {

                $this->_view->loadLayout(); $this->_view->getLayout()->initMessages();
                $this->_view->renderLayout();
            }
        }

Ora nel file phtml

<?php
$customerId = $customer->getCustomerId();
?>

qualsiasi suggerimento o problema nel codice grazie

Aggiorna controller

<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;

class Customer extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;

    public function __construct(
        Context $context, PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context); } public function execute() { return $this->resultPageFactory->create();
        $this->_view->loadLayout(); $this->_view->renderLayout(); 
    }


  
} 
 

Risposte

3 AmitBera Sep 08 2020 at 17:42

Se non è possibile identificare l'ID cliente nella classe di blocco quando la pagina viene visualizzata nella cache della pagina intera.

Devi passare l' ID cliente come variabile di contesto HTTP .

Vedere https://devdocs.magento.com/guides/v2.3/extension-dev-guide/cache/page-caching/public-content.html#configure-page-variations

Crea una classe plugin su Magento\Framework\App\Action\AbstractAction.

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 
    <type name="Magento\Framework\App\Action\AbstractAction">
        <plugin name="add_customr_id_full_page"  disabled="false" sortOrder="20"
                type="Devamitbera\Module\Plugin\Framework\App\Action"/>        
    </type>   

    </type>      
</config>

Sul plug-in, passare l'ID cliente corrente come variabile di contesto http:

<?php

declare(strict_types=1);

namespace Devamitbera\Module\Plugin\Framework\App\Action;

use Magento\Customer\Model\Context as CustomerContext;
use Magento\Framework\Exception\NoSuchEntityException;

class AbstractAction
{

    /**
     * @var \Magento\Customer\Api\CustomerRepositoryInterface
     */
    private $customerRepository; /** * @var \Magento\Customer\Model\Session */ private $customerSession;

    /**
     * @var \Magento\Framework\App\Http\Context
     */
    private $httpContext; public function __construct( \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\App\Http\Context $httpContext, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
    ) {
        $this->customerSession = $customerSession;
        $this->httpContext = $httpContext;
        $this->customerRepository = $customerRepository;
    }
    

    public function aroundDispatch(
        \Magento\Framework\App\ActionInterface $subject, callable $proceed,
        \Magento\Framework\App\RequestInterface $request ) { $customerId = $this->customerSession->getCustomerId(); $this->httpContext->setValue(
            'current_cust_id',
            $customerId, 0 ); return $proceed($request);
    }
} 

Dopo di ciò, inserisci, \Magento\Framework\App\Http\Contextsulla tua classe di blocco e ottieni questo valore di ID cliente per$this->httpContext->getValue('current_cust_id')

1 DhirenVasoya Sep 07 2020 at 13:23

Il tuo codice di blocco deve essere simile a questo:

public function getCustomerId()
{
     if($this->_customerSession->isLoggedIn()): return $this->_customerSession->getCustomer()->getId();                        
     endif;
}

E in phtml devi chiamare in questo modo:

<?php $customerId = $block->getCustomerId(); ?>
MohitPatel Sep 05 2020 at 19:01

Il tuo codice è perfetto Suppongo che la chiamata al file di blocco nel tuo .xmlfile e nel file di chiamata del file xml .phtmlesegua sotto tutti i comandi come: -

remove your var/cache
remove your var/view_preprocessed
php bin/magento setup:di:compile
php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c
php bin/magento c:f

Dopo aver controllato l'output e ancora una volta non mostrare l'output, controlla il tuo errore di registro condividi con me.

THANKS.

RiteshSantra Sep 05 2020 at 21:46

In Block file è necessario modificare il codice come di seguito

A partire dal:

<?php
$customerId = $customer->getCustomerId();
?>

Per:

<?php
$customerId = $block->getCustomerId();
?>
WaqarAli Sep 07 2020 at 17:19

Se il cliente ha effettuato l'accesso, non puoi accedere a Dalla sessione Prova in questo modo

public function __construct(
    \Magento\Framework\App\Http\Context $customerContext, \Magento\Customer\Model\SessionFactory $customer
{
    $this->customer = $customer;
    $this->customerContext = $customerContext;
}

public function getCustomerID()
{
    $customerLoggedIn= $this->customerContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
    if($customerLoggedIn){ $customerId = $this->customer->create()->getCustomer()->getId(); return $customerId;
    }
}
Msquare Sep 07 2020 at 16:45

Usalo nel tuo file di layout dove aggiungi il tuo blocco.

cacheable = "false"

        <block class="VendoreName\ModuleName\Block\BlockName"
               name="block_index_edit"
               template="VendoreName_ModuleName::edit.phtml"
               cacheable="false" />

Aggiornare

Il tuo file controller

<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;

class Customer extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory; public function __construct( Context $context,
        PageFactory $resultPageFactory ) { $this->resultPageFactory = $resultPageFactory; parent::__construct($context);
    }
    public function execute()
    {
        return $this->resultPageFactory->create(); $this->_view->loadLayout(); 
        $this->_view->renderLayout(); 
    }
} 

Il tuo file di blocco

<?php

namespace VendoreName\ModuleName\Block;

use Magento\Framework\View\Element\Template;

class Rfq extends Template
{
    protected $request;
    protected $sessionFactory; public function __construct( Template\Context $context,
        \Magento\Framework\App\Request\Http $request, \Magento\Customer\Model\SessionFactory $sessionFactory,
        array $data = [] ) { parent::__construct($context, $data); $this->sessionFactory = $sessionFactory; $this->request = $request; } public function getCustomerId() { // get customer id here $customerSession = $this->sessionFactory->create(); return $customerSession->getCustomer()->getId();
    }

}

Il tuo file phtml

<?php
$customerId = $block->getCustomerId();
echo "Customer ID is ".$customerId;
?>

Spero che questo ti aiuta.