Saturday 27 September 2014

how to set simple form captcha through js

<script>
function myFunction() {
    var x = Math.floor((Math.random() * 9) + 1);

    document.getElementById("cap1").innerHTML = x;
 var y = Math.floor((Math.random() * 9) + 1);
document.getElementById("cap2").innerHTML = y;
var z= x+y;
document.getElementById("hid_cap1").value = z;

}
function valcpa() {
var hidc = document.getElementById("hid_cap1").value;
var orgc = document.getElementById("org_cap1").value;
if(orgc=="")
{
document.getElementById("cap_msg").innerHTML = "*Please Enter captcha value.";
return false;
}
else if(hidc!=orgc)
{
document.getElementById("cap_msg").innerHTML = "*Please Enter sum of both value.";
return false;
}

else {
document.getElementById("cap_msg").innerHTML = "";
 }
}
</script>



<body onload="myFunction();">
<form action="" method="post">
 <table>
 <tr>
  <td><label><span id="cap1"></span>+<span id="cap2"></span> =</label></td>
  <td><input type="hidden" id="hid_cap1" name="hid_cap" value="" /><input type="text" name="org_cap" id="org_cap1" required="required" />
  <p id="cap_msg" style="color:#f00;"></p>
  </td>
  </tr>
 
  <tr>
  <td colspan="2">
 <input type="SUBMIT" name="" value="Submit"    CLASS="Submit-d-ship " onclick="return valcpa();">
  </td>
  </tr>
  </table>
  </form>
</body>

how to resize image in custom module in magento

 Open namespace/modulename/helper/data.php

paste following code in helper class :-

 <?php
class Namespace_Modulename_Helper_Data extends Mage_Core_Helper_Abstract
{

public function resizeImage($imageName, $width=NULL, $height=NULL, $imagePath=NULL)
{     
    $imagePath = str_replace("/", DS, $imagePath);
    $imagePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $imageName;
    
    if($width == NULL && $height == NULL) {
        $width = 100;
        $height = 100;
    }
    $resizePath = $width . 'x' . $height;
    $resizePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $resizePath . DS . $imageName;
            
    if (file_exists($imagePathFull) && !file_exists($resizePathFull)) {
        $imageObj = new Varien_Image($imagePathFull);
        $imageObj->constrainOnly(TRUE);
        $imageObj->keepAspectRatio(TRUE);   //set false if you don't want set image size in ratio (like:-100x100,200x200).
        $imageObj->resize($width,$height);
        $imageObj->save($resizePathFull);
    }
            
    $imagePath=str_replace(DS, "/", $imagePath);
    return Mage::getBaseUrl("media") . $imagePath . "/" . $resizePath . "/" . $imageName;
}
}

and  use in any template/phtml file of your module:-
 

<img src="<?php echo Mage::helper('modulename')->resizeImage('imagename.jpg', 100, 100, 'path/image'); ?>" style="padding:10px;">


Note :- it take automatically base url (www.domain.com/media/). So you put only your image url.

Thursday 25 September 2014

url rewrite to hide query sting in php

It rewrite url like :-

http://www.rootdirectory.com/index.php?sate=rajasthan&city=jaipur&land=malviyanagar

to :-

http://www.rootdirectory.com/rajasthan/jaipur/malviyanagar

create a .htaccess file on root directory and paste following code

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z0-9]+|)/?$ index.php?state=$1 [QSA]

RewriteRule ^([a-zA-Z0-9]+|)/([a-zA-Z0-9]+|)/?$ index.php?state=$1&city=$2 [QSA]

RewriteRule ^([a-zA-Z0-9]+|)/([a-zA-Z0-9]+|)/([a-zA-Z0-9]+|)/?$ index.php?state=$1&city=$2&land=$3 [QSA]

After used it code you can access your query string value like :-

And last  on http://www.rootdirectory.com/index.php

paste following code :-

<div>

<a href="http://www.rootdirectory.com">home</a>
<a href="http://www.rootdirectory.com/rajasthan">Rajasthan</a>
<a href="http://www.rootdirectory.com/delhi/newdelhi">New Delhi</a>
<a href="http://www.rootdirectory.com/rajasthan/jaipur/malviyanagar">Malviya Nagar</a>
</div>


<?php

echo "<h2>".$_GET['state']."</h2>";
echo "<h2>".$_GET['city']."</h2>";

echo "<h2>".$_GET['land']."</h2>";

?>

Monday 22 September 2014

Add get directions maps to website

<!DOCTYPE html>
<html>
  <head>
    <title> Lalit Get Directions service</title>
    <style>
      html, body, #map-canvas {
        height: 600px;
        width: 600px;
       margin-left:150px;
       top:60px;
        padding: 0px
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom:7,
    center: chicago
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="panel">
    <b>Start: </b>
    <input type="text" value="jaipur,rajsthan" id="start">
    <b>End: </b>
    <input type="text" id="end">
    <input type="button" onClick="calcRoute();" value="Get Direction">
  
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

how to add google address search map on website

<!DOCTYPE html>
<html>
  <head>
    <title> address search</title>
    <style>
      html, body, #map-canvas {
         height: 600px;
        width: 600px;
        padding: 0px;
        margin-left:100px;
        top:60px;
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 10,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="panel">
      <input id="address" type="textbox" value="Sydney, NSW">
      <input type="button" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

Thursday 18 September 2014

how to get category thumbnail image in magento

<?php  $catId = $_category->getId(); ?>
<?php $thumb = Mage::getModel('catalog/category')->load($catId)->getThumbnail();?>
<img src="<?php echo Mage::getBaseUrl('media').'catalog/category/'.$thumb;?>" >

Wednesday 17 September 2014

get all sale products from category and show on header top in magento

Note :-It's work only magneto 1.9 version because we used magento default funcnality.



On list page  will be show only simple products and and sale product show on tab.
 and set design according to your theme.

First open list.phtml file and replace all code with following  :-

<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else:

?>


<div class="header-minicart minicart1">
<a class="skip-link skip-cart " href="#header-cart12">
<span class="icon"></span>
<span class="label">closeout</span>
</a>

<div id="header-cart12" class="block block-cart skip-content">
<div id="minicart-error-message" class="minicart-message"></div>
<div id="minicart-success-message" class="minicart-message"></div>
<div class="minicart-wrapper">
<?php $i="";
$k = 0; ?>
<div>
<ul id="cart-sidebar" class="mini-products-list">
<?php foreach ($_productCollection as $_products): ?>
<?php  $specialprice = $_products->getSpecialPrice();
$specialPriceToDate = $_products->getSpecialToDate();

$specialdate = 1;
$today = 0;
if($specialPriceToDate!="")
{
$today = strtotime(date("Y-m-d"));
$specialdate = strtotime($specialPriceToDate);
}
if($specialprice!="" && $specialdate >= $today) {

$i = 0; ?>
<li class="item last odd" xmlns="http://www.w3.org/1999/html">
<a class="product-image" href="<?php echo $_products->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_products, 'small_image'), null, true) ?>">
<img height="50" width="50" alt="<?php echo $this->stripTags($this->getImageLabel($_products, 'small_image'), null, true) ?>" src="<?php echo $this->helper('catalog/image')->init($_products, 'small_image')->keepFrame(false)->resize(50); ?>">
</a>
<div class="product-details">
<?php $_productsNameStripped = $this->stripTags($_products->getName(), null, true); ?>
<p class="product-name">
<a href="<?php echo $_products->getProductUrl() ?>" title="<?php echo $_productsNameStripped; ?>"><?php echo $_helper->productAttribute($_products, $_products->getName() , 'name'); ?></a>
</p>
<table class="info-wrapper">
<tbody>
<tr>
<th>Price</th>
<td>
<span class="price"><?php echo $this->getPriceHtml($_products, true) ?></span>
</td>
</tr>

</tbody>
</table>
</div>
</li>
<?php $i++;
$k++;
}

?>
<?php endforeach; ?>

</ul>
<?php if($i==0){
?>
<p class="block-subtitle">No Sale item in this category!</p>
<?php
}
?>

</div>
</div>
</div>

</div>


<div class="category-products">
    <?php echo $this->getToolbarHtml() ?>
    <?php // List mode ?>
    <?php if($this->getMode()!='grid'): ?>
    <?php $_iterator = 0; ?>
    <ol class="products-list" id="products-list">
    <?php foreach ($_productCollection as $_product): ?>
<?php  $specialprices = $_product->getSpecialPrice();
$specialPriceToDate = $_product->getSpecialToDate();
$specialdate = 0;
$today = 1;
if($specialPriceToDate!="")
{
$specialprices="";
$today = strtotime(date("Y-m-d"));
$specialdate = strtotime($specialPriceToDate);
}
if($specialprices=="" && $specialdate < $today) { ?>

        <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
            <?php // Product Image ?>
            <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
                <?php /* Based on the native RWD styling, product images are displayed at a max of ~400px wide when viewed on a
                        one column page layout with four product columns from a 1280px viewport. For bandwidth reasons,
                        we are going to serve a 300px image, as it will look fine at 400px and most of the times, the image
                        will be displayed at a smaller size (eg, if two column are being used or viewport is smaller than 1280px).
                        This $_imgSize value could even be decreased further, based on the page layout
                        (one column, two column, three column) and number of product columns. */ ?>
                <?php $_imgSize = 300; ?>
                <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                     src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize($_imgSize); ?>"
                     alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
            </a>
            <?php // Product description ?>
            <div class="product-shop">
                <div class="f-fix">
                    <div class="product-primary">
                        <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
                        <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></a></h2>
                        <?php if($_product->getRatingSummary()): ?>
                        <?php echo $this->getReviewsSummaryHtml($_product) ?>
                        <?php endif; ?>

                        <?php
                            $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                            foreach($_nameAfterChildren as $_nameAfterChildName):
                                $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                                $_nameAfterChild->setProduct($_product);
                        ?>
                            <?php echo $_nameAfterChild->toHtml(); ?>
                        <?php endforeach; ?>
                    </div>
                    <div class="product-secondary">
                        <?php echo $this->getPriceHtml($_product, true) ?>
                    </div>
                    <div class="product-secondary">
                        <?php if($_product->isSaleable() && !$_product->canConfigure()): ?>
                            <p class="action"><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></p>
                        <?php elseif($_product->isSaleable()): ?>
                            <p class="action"><a title="<?php echo $this->__('View Details') ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?></a></p>
                        <?php else: ?>
                            <p class="action availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                        <?php endif; ?>
                        <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>
                    <div class="desc std">
                        <?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                        <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped ?>" class="link-learn"><?php echo $this->__('Learn More') ?></a>
                    </div>
                </div>
            </div>
        </li>
<?php } ?>
    <?php endforeach; ?>
    </ol>
    <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>

    <?php else: ?>

    <?php // Grid Mode ?>

    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = $this->getColumnCount(); ?>
    <ul class="products-grid products-grid--max-<?php echo $_columnCount; ?>-col">
        <?php $i=0; foreach ($_productCollection as $_product): ?>
            <?php /*if ($i++%$_columnCount==0): ?>
            <?php endif*/ ?>
<?php  $specialprices = $_product->getSpecialPrice();
$specialPriceToDate = $_product->getSpecialToDate();
$specialdate = 0;
$today = 1;
if($specialPriceToDate!="")
{
$specialprices="";
$today = strtotime(date("Y-m-d"));
$specialdate = strtotime($specialPriceToDate);
}
if($specialprices=="" && $specialdate < $today) { ?>            <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->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
                    <?php $_imgSize = 210; ?>
                    <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                         src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
                         alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
                </a>
                <div class="product-info">
                    <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>

                    <?php
                        $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                        foreach($_nameAfterChildren as $_nameAfterChildName):
                            $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                            $_nameAfterChild->setProduct($_product);
                    ?>
                        <?php echo $_nameAfterChild->toHtml(); ?>
                    <?php endforeach; ?>

                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                    <?php endif; ?>
                    <div class="actions">
                        <?php if($_product->isSaleable() && !$_product->canConfigure()): ?>
                            <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 elseif($_product->isSaleable()): ?>
                            <a title="<?php echo $this->__('View Details') ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?></a>
                        <?php else: ?>
                            <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                        <?php endif; ?>
                        <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>
                </div>
            </li>
<?php } ?>
            <?php /*if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
            <?php endif*/ ?>
        <?php endforeach ?>
    </ul>
    <script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
    <?php endif; ?>

    <div class="toolbar-bottom">
        <?php echo $this->getToolbarHtml() ?>
    </div>
</div>
<?php endif; ?>

<?php
    //set product collection on after blocks
    $_afterChildren = $this->getChild('after')->getSortedChildren();
    foreach($_afterChildren as $_afterChildName):
        $_afterChild = $this->getChild('after')->getChild($_afterChildName);
        $_afterChild->setProductCollection($_productCollection);
    ?>
    <?php echo $_afterChild->toHtml(); ?>
<?php endforeach; ?>


Tuesday 16 September 2014

how to remove .php from urls with htaccess in php

url :-
http://hostname/product.php

create a .htaccess file on root directory  and paste following code :-

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

then you can access set your link like :-
 http://hostname/product

Tuesday 9 September 2014

magento product share on pintrest

 Set following code on product view page:-

<script type="text/javascript">
(function(d){
    var f = d.getElementsByTagName('SCRIPT')[0], p = d.createElement('SCRIPT');
    p.type = 'text/javascript';
    p.async = true;
    p.src = 'http://assets.pinterest.com/js/pinit.js';
    f.parentNode.insertBefore(p, f);
}(document));
</script>

 <a href="http://www.pinterest.com/pin/create/button?url=<?php echo $this->helper('catalog/product')->getProductUrl($_product); ?>&media=<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(600,400) ?>&description=<?php echo $_helper->productAttribute($_product, nl2br($_product->getShortDescription()), 'short_description') ?>" data-pin-do="buttonPin" data-pin-config="above">
        <img src="http://assets.pinterest.com/images/pidgets/pin_it_button.png" />
    </a>

Monday 1 September 2014

how to convert number to words in php

<?php

function convert_number($number)
{
    if (($number < 0) || ($number > 999999999))
    {
    throw new Exception("Number is out of range");
    }

    $Gn = floor($number / 100000);  /* Millions (giga) */
    $number -= $Gn * 100000;
    $kn = floor($number / 1000);     /* Thousands (kilo) */
    $number -= $kn * 1000;
    $Hn = floor($number / 100);      /* Hundreds (hecto) */
    $number -= $Hn * 100;
    $Dn = floor($number / 10);       /* Tens (deca) */
    $n = $number % 10;               /* Ones */

    $res = "";

    if ($Gn)
    {
        $res .= convert_number($Gn) . " Lac";
    }

    if ($kn)
    {
        $res .= (empty($res) ? "" : " ") .
            convert_number($kn) . " Thousand";
    }

    if ($Hn)
    {
        $res .= (empty($res) ? "" : " ") .
            convert_number($Hn) . " Hundred";
    }

    $ones = array("", "One", "Two", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
        "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen",
        "Nineteen");
    $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",
        "Seventy", "Eigthy", "Ninety");

    if ($Dn || $n)
    {
        if (!empty($res))
        {
            $res .= " and ";
        }

        if ($Dn < 2)
        {
            $res .= $ones[$Dn * 10 + $n];
        }
        else
        {
            $res .= $tens[$Dn];

            if ($n)
            {
                $res .= "-" . $ones[$n];
            }
        }
    }

    if (empty($res))
    {
        $res = "zero";
    }

    return $res;
}
?>

dynamically adding file upload fields to a form using javascript

<script language="javascript" type="text/javascript">
       var a=1;
        function AddMoreImages() {

         
            var fileUploadarea = document.getElementById("fileUploadarea");
          
            //var newLine = document.createElement("br");
            //fileUploadarea.appendChild(newLine);
            var newFile = document.createElement("input");
            newFile.type = "file";
          

      
             
            newFile.setAttribute("id", "FileUpload" + a);
            newFile.setAttribute("name", "file[]");
            newFile.setAttribute("class", "browse-snap");
            var div = document.createElement("div");
            div.appendChild(newFile);
            div.setAttribute("id", "div" + a );
            fileUploadarea.appendChild(div);
          
             var newbot= document.createElement("input");
                newbot.type="Button";
                newbot.setAttribute("id","b" + a);
                newbot.setAttribute("value","remove" + a);
                newbot.setAttribute("class","close-btn");
                newbot.setAttribute("onclick","deletefile(this.id);");
                var divid=document.getElementById("div" + a);
               fileUploadarea.appendChild(div).appendChild(newbot);
             
            a++;
            return false;
        }
      
        function deletefile(abf)
        {
        a--;
        var abf1 = abf.split("b");
        //var uplod=document.getElementById("fileUploadarea");
        var im=document.getElementById("div" + abf1[1]);
        im.parentNode.removeChild(im);
        return false;
      
        }
    </script>
<body>
    <form id="form1">
    <div>
        <div id="fileUploadarea">
          
        </div>
        &nbsp;
        <input style="display: block;" id="btnAddMoreImages" type="button" value="Add more images" onClick="AddMoreImages();" />
      
    </div>
    </form>
</body>
</html>

how to get attribute value in magento

<?php 

   echo $_product->getAttributeText('attribute_code');

?>

create administrator user by run code in magento

Create a php file on magento root directory and run following code :-



<?php
require_once('app/Mage.php');
umask(0);
Mage::app();

$user = Mage::getModel('admin/user')->setData(array(
'username'  => 'admin1',
'firstname' => 'admin',
'lastname'    => 'ministrator',
'email'     => 'admin1@gmail.com',
'password'  =>'tm123456',
'is_active' => 1
))->save();
$user->setRoleIds(array(1))->setRoleUserId($user->getUserId())->saveRelations();

echo "User has been created successfully!";
?>
if  genrate an error :-
(error "parent role id 'G1' does not exist" on admin)

 then  below two query are run on db 


insert into admin_role values(1,0,1,1,'G',0,'Administrator');


insert into admin_rule values (8,1,'all',null,0,'G','allow');

how to get logged in user id and email in magento

<?php $cuid = Mage::getSingleton('customer/session')->getCustomer()->getId();?>

<?php $cuemail = Mage::getSingleton('customer/session')->getCustomer()->getEmail();?>

How to get customer group id by email id in magento

<?php
$con = Mage::getSingleton('core/resource')->getConnection('core_write');

$res=$con->query("select * from customer_entity where email = '".$rows['email']."'");

$rowss=$res->fetch();
echo $rowss['group_id'];
?>

how to get admin customer edit url in magento

<?php $cus_adit_url = Mage::helper("adminhtml")->getUrl("adminhtml/customer/edit/id/".$ids."/"); ?>

2d array sorting by string value in php

<?php
function lalit($a, $b)
 {
 return strnatcmp($a[1], $b[1]);
  }
 usort($array, 'lalit'); // your array with string value

print_r($array);
?>

how to get email address from admin configuration in magento

<?php echo Mage::getStoreConfig('contacts/email/recipient_email');
?>

active class on custom menu in magento

<?php $main_cat = explode('index.php',$this->helper('core/url')->getCurrentUrl());
                 $mn_cat = explode('/',substr($main_cat[1],0,-5));
                 ?>
               
                <?php $_subcategories = $_category->getChildrenCategories() ?>
    <li class="<?php if(in_array(str_replace(' ','-',strtolower($_category->getName())),$mn_cat)){ echo "active";}?>"  ><span><a href="<?php echo $_helper->getCategoryUrl($_category) ?>">    

Rwrite url by xml file in magento

first you go to yourmodule/etc/config.xml paste this code between  <global> </global>
 tag :-

<global>
<rewrite>
            <customer_account_create>
                <from><![CDATA[#^/account/create/#]]></from>which url is you wants
                <to>/customer/account/create/</to>//current url
                <complete>1</complete>
            </customer_account_create>
        </rewrite>

</global>

how to change  module name  from url :-

<routers>
            <customer>
                <use>standard</use>
                <args>
                    <module>Mage_Customer</module>
                    <frontName>customer</frontName>//for example change the front name cutomer to user.
                </args>
            </customer>
        </routers>

get image from instagram by api code

<?php
$userid = "1367761071";
$accessToken = "1367761071.5b9e1e6.7651f16d557948a598176b957c35c693";
$url = "https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
?>

<ul>
<?php $i=1; foreach ($result->data as $post): ?>
    <?php  if($i>5){ break;} ?>
    <li><a class="" href="<?php echo $post->images->standard_resolution->url ?>" data-fancybox-group="gallery" title="<?php echo $post->caption->text ?>"><img src="<?php echo $post->images->thumbnail->url ?>" width="246" height="246" alt="<?php echo $post->caption->text ?>" /></a> </li>

<?php $i++; endforeach; ?>
</ul>
</div>

remove category from layered navigation in magento


 add following condition on layered navigation filtering :-

<?php if($_filter->getItemsCount() && $_filter->getType() != "catalog/layer_filter_category"): ?>   

how to get product all image in magento

<?php
$product = Mage::getModel('catalog/product')->load($_product->getId());
             foreach ($product->getMediaGalleryImages() as $image) {
                        echo var_export($image->getUrl());
                       
                        } ?>

how to call block in controller in magento

<?php 
public function indexAction()
{
//Get current layout state
$this->loadLayout();
$block = $this->getLayout()->createBlock(
'Mage_Core_Block_Template',
'my_block_name_here',
array('template' => 'codeline/developer.phtml')
);
$this->getLayout()->getBlock('content')->append($block);
//Release layout stream... lol... sounds fancy
$this->renderLayout();
}
?>

how to get product Qty on product view page in magento

<?php echo $up_qty =  $this->getProductDefaultQty() * 1 ?>  //get selected quantity.
<?php $m_id = $_product->getId();
 $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($m_id);
$p_stock = $stock->getQty();//get total quantity.
?>
<select name="qty" id="qty" class="input-text qty" >
<?php 

for($i=1; $i<=$p_stock; $i++) { ?>
<option <?php if($p_stock==$up_qty) {?> select="selected"<?php } ?>><?php echo $i; ?> </option>
<?php } ?>
</select>

product list sort by popularity in magento

follow the following step :-

first you go to  following directory:-

/app/code/core/Mage/Catalog/Model/Resource/Product/collection.php

isert this code
<?php
public function sortByReview($dir){
 $table = $this->getTable('review/review');
 $entity_code_id = Mage::getModel('review/review')->getEntityIdByCode(Mage_Rating_Model_Rating::ENTITY_PRODUCT_CODE);

 $cond = $this->getConnection()->quoteInto('t2.entity_pk_value = e.entity_id and ','').$this->getConnection()->quoteInto('t2.entity_id = ? ',$entity_code_id);

 $this->getSelect()->joinLeft(array('t2'=>$table), $cond,array('review' => new Zend_Db_Expr('count(review_id)')))

->group('e.entity_id')->order("review $dir");

 }
?>
second open below directory:---
/app/code/core/Mage/Catalog/Model/Config.php
find "getAttributeUsedForSortByArray" function and replace it these code

<?php
public function getAttributeUsedForSortByArray()
    {
        $options = array(
            'position'  => Mage::helper('catalog')->__('Position'),
            'popularity'  => Mage::helper('catalog')->__('Popularty')
            
        );
        foreach ($this->getAttributesUsedForSortBy() as $attribute) {
            /* @var $attribute Mage_Eav_Model_Entity_Attribute_Abstract */
            $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
        }

        return $options;
    }
?>
Last open below directory:---
/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php

find "setCollection" function and replace it these code
<?php

public function setCollection($collection)
   {
       $this->_collection = $collection;
       $this->_collection->setCurPage($this->getCurrentPage());
       // we need to set pagination only if passed value integer and more that 0
       $limit = (int)$this->getLimit();
       if ($limit) {
           $this->_collection->setPageSize($limit);
       }
        if($this->getCurrentOrder() == 'popularity'){
           $this->_collection->sortByReview($this->getCurrentDirection());
       }
     else if ($this->getCurrentOrder()) {
      
           $this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
    }
  
       return $this;
   }
?>

how to call all reviews and reviews form in product page in magento



{{block type="review/product_view_list" name="product.info.product_additional_data" as="product_additional_data" template="review/product/view/list.phtml"}}

{{block type="review/form" name="product.review.form" as="review_form"}}

create a zoom effects on image css


<style>

.product-image img:hover {
    transform: scale(1.10);
}
.product-image img {
    transition-duration: 0.3s;
}

</style>

how to change success and error massage due to create account in magento

got to app/code/core/Mage/customer/controllers/accountcontroller.php

search default massege and replace your new massege.

header,footer,head in magneto

Open it :-

app\design\frontend\base\default\template\page\html

create custom homepage in magento

First go to magento root directory : -

app/design/frontend/packa/template/page

and create phtml file (home.phtml) then defile it in xml layout file
app\design\frontend\base\default\layout\page.xml


<!--  set home page   -->
        <page_home translate="label">
        <label>home page</label>
        <reference name="root">
        <action method="setTemplate"><template>page/home.phtml</template></action>
        <!-- Mark root page block that template is applied -->
        <action method="setIsHandle"><applied>1</applied></action>
        </reference>
        </page_home>
    
<!--  set home page   --> 

last define in  config xml file

app\code\core\Mage\Page\etc\config.xml

<!--  set home page   -->
            <home module="page" translate="label">
                    <label>home page</label>
                    <template>page/home.phtml</template>
                    <layout_handle>page_home</layout_handle>
                </home>
 <!--  set home page   -->