Monday, June 27, 2016

Magento 2 get new products collection on homepage

(1) Create A Block File in app/code/Companyname/NewProduct/Block/NewProduct.php

<?php

namespace Companyname\NewProduct\Block;

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\Entity\Collection\AbstractCollection;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Customer\Model\Context as CustomerContext;



class NewProduct extends \Magento\Framework\View\Element\Template
{
    protected $urlHelper;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,

        \Magento\Directory\Model\Currency $currency,      
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,  

        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Framework\Data\Helper\PostHelper $postDataHelper,
        \Magento\Catalog\Model\Layer\Resolver $layerResolver,
        CategoryRepositoryInterface $categoryRepository,  

        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        \Magento\Framework\Data\Form\FormKey $formKey,


        array $data = []
    )
    {  
        $this->_categoryFactory = $categoryFactory;
        $this->_currency = $currency;
        $this->_catalogLayer = $layerResolver->get();
        $this->_postDataHelper = $postDataHelper;
        $this->categoryRepository = $categoryRepository;
        $this->urlHelper = $urlHelper;
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->formKey = $formKey;
        parent::__construct($context, $data);
    }
   
 


    public function getAddToCartPostParams(\Magento\Catalog\Model\Product $_product)
    {
        $url = $this->getAddToCartUrl($_product);
        return [
            'action' => $url,
            'data' => [
                'product' => $_product->getEntityId(),
                \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED =>
                    $this->urlHelper->getEncodedUrl($url),
            ]
        ];
    }

    public function getNewProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(4);
        $collection->setOrder('entity_id','DESC');
        return $collection;
       
    }
    public function getFormKey()
    {
        return $this->formKey->getFormKey();
    }


}

?>

(2) Create module.xml file in app/code/Companyname/NewProduct/etc/module.xml


<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Companyname_NewProduct" setup_version="2.0.2">
    </module>
</config>


(3) Create registration.php in app/code/Companyname/NewProduct/registration.php


<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Companyname_NewProduct',
    __DIR__
);


(4) create a newproduct.phtml file in  vender/magento/module-theme/view/frontend/templates/html/newproduct.phtml


<?php

$block = \Magento\Framework\App\ObjectManager::getInstance()->get('Kodematix\NewProduct\Block\NewProduct');
use Magento\Framework\App\Action\Action;
use Magento\Store\Model\StoreManagerInterface;


$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface');
$currentStore = $storeManager->getStore();


$productCollection = $block->getNewProductCollection();
$_helper = $this->helper('Magento\Catalog\Helper\Output');



?>

<div class="category-home-content">
<div class="category-home-display-top">
<div class="custom-title">
<span></span>
<h2><?php echo __('New Product'); ?></h2>
</div>
</div>


<?php if (!$productCollection->count()): ?>
    <div class="message info empty"><div><?php /* @escapeNotVerified */ echo __('We can\'t find products matching the selection.') ?></div></div>
<?php else: ?>
    <?php echo $block->getToolbarHtml() ?>
    <?php echo $block->getAdditionalHtml() ?>
       
        <?php
        $viewMode = 'grid';
        $image = 'category_page_grid';
        $showDescription = false;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
        $pos = $block->getPositioned();
       
        ?>
       
         <div class="products wrapper <?php /* @escapeNotVerified */ echo $viewMode; ?> products-<?php /* @escapeNotVerified */ echo $viewMode; ?>">
        <?php $iterator = 1; ?>
        <ol class="products list items product-items">
            <?php /** @var $_product \Magento\Catalog\Model\Product */ ?>
            <?php foreach ($productCollection as $_product): ?>
                <?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<li class="item product product-item">' : '</li><li class="item product product-item">' ?>
                <div class="product-item-info" data-container="product-grid">
                    <?php
                    $productImage = $block->getImage($_product, $image);
                    if ($pos != null) {
                        $position = ' style="left:' . $productImage->getWidth() . 'px;'
                            . 'top:' . $productImage->getHeight() . 'px;"';
                    }
                    ?>
                         <?php
            //$image = 'category_page_grid' or 'category_page_list';
            $_imagehelper = $this->helper('Magento\Catalog\Helper\Image');

            $productImage = $_imagehelper->init($_product, $image)->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(400)->getUrl();
                    ?>
<div class="product-grid-img-area">
                    <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
                        <img src="<?php echo $productImage; ?>" />
                    </a>
</div>
                   
                      <div class="product details product-item-details">
                        <?php
                            $_productNameStripped = $block->stripTags($_product->getName(), null, true);
                        ?>
                        <strong class="product name product-item-name">
                            <a class="product-item-link"
                               href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>">
                                <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getName(), 'name'); ?>
                            </a>
                        </strong>

                       

                        <?php echo $block->getReviewsSummaryHtml($_product, $templateType); ?>
<div class="product-price-cart">
<div class="final-price-box">
                     <strong><?php echo $block->getCurrencySymbol($_product).$_product->getFinalPrice($_product); ?>
<?php echo __('€'); ?>

</strong>
</div>
                        <?php echo $block->getProductDetailsHtml($_product); ?>

                        <div class="product-item">
                            <div class="product actions product-item-actions"<?php echo strpos($pos, $viewMode . '-actions') ? $position : ''; ?>>
                                <div class="actions-primary"<?php echo strpos($pos, $viewMode . '-primary') ? $position : ''; ?>>
                                    <?php if ($_product->isSaleable()): ?>
                                        <?php $postParams = $block->getAddToCartPostParams($_product); ?>

                <form data-role="tocart-form" action="<?php echo $baseUrl = $currentStore->getBaseUrl().'checkout/cart/add/uenc/product/'.$_product->getId();?>" method="post">
                <input type="hidden" name="product" value="<?php echo $postParams['data']['product']; ?>">
                                            <?php echo $block->getBlockHtml('formkey')?>
                           <button type="submit"
                                                    title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                                                    class="action tocart primary">
                                                <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <?php  if ($_product->getIsSalable()): ?>
                                            <div class="stock available"><span><?php echo __('In stock') ?></span></div>
                                        <?php else: ?>
                                            <div class="stock unavailable"><span><?php echo __('Out of stock') ?></span></div>
                                        <?php endif;  ?>
                                    <?php endif; ?>
                                </div>
                                 
                                <div data-role="add-to-links" class="actions-secondary"<?php echo strpos($pos, $viewMode . '-secondary') ? $position : ''; ?>>
                                    <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow()): ?>
                                        <a href="#"
                                           class="action towishlist"
                                           title="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                           aria-label="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                           data-post='<?php echo $block->getAddToWishlistParams($_product); ?>'
                                           data-action="add-to-wishlist"
                                           role="button">
                                            <span><?php echo __('Add to Wish List') ?></span>
                                        </a>
                                    <?php endif; ?>
                                    <?php
                                    $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');
                                    ?>
                                    <a href="#"
                                       class="action tocompare"
                                       title="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"
                                       aria-label="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"
                                       data-post='<?php  echo $compareHelper->getPostDataParams($_product); ?>'
                                       role="button">
                                        <span><?php echo __('Add to Compare') ?></span>
                                    </a>
                                </div>
                             

                            </div>
                            <?php if ($showDescription):?>
                                <div class="product description product-item-description">
                                    <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                                    <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" title="<?php /* @escapeNotVerified */ echo $_productNameStripped ?>"
                                       class="action more"><?php /* @escapeNotVerified */ echo __('Learn More') ?></a>
                                </div>
                            <?php endif; ?>
                        </div>
</div>
                    </div>
                   
                </div>
                <?php echo($iterator == count($productCollection)+1) ? '</li>' : '' ?>
            <?php endforeach; ?>
        </ol>
    </div>
        <?php echo $block->getToolbarHtml() ?>

        <script type="text/x-magento-init">
        {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {}
            }
        }
        </script>

<?php endif; ?>
</div>




****** New product on homepage display successfully********


5 comments:

  1. Thanks for sharing blog !
    Here i get information about where i use magento SMS gateway service.

    ReplyDelete
  2. Nice article use in this blog post...good information sharing for post....Magento 2

    ReplyDelete
  3. Now Msgclub Bulk sms provider allow you to start Sending SMS through Magento plugin.

    ReplyDelete
  4. Our goal is to go far beyond simple data entry service to provide a complete X-Cart product data management solution tailored to your business needs.

    ReplyDelete