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********


Saturday, June 18, 2016

Magento 2 Getting product Image url

$imagehelper = $objectManager->create('Magento\Catalog\Helper\Image');
$image = $imagehelper->init($_product,'category_page_list')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(400)->getUrl();

<img src="<?php echo $image; ?>">

Change inventory on select configurable options

=> Please follow the below steps for the inventory options changes.

Step 1 :   \app\design\frontend\rwd\default\template\catalog\product\view\type\options\configurable.phtml file in replace below code

<?php
$_product    = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
$_jsonConfig = $this->getJsonConfig();
$_renderers = $this->getChild('attr_renderers')->getSortedChildren();
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <?php
        $_rendered = false;
        foreach ($_renderers as $_rendererName):
            $_renderer = $this->getChild('attr_renderers')->getChild($_rendererName);
            if (method_exists($_renderer, 'shouldRender') && $_renderer->shouldRender($_attribute, $_jsonConfig)):
                $_renderer->setProduct($_product);
                $_renderer->setAttributeObj($_attribute);
                echo $_renderer->toHtml();
                $_rendered = true;
                break;
            endif;
        endforeach;

        if (!$_rendered):
        ?>
        <dt><label class="required"><em>*</em><?php echo $_attribute->getLabel() ?></label></dt>
        <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
            <div class="input-box">
                <select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" onchange = "spConfig.getIdOfSelectedProduct()" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select">
                    <option><?php echo $this->__('Choose an Option...') ?></option>
                  </select>
              </div>
        </dd>
        <?php endif; ?>
    <?php endforeach; ?>
    </dl>
 
<script type="text/javascript">
        var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);

spConfig.getIdOfSelectedProduct = function (mId) {
var sId = "myid"+mId;
var mId = "attribute"+mId;
var s = jQuery("select#"+mId+" option:selected").text();

if (s.indexOf('+$') >= 0)
{
s = s.substring(0, s.indexOf('+$'));
}
else if (s.indexOf('-$') >= 0)
{
s = s.substring(0, s.indexOf('-$'));
}
else
{
s = s;
}

jQuery("#"+sId).html(s);

//this.settings[i].attributeId =  'attribute'+attributeId;

var existingProducts = new Object();
//console.log(this);
    for (var i = this.settings.length - 1; i >= 0; i--) {
        var selected = this.settings[i].options[this.settings[i].selectedIndex];

if (selected.config) {
console.log("SpConfig : "+selected.config.products.length);
            for (var iproducts = 0; iproducts < selected.config.products.length; iproducts++) {
                var usedAsKey = selected.config.products[iproducts] + "";
//console.log("UsedasKey : "+usedAsKey);
                if (existingProducts[usedAsKey] == undefined) {
                    existingProducts[usedAsKey] = 1;
                } else {
                    existingProducts[usedAsKey] = existingProducts[usedAsKey] + 1;
                }
            }
        }
    }
    for (var keyValue in existingProducts) {
        for (var keyValueInner in existingProducts) {
            if (Number(existingProducts[keyValueInner]) < Number(existingProducts[keyValue])) {
                delete existingProducts[keyValueInner];
            }
        }
    }
    var sizeOfExistingProducts = 0;
    var currentSimpleProductId = "";

    for (var keyValue in existingProducts) {
currentSimpleProductId = keyValue;
        sizeOfExistingProducts = sizeOfExistingProducts + 1
    }
console.log(sizeOfExistingProducts);

    if (sizeOfExistingProducts == 1 ) {
currentSimpleProductId;
jQuery.ajax({
type: "POST",
url: "<?php echo $this->getBaseUrl().'sku.php'?>",
data:"id="+currentSimpleProductId,
success: function(msg)
{
jQuery("#product-sku").html(msg);

//jQuery("#product-sku").show();

}
});
    }
}

    </script>

    <?php echo $this->getChildHtml('after') ?>
<?php endif;?>

Step 2 : Create A File sku.php in magento root folder 

<?php
include_once 'app/Mage.php';
Mage::init();

$id = $_POST['id'];
$obj = Mage::getModel('catalog/product')->load($id);
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($obj);
echo $stock->getQty();
?>

Step 3 :  app\design\frontend\rwd\default\template\catalog\product\view.phtml file in add div 

<div id ="product-sku"> </div>