The address book API: Working with anonymous users

Last updated on
9 May 2017

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Ubercart Addresses doesn't allow to save addresses for anonymous users. However, sometimes you need an address object for an user when that user has no user ID yet. For example, you want to ask an user for an address at registering. For these cases you can ask the address book class to create an unowned address book with an unowned address. Call the static method newAddress():

<?php
// Create an unonwed address
$address = UcAddressesAddressBook::newAddress();
?>

The address will come in an address book owned by user 0. When you are working with an unowned address, some restrictions apply:

  • It can not be saved to the database. Calling the method save() will result in an UcAddressesUnownedException.
  • You can't mark an unowned address as a default address. Because it's unknown to which user it's going to belong, it's uncertain if that user already has a default address.

When the time comes the user ID is known, for example when registering is done, you can set the owner of the address by calling the method setOwner() on the address object:

<?php
// Set the owner of the address
$address->setOwner($uid);
?>

You can only set the addresses' owner if it is still unowned. The API does not allow to *transfer* addresses from one address book to another.

If you want to know if you are working with an owned address object (or an owned address book object), you call the method isOwned(). This method will return TRUE or FALSE:

<?php
// Check if the address is owned
if ($address->isOwned()) {
  // (Perform actions...)
}

// Check if the address book is owned
if ($addressBook->isOwned()) {
  // (Perform actions...)
}
?>

If you just want to know who owns the address (or address book), call getUserId().

<?php
// Get the user ID from the user who owns this address
$uid = $address->getUserId();

// Get the user ID from the user who owns this address book
$uid = $addressBook->getUserId();
?>

Help improve this page

Page status: No known problems

You can: