Question

I want to add "Notify me when this product is in stock" on product listing page in magento 2 . by default if product is out of stock this comes in the product detail page. but i want in the product listing page. I am using magento 2.2.5

No correct solution

OTHER TIPS

Update Code:

For this requirement, you cannot use existing stock notify block Magento\ProductAlert\Block\Product\View\Stock ,

You have to create a custom block which will extend ``Magento\ProductAlert\Block\Product\Viewthen using below codelist.phtml`.

You can use shown "Notify me when this product is in stock" section

Block Code:

<?php

namespace StackExchanges\OnlyMagento\Block;

class StockNotify extends \Magento\ProductAlert\Block\Product\View {


    protected function getProduct()
    {
        $product = $this->getProuctinfo();
        if ($product!== null && $product->getId()) {
            return $product;
        }
        return false;
    }
    public function setTemplate($template)
    {
        if (!$this->_helper->isStockAlertAllowed() || !$this->getProduct() || $this->getProduct()->isAvailable()) {
            $template = '';
        } else {
            $this->setSignupUrl($this->getSaveUrl('stock'));
        }
        return parent::setTemplate($template);
    }
     /**
     * @param string $type
     * @return string
     */
    public function getSaveUrl($type)
    {

        return $this->getUrl(
            'productalert/add/' . $type,
            [
                'product_id' => $this->getProduct()->getId(),
                \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED =>$this->_helper->getEncodedUrl()
            ]
        );
    }     
}

After that add below code add list.phtml after <?= $productImage->toHtml() ?>

            <?php 
            $blockStockNofity = $this->getLayout()
                    ->createBlock(
                    "StackExchanges\OnlyMagento\Block\StockNotify",
                    "list.page.stocknotify.".$_product->getId(),
                        [
                            'data' => [
                            'prouctinfo' => $_product
                            ]
                        ]
                    )->setData('area', 'frontend');
            ?>
            <?= /* @escapeNotVerified */ $blockStockNofity->setHtmlClass('stock')
                    ->setSignupLabel(__('Notify me when this product is in stock'))
                    ->setTemplate('Magento_ProductAlert::product/view.phtml')
                    ->toHtml();?>

Note that here, i have to send product model data as a parameter of the block 'prouctinfo' => $_product.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top