You are here

public function Wishlist::preSave in Commerce Wishlist 8.3

Acts on an entity before the presave hook is invoked.

Used before the entity is saved and before invoking the presave hook. Note that in case of translatable content entities this callback is only fired on their current translation. It is up to the developer to iterate over all translations if needed. This is different from its counterpart in the Field API, FieldItemListInterface::preSave(), which is fired on all field translations automatically. @todo Adjust existing implementations and the documentation according to https://www.drupal.org/node/2577609 to have a consistent API.

Parameters

\Drupal\Core\Entity\EntityStorageInterface $storage: The entity storage object.

Throws

\Exception When there is a problem that should prevent saving the entity.

Overrides ContentEntityBase::preSave

See also

\Drupal\Core\Field\FieldItemListInterface::preSave()

File

src/Entity/Wishlist.php, line 315

Class

Wishlist
Defines the wishlist entity class.

Namespace

Drupal\commerce_wishlist\Entity

Code

public function preSave(EntityStorageInterface $storage) {

  /** @var \Drupal\commerce_wishlist\WishlistStorageInterface $storage */
  parent::preSave($storage);
  if ($this
    ->get('code')
    ->isEmpty()) {

    /** @var \Drupal\commerce_wishlist\WishlistStorageInterface $storage */
    $storage = $this
      ->entityTypeManager()
      ->getStorage('commerce_wishlist');
    $random = new Random();
    $code = $random
      ->word(13);

    // Ensure code uniqueness. Collisions are rare, but possible.
    while ($storage
      ->loadByCode($code)) {
      $code = $random
        ->word(13);
    }
    $this
      ->setCode($random
      ->word(13));
  }

  // Mark the wishlist as default if there's no other default.
  if ($this
    ->getOwnerId() && !$this
    ->isDefault()) {
    $wishlist = $storage
      ->loadDefaultByUser($this
      ->getOwner(), $this
      ->bundle());
    if (!$wishlist || !$wishlist
      ->isDefault()) {
      $this
        ->setDefault(TRUE);
    }
  }
}