0

I'm trying to get the User ID from Shipping Profile in Drupal Commerce using the following code, but eventually, $entity->getOwnerId() is returning me NULL in any case, if it's an authenticated user or admin it's giving me 0 as the UID.

function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'profile') {
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($entity->getOwnerId());
    }
}

2 Answers 2

2

Shipping and billing profiles don't have a user ID, they are always anonymous because they belong to the parent entity (order/shipment), not the user.

Only address book profiles have user IDs.

0
0

Thanks for the heads-up @bojanz. Considering your response, I've found 2 possible solutions:

function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'profile') {
        $entity->setData('copy_to_address_book', TRUE);
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($entity->getOwnerId());
    }
}

More reasonable one:

function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'commerce_order') {
        $uid = $entity->get('uid')->target_id;
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($uid);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.