Example #1
0
 /**
  * Adds new product to wishlist.
  * Returns new item or string on error.
  *
  * @param int|\Magento\Catalog\Model\Product $product
  * @param \Magento\Framework\Object|array|string|null $buyRequest
  * @param bool $forciblySetQty
  * @return Item|string
  */
 public function addNewItem($product, $buyRequest = null, $forciblySetQty = false)
 {
     /*
      * Always load product, to ensure:
      * a) we have new instance and do not interfere with other products in wishlist
      * b) product has full set of attributes
      */
     if ($product instanceof \Magento\Catalog\Model\Product) {
         $productId = $product->getId();
         // Maybe force some store by wishlist internal properties
         $storeId = $product->hasWishlistStoreId() ? $product->getWishlistStoreId() : $product->getStoreId();
     } else {
         $productId = (int) $product;
         if (isset($buyRequest) && $buyRequest->getStoreId()) {
             $storeId = $buyRequest->getStoreId();
         } else {
             $storeId = $this->_storeManager->getStore()->getId();
         }
     }
     /* @var $product \Magento\Catalog\Model\Product */
     $product = $this->_productFactory->create();
     $product->setStoreId($storeId);
     $product->load($productId);
     if ($buyRequest instanceof \Magento\Framework\Object) {
         $_buyRequest = $buyRequest;
     } elseif (is_string($buyRequest)) {
         $_buyRequest = new \Magento\Framework\Object(unserialize($buyRequest));
     } elseif (is_array($buyRequest)) {
         $_buyRequest = new \Magento\Framework\Object($buyRequest);
     } else {
         $_buyRequest = new \Magento\Framework\Object();
     }
     $cartCandidates = $product->getTypeInstance()->processConfiguration($_buyRequest, $product);
     /**
      * Error message
      */
     if (is_string($cartCandidates)) {
         return $cartCandidates;
     }
     /**
      * If prepare process return one object
      */
     if (!is_array($cartCandidates)) {
         $cartCandidates = array($cartCandidates);
     }
     $errors = array();
     $items = array();
     foreach ($cartCandidates as $candidate) {
         if ($candidate->getParentProductId()) {
             continue;
         }
         $candidate->setWishlistStoreId($storeId);
         $qty = $candidate->getQty() ? $candidate->getQty() : 1;
         // No null values as qty. Convert zero to 1.
         $item = $this->_addCatalogProduct($candidate, $qty, $forciblySetQty);
         $items[] = $item;
         // Collect errors instead of throwing first one
         if ($item->getHasError()) {
             $errors[] = $item->getMessage();
         }
     }
     $this->_eventManager->dispatch('wishlist_product_add_after', array('items' => $items));
     return $item;
 }