Magento 2 – Programmatically Add Product to Wishlist

magento2wishlist

I have added one login popup on product details page and want to add product to wishlist after customer is logged in. But getting error when trying with wishlist code. I am trying this solution but something is not correct in my code. Here is my code

<?php

namespace Test\Customcatalog\Controller\Account;

use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Controller\ResultFactory;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {
    protected $_wishlistRepository;
    protected $_productRepository;

    public function __construct(
            \Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
            \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ){
        $this->_wishlistRepository= $wishlistRepository;
        $this->_productRepository = $productRepository;
    }

    public function execute() {
        if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;
        }

        $postData = $this->getRequest()->getPost();

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                    $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                    $this->session->setCustomerDataAsLoggedIn($customer);
                    $this->session->regenerateId();
                } catch (EmailNotConfirmedException $e) {
                    $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
                    $message = __(
                            'This account is not confirmed.' .
                            ' <a href="%1">Click here</a> to resend confirmation email.', $value
                    );
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (AuthenticationException $e) {
                    $message = __('Invalid login or password.');
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (\Exception $e) {
                    $this->messageManager->addError(__('Invalid login or password.'));
                }
            } else {
                $this->messageManager->addError(__('A login and a password are required.'));
            }
        }



        if($postData['referProductID']){
            $productId = $postData['referProductID'];
            try {
                $product = $this->_productRepository->getById($productId);
            } catch (NoSuchEntityException $e) {
                $product = null;
            }

            $customerId = $customer->getId();
            if($customerId){
                $wishlist = $this->_wishlistRepository->create()->loadByCustomerId($customerId, true);
                $wishlist->addNewItem($product);
                $wishlist->save();
            }
        }

        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }

}

The error message is:

Fatal error: Uncaught TypeError: Argument 1 passed to Test\Customcatalog\Controller\Account\LoginPost::__construct() must be an instance of Magento\Wishlist\Model\WishlistFactory, instance of Magento\Framework\App\Action\Context given, called in /home/public_html/demo/var/generation/Test/Customcatalog/Controller/Account/LoginPost/Interceptor.php on line 14 and defined in /home/public_html/demo/app/code/Test/Customcatalog/Controller/Account/LoginPost.php:24 Stack trace: #0 /home/public_html/demo/var/generation/Test/Customcatalog/Controller/Account/LoginPost/Interceptor.php(14): Test\Customcatalog\Controller\Account\LoginPost->__construct(Object(Magento\Framework\App\Action\Context), Object(Magento\Customer\Model\Session\Interceptor), Object(Magento\Customer\Model\AccountManagement\Interceptor), Object(Magento\Customer\Model\Url), Object(Magento\Framework\Data\Form\FormKey\Validator), Object(Magento\Customer\Model\Account\Redirect)) #1 /home/public_html/demo/vendor/magento/framework/ in /home/public_html/demo/app/code/Test/Customcatalog/Controller/Account/LoginPost.php on line 24

I hope someone help me to fix this.
Thanks,

Best Answer

The error you are getting because you are overriding Account/LoginPost controller but not using its default repositories, Update your __construct function like,

public function __construct(
    Context $context,
    Session $customerSession,
    AccountManagementInterface $customerAccountManagement,
    CustomerUrl $customerHelperData,
    Validator $formKeyValidator,
    AccountRedirect $accountRedirect,
    \Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->session = $customerSession;
    $this->customerAccountManagement = $customerAccountManagement;
    $this->customerUrl = $customerHelperData;
    $this->formKeyValidator = $formKeyValidator;
    $this->accountRedirect = $accountRedirect;
    $this->_wishlistRepository= $wishlistRepository;
    $this->_productRepository = $productRepository;
    parent::__construct($context,$customerSession,$customerAccountManagement,$customerHelperData,$formKeyValidator,$accountRedirect);
}

Remove var/generation and check.

Related Topic