Magento 2: How to get customer id
سؤال
Can any one tell me how can I get the customer id whose order is being created by admin in admin panel, in file /vendor/magento/module-sales/view/adminhtml/templates/order/create/form/account.phtml
المحلول
$block->getCustomerId()
This should do it, let me know if you need any further assistance !
UPDATE:
In order to get the customer and retrive atributes you can do the following:
SOLUTION USING OBJECT MANAGER
$customerId = $block->getCustomerId();
if(isset($customerId))
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);
//here get the attributtes you need from $customer, for example
$firstname = $customer->getData('firstname');
}
SOLUTION USING CUSTOMER REPOSITORY:
In your di.xml (Vendor\Module\etc\di.xml)
<preference for="Magento\Sales\Block\Adminhtml\Order\Create\Form\Account" type="Vendor\Module\Block\Adminhtml\Order\Create\Account"/>
Create the following file in (Vendor\Module\Block\Adminhtml\Order\Create)
<?php
namespace Vendor\Module\Block\Adminhtml\Order\Create;
class Account extends \Magento\Sales\Block\Adminhtml\Order\Create\Form\Account
{
public function getCustomer( $customerId)
{
try {
return $this->customerRepository->getById($customerId);
} catch (\Exception $e) {
/** If customer does not exist do nothing. */
}
}
}
?>
In your account.phtml:
$customerId = $block->getCustomerId();
if(isset($customerId))
{
$customer = $block->getCustomer( $customerId);
$firstname = $customer->getFirstName();
}
?>
نصائح أخرى
Only solution for this doing something with remote ip . If it matches with your admin ip address than fetch the data.
if(!empty($order->getRemoteIp()) {
check your ip address here
}
You can get Customer ID in /vendor/magento/module-sales/view/adminhtml/templates/order/create/form/account.phtml
using the below code:
<p>Customer Id: <?= $this->getCustomerId() ?> </p>
<p>Customer Email: <?= $this->getQuote()->getCustomerEmail() ?></p>
Check the block $block \Magento\Sales\Block\Adminhtml\Order\Create\Form\Account
as it gets in the same way.
Hope this helps!