When a new product is added in Magento catalog, it should get added to the wishlist of the customer and an order should be automatically created for it. I am using the following code. Can anyone help me with this?
<?php
namespace Wishorder\Asorder\Block;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\View\Element\Template\Context;
use \Wishorder\Asorder\Helper\Data;
class Cwish extends \Magento\Framework\View\Element\Template
{
protected $_productFactory;
protected $_wishlistRepository;
protected $_customerFactory;
protected $_helper;
public function __construct(
Context $context,
\Magento\Wishlist\Model\WishlistFactory $WishlistFactory,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Custom\Wlist\Helper\Data $helper,
array $data = []
) {
$this->_wishlistFactory= $WishlistFactory;
$this->_productFactory = $productFactory;
$this->_customerFactory = $customerFactory;
$this->_helper = $helper;
parent::__construct($context, $data);
}
public function getHelloWorldTxt(){
return 'Hello world!';
}
public function getProductCollection()
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$collection = $this->_customerFactory->create()->getCollection();
foreach ($collection as $cust)
{
$Email=$cust->getEmail();
echo "Email : ".$Email.'<br/>';
$Fname=$cust->getFirstname();
$Lname=$cust->getLastname();
echo "First Name : ".$Fname.'<br/>';
echo "Last Name : ".$Lname.'<br/>';
$CustomerModel->loadByEmail($Email);
$userId = $CustomerModel->getId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$wishlist = $objectManager->get('\Magento\Wishlist\Model\Wishlist');
$wishlist_collection = $wishlist->loadByCustomerId($userId, true)->getItemCollection();
echo "Last Name : ".$userId.'<br/>';
print_r($wishlist_collection); die;
foreach ($wishlist_collection as $wlist)
{
$orderData=[
'currency_id' => 'USD',
'email' => $Email, //buyer email id
'shipping_address' =>[
'firstname' => $Fname, //address Details
'lastname' => $Lname,
'street' => 'xxxxx',
'city' => 'xxxxx',
'country_id' => 'IN',
'region' => 'xxx',
'postcode' => '43244',
'telephone' => '52332',
'fax' => '32423',
'save_in_address_book' => 1],
'items'=> ['product_id'=>$wlist->getProductId(),'qty'=>1]
];
return $this->_helper->createOrder($orderData);
}
}
}
}