Tuesday, April 24, 2012

Magento add category with images on homepage



if you would like to add category titles with images on the front page, just follow the steps:

place this snippet on your homepage cms page:

{{block type="core/template" name="homepage" template="catalog/category/homepagecategory.phtml"}}

then place this code in app/code/design/frontend/YOUR_PACKAGE/YOUR_TEMPLATE/catalog/category/homepagecategory.phtml

<?php
 $currcatId = 3;
 if($currcatId != NULL)
    {
  $collection = Mage::getModel('catalog/category')->getCategories($currcatId);
  $ctr = 0;
  foreach($collection as $subcat)
  {
      //limits the categories to be shown on home page to 6 categories
      if ($ctr < 6)
   if($subcat->getIsActive())
   {
       $category = Mage::getModel('catalog/category')->load($subcat->getEntityId());
       $ctr++;
       if (strtolower($category->getName()) == "overige lampen") 
       {
       }
    else
   {
?>

<div class="sub-category-container" style="margin-right:<?php if(($ctr % 2) == 0) {echo "0";} else {echo "8px";} ?>; margin-bottom:10px;" >
 <a href="<?php echo $this->getBaseUrl() . $category->getUrlKey() ?>" style="background:none; border:none;">
  <div>
     <?php if($_imgUrl = $category->getImageUrl()): ?>
   <img src="<?php echo $_imgUrl; ?>" border="0" />
     <?php else:?>
   <img src="<?php echo $this->getSkinUrl('images/lampen/placeholder.jpg') ?>" border="0" width="185px" height="185px" />
     <?php endif; ?>
  </div>
  <div>
   <a href="<?php echo $this->getBaseUrl() . $category->getUrlKey() ?>"><?php echo $category->getName(); ?></a>
  </div>
 </a>
</div>

<?php
     }
   }
  }
 }
?>

Magento 1.6 cannot login on admin

I have a sample Magento 1.6.2 installation wherein I test sample codes, install/test extension and also it acts as a quick reference whenever I'm not sure of anything on the admin area.
As you have guessed I tried loggin in one fine day and pooof! I can't login.. Tried almost anything (eg. clearing cache, session, locks ... using other web browser) but it still wont log me in..

Tried searching for a solution and thank God I found one on phpgenious..
It says that this is a cookie problem because Magento cannot create a cookie on your site, so here's the solution. (this solution worked for me..)

COPY app/code/core/Mage/Core/Model/Session/Abstract/Varien.php on app/code/local/Mage/Core/Model/Session/Abstract/Varien.php (so that it will not be overwritten when you upgrade)


        // session cookie params
        $cookieParams = array(
            'lifetime' => $cookie->getLifetime(),
            'path'     => $cookie->getPath()
            'domain'   => $cookie->getConfigDomain(),
            'secure'   => $cookie->isSecure(),
            'httponly' => $cookie->getHttponly()
        ); 

and replace it with:


        // session cookie params
        $cookieParams = array(
            'lifetime' => $cookie->getLifetime(),
            'path'     => $cookie->getPath()
           // 'domain'   => $cookie->getConfigDomain(),
           // 'secure'   => $cookie->isSecure(),
           // 'httponly' => $cookie->getHttponly()
        ); 

What we did here is we disabled the cookies check that Magento do when we try to login.. This should not be used on live site because cookies will work if you have a true domain.

Tuesday, April 12, 2011

Magento - How to make a quantity increment in product view?



Files needed, Files to be edited:
  • JQuery (probably the latest version, better if minified)
  • jincrement.js (this is our own js.. you can change its name as you like)
  • jQuery.noConflict()
  • styles.css (styling for the increment buttons)
  • layout/catalog.xml (this is where we'll reference our js, just being clean)
  • template/catalog/product/view/addtocart.phtml (we'll put a div here)
  1. create a file with the name jincrement.js and put this code on it..
  2. jQuery(document).ready(function(){
        var $j = jQuery.noConflict();
        $j("div.quantity").append('<input type="button" value="+" id="add1" class="plus" />').prepend('<input type="button" value="-" id="minus1" class="minus" />');
        $j(".plus").click(function(){
            var currentVal = parseInt($j(this).prev(".qty").val());
            if (!currentVal || currentVal=="" || currentVal == "NaN") 
               currentVal = 0;
               $j(this).prev(".qty").val(currentVal + 1);
        });
        $j(".minus").click(function(){
            var currentVal = parseInt($j(this).next(".qty").val());
            if (currentVal == "NaN") 
                currentVal = 0;
                if (currentVal > 0){
                    $j(this).next(".qty").val(currentVal - 1);
                }
        });
    });
  3. Place the JQuery and jincrement.js on js/
  4. in catalog.xml
  5. <!--
    Product view
    -->
    <reference name="head">
                <action method="addJs"><script>jquery.min.js</script></action>
                <action method="addJs"><script>jquery.noconflict.js</script></action>
                <action method="addJs"><script>jquery.jincrement.js</script></action>
               ... OTHER CODES HERE ...
    </reference>
  6. in addtocart.phtml
    in line 34, enclose in <div class="quantity"></div> the input tag...

  7. style using styles.css.. this is my code for styling..
  8. div.add-to-cart div.quantity input#minus1{
        background-color: #A1A1A1;
        border: 1px solid #BBB;
        border-radius: 3px 0 0 3px;
        -moz-border-radius: 3px 0 0 3px;
        float: left;
        height: 20px;
        margin-right: 1px;
        padding-left: 2px;
        cursor: pointer;
    }
    div.add-to-cart div.quantity input#minus1:hover{
        background-color: #CCC;
        border: 1px solid #DDD;
    }
    div.add-to-cart div.quantity input#add1{
        background-color: #A1A1A1;
        border: 1px solid #BBB;
        border-radius: 0 3px 3px 0;
        -moz-border-radius: 0 3px 3px 0;
        height: 20px;
        vertical-align: top;
        cursor: pointer;
    }
    div.add-to-cart div.quantity input#add1:hover{ 
        background-color: #CCC;
        border: 1px solid #DDD;
    }
    div.add-to-cart div.quantity{
        margin-bottom: 5px;
        float: right;
    }
and that's it!

Monday, March 28, 2011

Magento Debugging Tips

Referenced from Inchoo

Snippet 1: Check if variable is object and of which class
<?php Zend_Debug::dump(get_class($this), 'get_class') ?>
<?php
/**
 * Once you do get_class you will get a class name.
 * With class name you can do something like
 * $this = new Mage_Page_Block_Html_Header();
 * then IDE will give you autocomplete on things like "$this->"
 *
 * Just remember to comment the out the
 * //$this = new Mage_Page_Block_Html_Header();
 * once you are done
 */
?>

Snippet 2: Do a basic dump of variable to see its "content"/value

<?php Zend_Debug::dump($this->debug(), 'debug') ?>

Snippet 3: Read the value of object properties/attributes

(Note that $_product var is just example, it can be any Magento/Varien object)

<?php Zend_Debug::dump($_product->getData('attribute_name')) ?> 

Snippet 4: Read the value of object properties/attributes

(Does the same thing as Snippet 3)

<?php Zend_Debug::dump($_product->getAttributeName()) ?>

Snippet 5: Compare the value of attribute/property to some other value

<?php if($_product->getSku() == 'sku-xxx-ppp-222'): ?>
    Ouput something only if product Sku is equal to 'sku-xxx-ppp-222'.
<?php endif; ?> 

Snippet 6: Loop trough Magento collection object

(Check if something is a collection, if we can iterate trough it)

<?php if($someVar instanceof Varien_Data_Collection): ?>
    
    <?php foreach($someVar as $k => $v): ?>
  • Some value: < ?php echo $v ?>

Tuesday, March 22, 2011

How to automate related products selection in Magento?

This mod does the following
  • fetch all the products in a category
  • dispaly them below the main picture in product view
  • no need to set the related products (if your products are within the same category)
  1. go to app/design/frontend/your-package/your-theme/template/catalog/list/related.phtml ( make a backup of this one )
  2. overwrite all the codes in your related.phtml with this one
<?php
$_product = $this->getProduct();
if ($_product) {
   // get collection of categories this product is associated with
   $categories = $_product->getCategoryCollection()
   ->setPage(1, 1)
   ->addFieldToFilter('parent_id',"2")
   ->load();

   // if the product is associated with any category
   if ($categories->count())
      foreach ($categories as $_category){
         $cur_category = Mage::getModel('catalog/category')->load($_category->getId());
         $prodCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($_category);
         Mage::getSingleton('catalog/product_status')
           ->addVisibleFilterToCollection($prodCollection);
         Mage::getSingleton('catalog/product_visibility')
           ->addVisibleInCatalogFilterToCollection($prodCollection);
         if($prodCollection->count() > 1) :
             ?><div class="related-product">
               <div class="block-title">
                 <h4><?php echo $this->__('More from this artist...') ?></h4>
               </div>
             <?php $products = Mage::getResourceModel('catalog/product_collection')
             ->addCategoryFilter($_category)
             ->addAttributeToSelect('small_image'); ?>
<ol class="mini-products-list" id="block-related">
 <div class="block-content">
<?php foreach ( $products as $productModel ){
$_product = Mage::getModel('catalog/product')->load($productModel->getId());
$width=100; $height=100;
$_imageUrl = $this->helper('catalog/image')->init($productModel, 'small_image')->resize($width, $height);
$currentUrl = $this->helper('core/url')->getCurrentUrl();                    //SPLIT THE URL FOR QUERY STRING<br />
$rel_product = explode( "?", $currentUrl); 
//SPLIT THE URL FOR CATEGORY
$cprod_url = explode( "/", $_product->getProductUrl());                    //ASSIGN THE STRIPPED URL TO A VARIABLE
$isyan = $cprod_url[0].'//'.$cprod_url[2].'/'.$cprod_url[4];                    //WE WILL HIDE THE PRODUCT THAT IS CURRENTLY BEING VIEWED FROM DISPLAYING ON THE RELATED PRODUCTS
if( $_product->getProductUrl() != $rel_product[0] && $isyan != $rel_product[0]){
?>
 <li class="item">
<a href="<?php echo $isyan ?>" class="product-image" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><img src=<?=$_imageUrl ?> width="<?=$width?>" height="<?=$height?>"/></a>
</li>
 <?php } 
}
?>
</div>
</ol>
</div>
<?php   endif; 
}
}
?>
Hope this helps! Godbless!

Wednesday, February 23, 2011

Magento - How to insert a custom tab in One Page Checkout?

I found a nice extension from Inchoo which will insert a customizable tab in Magento OnePage Checkout. So I used this extension and extended it a little bit to fit the requirements.

What I want to do is to add a Terms & Conditions tab before placing an order. So here's the code.
/home/donnafiera/magento/app/design/frontend/default/default/template/checkout/onepage/heared4us.phtml

<form id="co-heared4us-form" action="">
  <?php echo "I have read the <a href='".Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."test.pdf' target='_Blank'>TERMS AND CONDITIONS</a>"; ?>
  <label><input id="chkaccept" type="checkbox" name="useraccept" value="yes" />&nbsp;Accept</label><br/>
</form>
<script type="text/javascript">
  function formValidation(oEvent) {
  oEvent = oEvent || window.event;
  var txtField = oEvent.target || oEvent.srcElement;
  var t1ck=true;
  if(!document.getElementById("chkaccept").checked ){ t1ck=false;}
    if(t1ck){document.getElementById("btnTerms").disabled = false; }
    else{document.getElementById("btnTerms").disabled = true; }
  }

window.onload = function () {
var btnTerms = document.getElementById("btnTerms");
var chkaccept=document.getElementById("chkaccept");
var t1ck=false;
document.getElementById("btnTerms").disabled = true;
chkaccept.onclick = formValidation;
}
</script> 
<div class="button-set">
<p class="required"><?php echo $this->__('* Required Fields') ?></p>
<div id="heared4us-buttons-container">
<button id="btnTerms" type="button" class="form-button right" onclick=" heared4us.save();"><span><?php echo $this->__('Continue') ?></span></button>
<span id="heared4us-please-wait" style="display:none;" class="opc-please-wait">
<img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" class="v-middle" alt="" /> &nbsp; <?php echo $this->__('Loading next step...') ?> &nbsp;
</span>
</div>
</div>

Sunday, February 6, 2011

Magento - How to create a special price page? (with new products first)

I've created a Magento site for a client who wants to have a special price page, wherein she could put products having special price/discounted price..
Requirements:
  • app/code/local/Mage/Catalog/Block/Product/Special.php
  • app/design/frontend/default/donna/template/catalog/product/special.phtml
  • Magento backend - CMS>Pages>create-a-special-price-page
Special.php
=========================================
<?php
class Mage_Catalog_Block_Product_Special extends Mage_Catalog_Block_Product_List
{
   function get_prod_count()
   {
      //unset any saved limits
      Mage::getSingleton('catalog/session')->unsLimitPage();
      return (isset($_REQUEST['limit'])) ? intval($_REQUEST['limit']) : 9;
   }// get_prod_count
   function get_cur_page()
   {
      return (isset($_REQUEST['p'])) ? intval($_REQUEST['p']) : 1;
   }// get_cur_page
   /**
    * Retrieve loaded category collection
    *
    * @return Mage_Eav_Model_Entity_Collection_Abstract
   **/
   protected function _getProductCollection()
   {
        $todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
        $tomorrow = mktime(0, 0, 0, date('m'), date('d')+1, date('y'));
        $dateTomorrow = date('m/d/y', $tomorrow);
        $collection = Mage::getResourceModel('catalog/product_collection');
        $collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
        $collection = $this->_addProductAttributesAndPrices($collection)
         ->addStoreFilter()
         ->addAttributeToSort('entity_id', 'desc') //THIS WILL SHOW THE LATEST PRODUCTS FIRST
         ->addAttributeToFilter('special_from_date', array('date' => true, 'to' => $todayDate))
         ->addAttributeToFilter('special_to_date', array('or'=> array(0 => array('date' => true, 'from' => $dateTomorrow), 1 => array('is' => new Zend_Db_Expr('null')))), 'left')
         ->setPageSize($this->get_prod_count())
         ->setCurPage($this->get_cur_page());
        $this->setProductCollection($collection);
        return $collection;
   }// _getProductCollection
}// Mage_Catalog_Block_Product_New
?> 
==============================================

special.phtml
==============================================
<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class="widget widget-new-products">
    <div class="widget-title">
        <h2><?php echo $this->__('Special Product') ?></h2>
    </div>
    <div class="widget-products">
    <?php $_columnCount = $this->getColumnCount(); ?>
        <?php $i=0; foreach ($_products->getItems() as $_product): ?>
        <?php if ($i++%$_columnCount==0): ?>
        <ul class="products-grid">
        <?php endif ?>
            <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image') ?>" width="195px" height="195px" alt="<?php echo $this->htmlEscape($_product->getName()) ?>" /></a>
                    <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>)"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
                    <!-- ###### BRANDS EG. BY CHIC ON A MISSION ###### -->
                    <div class="product-brand"><?php echo $this->htmlEscape($_product->getextraline()) ?></div>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?> 
                    <?php echo $this->getPriceHtml($_product, true, '-widget-new-grid') ?>
                <div class="actions">
                    <?php if($_product->isSaleable()): ?>
                        <!-- <button type="button" title="<?php /* echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart')*/ ?></span></span></button>-->
                    <?php else: ?>
                        <!--<p class="availability out-of-stock"><span><?php // echo $this->__('Out of stock') ?></span></p>-->
                        <div class="out-of-stock-special"><img src="<?php echo $this->getSkinUrl('images/donna/soldout-overon.png') ?>" alt="uitverkocht" width="50px" /></div>
                    <?php endif; ?>
                    <?php /*<ul class="add-to-links">
                        <?php if ($this->helper('wishlist')->isAllow()) : ?>
                            <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                        <?php endif; ?>
                        <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                            <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                        <?php endif; ?>
                    </ul> */ ?>
                </div>
                </li>
        <?php if ($i%$_columnCount==0 || $i==count($_products)): ?>
        </ul>
        <?php endif ?>
        <?php endforeach; ?>
        <div class="toolbar-bottom">
            <?php // echo $this->getToolbarBlock()->setTemplate('catalog/product/list/ctoolbar.phtml')->toHtml(); ?>
        </div>
    </div>
</div>
<?php endif; ?>  
========================================

In the CMS Page that you created, click Design tab then in the Page layout>Layout update xml put this code..

<reference name="content">
   <block type="catalog/product_special" name="product_special" template="catalog/product/list.phtml">
       <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
              <action method="setDefaultDirection"><dir>desc</dir></action>
              <action method="setDefaultOrder"><field>entity_id</field></action>
              <block type="page/html_pager" name="product_list_toolbar_pager" />
       </block>
      <action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action>
      <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
   </block>
</reference>
========================================

There you have it... Don't forget to put a special price, special-from-date and special-to-date in your products...
Reference: http://www.magentocommerce.com/boards/viewthread/16098/P15/ :kkrieger's post