public function WishlistProvider::createWishlist in Commerce Wishlist 8.3
Creates a wishlist entity for the given user.
Parameters
string $wishlist_type: The wishlist type ID.
\Drupal\Core\Session\AccountInterface $account: The user. If empty, the current user is assumed.
string $name: The wishlist name. Defaults to t('Wishlist').
Return value
\Drupal\commerce_wishlist\Entity\WishlistInterface The created wishlist entity.
Throws
\Drupal\commerce_wishlist\Exception\DuplicateWishlistException When a wishlist with the given criteria already exists.
Overrides WishlistProviderInterface::createWishlist
File
- src/
WishlistProvider.php, line 88
Class
- WishlistProvider
- Default implementation of the wishlist provider.
Namespace
Drupal\commerce_wishlistCode
public function createWishlist($wishlist_type, AccountInterface $account = NULL, $name = NULL) {
$account = $account ?: $this->currentUser;
$uid = $account
->id();
$allow_multiple = $this->configFactory
->get('commerce_wishlist.settings')
->get('allow_multiple');
if (empty($allow_multiple) && $this
->getWishlistId($wishlist_type, $account)) {
// Don't allow multiple wishlist entities matching the same criteria.
throw new DuplicateWishlistException("A wishlist for type '{$wishlist_type}' and account '{$uid}' already exists.");
}
// Create the new wishlist entity.
$wishlist = $this->wishlistStorage
->create([
'type' => $wishlist_type,
'uid' => $uid,
'name' => $name ?: $this
->t('Wishlist'),
// @todo By now, we only support one wishlist per user, so we automatically set it as the default one. In the long run we may need to distinct here.
'is_default' => TRUE,
]);
$wishlist
->save();
// Store the new wishlist id in the anonymous user's session so that it can
// be retrieved on the next page load.
if ($account
->isAnonymous()) {
$this->wishlistSession
->addWishlistId($wishlist
->id());
}
// Wishlist data has already been loaded, add the new wishlist to the list.
if (isset($this->wishlistData[$uid])) {
$this->wishlistData[$uid][$wishlist
->id()] = [
'type' => $wishlist_type,
];
}
return $wishlist;
}