Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Fromcart.php
Go to the documentation of this file.
1 <?php
8 
9 use Magento\Checkout\Helper\Cart as CartHelper;
19 use Magento\Wishlist\Helper\Data as WishlistHelper;
20 
25 {
29  protected $wishlistProvider;
30 
34  protected $wishlistHelper;
35 
39  protected $cart;
40 
44  protected $cartHelper;
45 
49  protected $escaper;
50 
54  protected $formKeyValidator;
55 
65  public function __construct(
66  Action\Context $context,
68  WishlistHelper $wishlistHelper,
70  CartHelper $cartHelper,
73  ) {
74  $this->wishlistProvider = $wishlistProvider;
75  $this->wishlistHelper = $wishlistHelper;
76  $this->cart = $cart;
77  $this->cartHelper = $cartHelper;
78  $this->escaper = $escaper;
79  $this->formKeyValidator = $formKeyValidator;
80  parent::__construct($context);
81  }
82 
90  public function execute()
91  {
93  $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
94  if (!$this->formKeyValidator->validate($this->getRequest())) {
95  return $resultRedirect->setPath('*/*/');
96  }
97 
98  $wishlist = $this->wishlistProvider->getWishlist();
99  if (!$wishlist) {
100  throw new NotFoundException(__('Page not found.'));
101  }
102 
103  try {
104  $itemId = (int)$this->getRequest()->getParam('item');
105  $item = $this->cart->getQuote()->getItemById($itemId);
106  if (!$item) {
107  throw new LocalizedException(
108  __("The cart item doesn't exist.")
109  );
110  }
111 
112  $productId = $item->getProductId();
113  $buyRequest = $item->getBuyRequest();
114  $wishlist->addNewItem($productId, $buyRequest);
115 
116  $this->cart->getQuote()->removeItem($itemId);
117  $this->cart->save();
118 
119  $this->wishlistHelper->calculate();
120  $wishlist->save();
121 
122  $this->messageManager->addSuccessMessage(__(
123  "%1 has been moved to your wish list.",
124  $this->escaper->escapeHtml($item->getProduct()->getName())
125  ));
126  } catch (LocalizedException $e) {
127  $this->messageManager->addErrorMessage($e->getMessage());
128  } catch (\Exception $e) {
129  $this->messageManager->addExceptionMessage($e, __('We can\'t move the item to the wish list.'));
130  }
131  return $resultRedirect->setUrl($this->cartHelper->getCartUrl());
132  }
133 }
__()
Definition: __.php:13
$wishlist
Definition: wishlist.php:10
foreach($product->getExtensionAttributes() ->getBundleProductOptions() as $option) $buyRequest
__construct(Action\Context $context, WishlistProviderInterface $wishlistProvider, WishlistHelper $wishlistHelper, CheckoutCart $cart, CartHelper $cartHelper, Escaper $escaper, Validator $formKeyValidator)
Definition: Fromcart.php:65