Pregunta

In Magento guest checkot we must fill firstname and lastname, and i want to retrieve guest firstname and lastname from order, i tried to do it like this:

$name = $order->getCustomerName();

but when i print the $name it shows guest not the guest firstname or lastname

¿Fue útil?

Solución

To Get Guest Name from Order:

public function getGuestCustomerName(\Magento\Sales\Model\Order $order)
{
    return $order->getBillingAddress()->getFirstName();
}

To display Customer name or Guest name:

<?php echo $customeName = ($order->getCustomerFirstname()) ? $order->getCustomerFirstname() : $block->getGuestCustomerName($order); ?>

Otros consejos

When an order is placed as guest the customername is stored as guest. You can get Firtname and Lastname for guest from billing address

$billingAddress     = $order->getBillingAddress();
$name = $billingAddress->getFirstname() . ' ' . $billingAddress->getLastname();
/**
 * @return string
 */
public function getCustomerName()
{
    if ($this->getCustomerFirstname()) {
        $customerName = $this->getCustomerFirstname() . ' ' . $this->getCustomerLastname();
    } else {
        $customerName = (string)__('Guest');
    }
    return $customerName;
}

As you can see, if the first name is not set on order, which is the case of being a guest, then translation of 'Guest' is returned.

To achieve your goal you can get first/last name from a shipping or billing address

$shippingAddress = $order->getShippingAddress();
$fisrtName = $shippingAddress->getFirstname();
$lastName = $shippingAddress->getLastname();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top