Thursday, September 8, 2016

customer discount apply on cart page using observer in magento


(1) app/code/local/Kodematix/Testing/etc/config.xml



<?xml version="1.0"?>

<config>
    <modules>
        <Kodematix_Testing>
            <version>0.1.0</version>
        </Kodematix_Testing>
    </modules>

   <frontend>
                  <events>
                     <checkout_cart_product_add_after>
                       <observers>
                           <testing>
                                 <class>testing/observer</class>
                                 <method>cartProductAddAfter</method>
                          </testing>
                     </observers>
                  </checkout_cart_product_add_after>
            </events>
   </frontend>

</config>



(2) app/code/local/Kodematix/Testing/Model/Observer.php

class Kodematix_Testing_Model_Observer{

    public function cartProductAddAfter($observer)
    {
       
        if(Mage::getSingleton('customer/session')->isLoggedIn()){


        $customer = Mage::getSingleton('customer/session')->getCustomer();
       
        $disprice = $customer['discount'];
     
     
    $product = $observer->getEvent()->getProduct();
    $currentItem = $observer->getEvent()->getQuoteItem();
        $event = $observer->getEvent();
   $quote_item = $event->getQuoteItem();

 
   $price = $product->getPrice();


    // Discounted off
        $percentDiscount = $disprice/100;

   $new_price = $price - ($price * $percentDiscount);


   $quote_item->setOriginalCustomPrice($new_price);
   $quote_item->save();


   Mage::getSingleton('core/session')->addSuccess('Your '.$disprice.'% Apply this Product');




 }

    }
}


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>



Friday, December 4, 2015

Out of Stock Products Display in Custom list.phtml

Step 1:

Create New CMS Page in Below Content Add.

{{block type="catalog/product_outofstock" template="catalog/product/list.phtml" column_count="4"}}


Step 2 :  

Create New PHP File Below Path.

Example :-  app/code/local/Mage/Catalog/Block/Product/Outofstock.php


Step 3 :

OutofStock.php in Add Below Function.

protected function _getProductCollection()
   {

         $products = Mage::getModel('catalog/product')
                ->getCollection()
                ->joinField(
                        'is_in_stock',
                        'cataloginventory/stock_item',
                        'is_in_stock',
                        'product_id=entity_id',
                        '{{table}}.stock_id=1',
                        'left'
                )
->addAttributeToSelect('*')
->addAttributeToSort('entity_id', 'desc')
                ->addAttributeToFilter('is_in_stock', array('eq' => 0));

        return $products;
   } 

Saturday, September 19, 2015

Product price change programatically after add to cart in magento

Step 1: Create an Attribute for the products
Example :-  Change Price Set its type yes/no for the product 


Step 2: Open File

code/core/mage/checkout/model/cart.php


Step 3: Goto on this function

 public function save()
    {
      ........
      ........
     }
Step 4: Copy and Paste below code,
public function save()
    {
        Mage::dispatchEvent('checkout_cart_save_before', array('cart'=>$this));

        $this->getQuote()->getBillingAddress();
        $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
        $this->getQuote()->collectTotals();
               
        foreach($this->getQuote()->getAllItems() as $item) {             
          $productId = $item->getProductId();
          $product = Mage::getModel('catalog/product')->load($productId);
          if($product->getAttributeText('change_price') == 'Yes')
         {
                 $price = 5;
                 $item->setCustomPrice($price);
                 $item->setOriginalCustomPrice($price);
          }
        }  
        $this->getQuote()->save(); 
        $this->getCheckoutSession()->setQuoteId($this->getQuote()->getId());
        
        /**
         * Cart save usually called after changes with cart items.
         */
        Mage::dispatchEvent('checkout_cart_save_after', array('cart'=>$this));
        return $this;
      }
Step 5: Now, Insert Product  Admin side  and set Attribute Change Price value yes for that product
Step 6: Add that product  to cart you can see that, product  price will change to $5.

 Enjoy!!!!!

Add Increase and Decrease Quantity Buttons in Magento


open addtocart.phtml file replace this code

Path :- app\design\frontend\default\your theme\template\catalog\product\view\addtocart.phtml


<?php $_product = $this->getProduct(); ?>
<?php $buttonTitle = Mage::helper('core')->quoteEscape($this->__('Add to Cart')); ?>
<?php if($_product->isSaleable()): ?>
    <div class="add-to-cart">
        <?php if(!$_product->isGrouped()): ?>
        <div class="qty-wrapper">
            <label for="qty"><?php echo $this->__('Qty:') ?></label>
            <input type="text" pattern="\d*" name="qty" id="qty" maxlength="12" value="<?php echo max($this->getProductDefaultQty() * 1, 1) ?>" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Qty')) ?>" class="input-text qty" / 
           <button class="button-arrow button-up" type="button">Increase</button>
           <button class="button-arrow button-down" type="button">Decrease</button>
        </div>
        <?php endif; ?>
        <div class="add-to-cart-buttons">
            <button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>
            <?php echo $this->getChildHtml('', true, true) ?>
        </div>
    </div>
<?php endif; ?>

<script type="text/javascript">

        //&lt;![CDATA[

        jQuery(function($) {

            $('.add-to-cart .button-up').click(function() {

                $qty = $(this).parent().find('.qty');

                qty = parseInt($qty.val()) + 1;

                $qty.val(qty);

            });

            $('.add-to-cart .button-down').click(function() {

                $qty = $(this).parent().find('.qty');

                qty = parseInt($qty.val()) - 1;

                if (qty < 0)

                    qty = 0;

                $qty.val(qty);

            });

        });

        //]]&gt;


        </script>