Thursday 26 December 2013

Get products from particular category Magento

 <?php $categoryIds = array(3,4);//category id

                                    $collection = Mage::getModel('catalog/product')
                                    ->getCollection()
                                    ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
                                    ->addAttributeToSelect('*')
                                    ->addAttributeToFilter('category_id', array('in' => $categoryIds))
                    ?>
                   
                    <?php $_collectionSize = $collection->count() ?>
    <?php //$_columnCount = $this->getColumnCount(); ?>
    <?php $i=0; foreach ($collection as $product): ?>
        <?php if ($i++%4==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 $product->getName()?>">
                        <img src="<?php echo Mage::helper('catalog/image')->init($product, 'small_image')->resize(197, 167); ?>" alt="<?php echo $product->getName()?>" border="0" />
                    </a>
                <h2 class="product-name"><a href="<?php echo $product->getProductUrl()?>" title="<?php echo $product->getName()?>"><?php echo $product->getName() ?></a></h2>
               <div class="price-box">
               <?php echo Mage::helper('core')->currency($product->getPrice(),true,false);?>
               </div>
                <div class="actions">
                    <?php if($product->isSaleable()): ?>
                        <button class="button" onclick="setLocation('<?php echo Mage::getUrl('checkout/cart/add/')?>product/<?php echo $product->getId() ?>/')" title="<?php echo $this->__('Köp');?>" type="submit"><span><span><?php echo $this->__('Köp');?></span></span></button>
                    <?php else: ?>
                        <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                    <?php endif; ?>

                </div>
            </li>
        <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
        </ul>
        <?php endif ?>
        <?php endforeach ?>

Friday 13 December 2013

get custom options programatically Magento

Hi with the below code you can get the product custom  option attributes all data


$product = Mage::getModel("catalog/product")->load(1); //product id 1
$i = 1;
echo "<pre>";
foreach ($product->getOptions() as $o) {
    echo "<strong>Custom Option:" . $i . "</strong><br/>";
    echo "Custom Option TITLE: " . $o->getTitle() . "<br/>"; //Colors
    echo "Custom Option TYPE: " . $o->getType() . "<br/>"; //drop_down
    echo "Custom Option Values: <br/>";
    $values = $o->getValues();
    foreach ($values as $v) {
        print_r($v->getData());
    }
    $i++;
    echo "<br/>";
}

Sunday 24 November 2013

Get product attribute on cart page magento

 
Hi to get the product atribute on cart page 
 
place the below code in 
 
in app/design/frontend/default/your_theme/template/checkout/cart/item/default.phtml 
 
<?php 
$_item = $this->getItem();
$_product = $_item->getProduct()->load();
?>
<?php echo $_product->getCustomAttribute(); ?>// place ths where ever you show 
and replace the CustomAttribute  with your attribute code
 
 
thanks 

add arrow to the div through css

Hi to add the css to your div at any position you can folow the below link

http://cssarrowplease.com/

here you will find the live demo and you can customize the css according to your need online.


hope this will help somebody
thanks

Thursday 14 November 2013

check current page is category page or another page in Magento

 
Hi In magento sometime we need to place conditions on content on the basis of page type .
For  that the best way to find the current page type is to check the controller of that page,
Below you can see how we can do this


  <?php $category = Mage::app()->getFrontController()->getRequest()->getControllerName(); // gives current controller name for eg "cart", "category"

you can check it by
 echo  $category ;  and than on the basis of that you can place your condition like below

in this i have check two controllers cart and or category thats why i have use array to check there values .
    $catpage = array("cart", "category");
if(in_array($category, $catpage)){    ;?>       

        <?php } else { ?>

<?php }?>

highlight current category link in magento

Hi with the below peace of code you can highlight the current category link. In this we get first get the current url and than match it with the category url and on the basis of that we will apply our classes  


 <?php $curr =  "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; //full current url
                                    $currcate =  $category->getURL(); // your category url (i have use this  on product list page )
                                    if ($curr == $currcate) {
                                    $class = "active";}else {

                                    $class="nonactive";}
                                    //echo $class;

                                    ?>
                            
on the bais of above match we will apply alss in the anchor tag as below
<a class="<?php echo $class; ?> " href="<?php echo $category->getURL()?>">




Friday 8 November 2013

onclick increment number by 1 javascript

<!DOCTYPE html>
<html>
<head>
<script>
function changeLink()
{
var a = document.getElementById('inc').value;
var b = ++a;

document.getElementById('inc').value= b;
}
</script>
</head>
<body>

<a id="myAnchor"  onclick="changeLink()" href="#">click</a>
<input type="button" id ="inc" value="1">



</body>
</html>

get all categories and subcategories in magento

 
 
<?php 
$_categories = Mage::getBlockSingleton('catalog/navigation'); 
foreach ($_categories->getStoreCategories() as $_category) { 
$category = Mage::getModel('catalog/category'); 
$category->load($_category->getId()); 
$subcategories = explode(',', $category->getChildren()); 
?> 
<dl> 
<dt><?php echo $this->htmlEscape($_category->getName()); ?></dt> 
<dd> 
<ol> 
<?php 
foreach ($subcategories as $subcategoryId) { 
$category->load($subcategoryId); 
echo '<li><a href="' . $category->getURL() . '">' . $category->getName() . '</a></li>'; 
} 
?> 
</ol> 
</dd> 
</dl> 
<?php

} 
?>

Tuesday 5 November 2013

submit multiplr forms on single click

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#submitButton").click(function () {
                $.post($("#form1").attr("action"), $("#form1").serialize(),
                  function () {
                      alert('Form 1 submitted');
                  });

                $.post($("#form2").attr("action"), $("#form1").serialize(),
                  function () {
                      alert('Form 2 submitted');
                  });
            });
        });
    </script>
</head>
<body>
    <form id="form1" action="#" method="post">
        <input type="button" id="submitButton" value="Submit" />
    </form>

    <!-- Hidden form -->
    <form id="form2" action="#" method="post">
        <input type="text" id="data1" value="testing1" />
        <input type="text" id="data2" value="testing2" />
    </form>
</body>
</html>

simple jquery increment decrement on click

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("p").click(function(){
    var newf = parseFloat($(inc).val())+1;
$(inc).val(newf);
  });

  $("b").click(function(){
    var newm = parseFloat($(inc).val())-1;
$(inc).val(newm);
  });



});
</script>
</head>
<body>
<p>If you click on me, I will add 1.</p>
<b>If you click on me, will reduce 1 </b>



<input type="text" value="1" id ="inc" name="num"/>
</body>
</html>

Monday 2 September 2013

change product image on hover in catalog page Magento

To show different image on hover on magento product category page  you have to change the small code in the list.phtml file located at


app->design->frontend->default->your theme->template->catalog->product->list.pthml


and in this file around line 58 you will see something like this

       <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a>
      
       just search for this and replace it with
      
        <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" onmouseover="this.src='<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(135) ?>';" onmouseout="this.src='<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(135) ?>';" />
       
       
        that’s all we need to do
        note in list file there are two modes list and grid above will work for list mode to make it work in grid mode change it around line 95 in same file
       
       

multiple website

i have recently configure a multi store for my client and i want to share this with you and in a simple way

 setting up multiple stores in Magento is somehow easy but configuring up multiple website in Magento is a bit difficult task :).

This step-by-step tutorial will guide you to do so.

I suppose that you have installed Magento in folder named ‘magento’. So, your website URL will be http://yourwebsite.com/magento/

- Create Website, Store, and Store View

- Create Website
- Go to System –> Manage Stores
- Create Website
- Name = My Website
- Code = mywebsite
- Sort Order = 10
- Save Website

- Create Store
- Go to System -> Manage Stores
- Create Store
- Website = My Website
- Name = Main Store
- Root Category = Root Catalog

- Create Store View
- Go to System -> Manage Stores
- Create Store View
- Store = My Website -> Main Store
- Name = English
- Code = English
- Status = Enabled
- Sort Order = 10

- Change Link URL
- Go to System -> Configuration -> GENERAL -> Web
- Change ‘Current Configuration Scope’ to ‘My Website’
- Unsecure -> Base URL = http://yourwebsite.com/magento/
- Unsecure -> Base Link URL = http://yourwebsite.com/magento/mywebsite/

- Change Theme (Optional: If you want different design for your new website)

- Suppose your new design template and skin folder is named ‘mywebsite’
- Copy ‘mywebsite’ template folder to magento/app/design/frontend/default/
- Copy ‘mywebsite’ skin folder to magento/skin/frontend/default/

- Go to System -> Configuration -> GENERAL -> Design
- Change ‘Current Configuration Scope’ to ‘My Website’
- Themes -> Default = ‘mywebsite’
- Uncheck ‘Use Default’
- Save Config

- Create a new folder named ‘mywebsite’ inside ‘magento’ folder.

- Copy index.php of magento folder into mywebsite folder.

- Open index.php of mywebsite folder.
- Change $compilerConfig = ‘includes/config.php’; to $compilerConfig = ‘../includes/config.php’;
- Change $mageFilename = ‘app/Mage.php’; to $mageFilename = ‘../app/Mage.php’;
- Change Mage::run(); to Mage::run(‘mywebsite’,'website’);

- Copy .htaccess file from magento folder to mywebsite folder

Finally, you have created a new website for your magento shop. Your base installation can be browsed by http://yourwebsite.com/magento/ and your new website can be browsed by http://yourwebsite.com/magento/mywebsite/

install language pack in magento

In magento to make multilanguage store work properly  we need to add a language pack in magento by default it has only english language for frontend 

to make it work we have to download the language pack and upload it to root directory

we can download the language pack from this url http://www.magentocommerce.com/translations here select your desired language and download it . In which you willl get a app folder , just upload it to root directory or merge into your app folder  and now go to admin -> system-> configuration -> you will see something like this



now click on locale tab under general  you will see something like this 

now in locale select box choose your language for which you have upload the language pack and its done .

create multilanguage store in magento

Magento has a very rich feature of multi language and normally the international sites which need to sell there products internationally needs to give information to the users in there language , for this magento has a inbuilt multi language store feature So lets see how we can do this . I assume that you have a fresh install magento now go to sytem->managestores and than click on it


and than you will see like this

now click on createstoreview tab in the right corner and you will see something like this

in the name field === give the name to your view like spanish, German etc

and in code field ==== give it like en or gm which will be useful for in files to distinguish the languages

set status === enable

and now save it now go to frontend and check in header a language switcher will be in right corner

The requested URL /magento/index.php/install/ was not found on this server. Solved

to fix this issue all you have to do is to open your  htacess file in magento folder in your favourite text editor and in the end of file just add

AcceptPathInfo On   and thats it



Sunday 25 August 2013

get odd even in forloop php

<?php $i  = 1;
$range = range(0,10);
foreach($range as $range1){
    $rangenew = $i++ ;
if ($rangenew % 2 == 0) {
  echo  $rangenew."It's even".'</br>';  
    }
else{
  
    echo  $rangenew."It's odd".'</br>';  
    }
}

?>

Thursday 9 May 2013

Replace labels text in form on load

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>

 var dictionary = new Array(); // for containing label texts and the text to be replaces
 dictionary['No1mbre'] = 'Number';   
 dictionary['Ogre'] = 'Age';  

//function for replacing text according to the attribute
//i use label attribute of table  , you can use any attribute in place of label

 $('document').ready(function(){
    
//     
 $('tbody').find('label').each(function(){
    if (dictionary[ $(this).text() ])
     {
         $(this).text( dictionary[ $(this).text() ] );
     }
 })

});

</script>
</head>
<body>
            <table>
            <tbody>
            <tr>
            <th>
            <label for="id_first_name" >No1mbre</label>
                <label for="id_first_name" >Age</label>
            </th>
            </tr>
            </tbody>
            </table>
</body>
</html>

Monday 22 April 2013

Add new field on click in forms


<?php
if(isset($_POST['sub']))
{
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
?>
<html>
<head>
<style>
p{overflow:visible; }

</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function appendText()
{

var txt3=document.createElement("p");
txt3.innerHTML="<input type='text' name='file[]'  />";               // Create text with DOM
$("div").append(txt3);        // Append new elements
}
</script>
</head>




<body>
<button onclick="appendText()">Append text</button>
<p>Add files here.</p>
<form action="" method="post" name="form1" >


<div></div>
<input type="submit" name="sub" />
</form>
</body>
</html>

Friday 12 April 2013

make active link highlight

HI with the use of jquery we can easily do this





<html>
<head></head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function () {
$(".somelink a").click(function (e) {
e.preventDefault();
$(".somelink a").addClass("active").not(this).removeClass("active");
});
});
</script>
<style>
.active { color:red;}
</style>
</head>
<body>
<ul class="somelink">
<li><a href="#">Sample Anchor</a></li>
<li><a href="#">Sample Anchor</a></li>
</ul>
</body>
</html>

enjoy this ...........

Monday 4 February 2013

How to update atribute value of all products at the same time MAGENTO?




In magento there is a very good option in the admin to update all the attributes at the same time.
like if there are 100 products whose price has been changed and there are same price for all and you want to change them quickly and not by updating each single product , magento has a good option for you


In the admin go to 

 system -> manageproduct-> and there will be checkbox on the left in front of each product 

Select the multiple products you want to update and than on the right top there is a option of action ,click on the dropdown and select  update attribute and than press submit . You will see the atribute of products and than click on the CHANGEcheckbox of attribute which ever you want to update for selected products and than press save . The attribute for all the products will be updated 

You can also select all if you want to update any attribute which has same value for all products  .

Thursday 31 January 2013

skip entry if already exist Mysql

Hi we can easily do this with the use of single parameter  ignore
 after insert

like

$insert1= mysql_query("INSERT IGNORE INTO your_table_name(your column name,..) VALUES('your values')",$conn1);

this will help you to skip a entry if already exist in table and continue after that with other entries

.htaacess file not visible in magento folder

Hi i was doing my magento project with multi store setup, in which i need to copy the .htacess file to new folder but i was amaze it was not present there
after so long i found the reason. in my folder the option for show hidden files was disable 

so for displaying the files you must go to

view-> and click on show hidden files

and you will able tyo see all hidden files with in that folder

Friday 18 January 2013

Print star with php using loops

  
You can print any shape with php like i have create a simple star shape shown below by using loops




<?php $nbsp = "*";
      $a = 100;
      $b = 0 ;
       $e = 10 ;
      for($i=0; $i<=10;$i++){ ?>
    <div ><div style = "text-align:center;width:<?php echo $a++ ;?>px;"><?php echo str_repeat($nbsp,$b++) ;?></div></div>
     <?php } ?>
<?php
           for($i=0; $i<=10;$i++){ ?>
    <div ><div style = "text-align:center;width:<?php echo $a++ ;?>px;"><?php echo str_repeat($nbsp,$e--) ;?></div></div>
     <?php } ?>

Tuesday 15 January 2013

Simple javascritp toggle or hide/show on click

Hi this is the simplest JavaScript toggle function to use on click


<script type="text/javascript">
                function toggle(element) {
              document.getElementById(element).style.display = (document.getElementById(element).style.display == "none") ? "" : "none";
   }

  // function toggle1(element) {
              //document.getElementById(element).style.display = "none";
  // }
    </script>


<div id="secret" style="display: none;">
         <!--content to show on click -->
             <div>put your content here which should be show on click</div>
           <!--/ontent to show on click -->
 </div>


//here is the li where i have use the toggle function
 <li><a  href="javascript:toggle('secret')" >click here to toggle or hide/show </a></li>

JUST COPY THE WHOLE CODE AND PLACE IN YOUR EDITOR TO GET IT WORK

Get product quantity in magento

with this code you can get the product quantity of a product           

   
 $qty = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();

echo   $qty ;

You can use this quantity also to show almost gone or soldout image for a product on category or product view page.

need to place in condition like this

<?php if($qty<10){ ?>
  show almost gone image...
    <?php }elseif ($qty<1) {?>
       show soldout image.............
    <?php } ?>

Monday 14 January 2013

Get custom attribute value in magento admin orders

with this code you can get any custom attribute value in magento admin order section , you can show only in admin or in frontend depends upon your need
   

 <div style="color: black; font-size: 14px; font-weight: bold;">proviser <span><?php $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $_item->getSku(), array('provider')); echo $product->getprovider(); ?>  </span>  </div>

in above code just replace your attribute code which you specify in admin for that like for my case i use "provider "
just replace provider with your attribute code and place this in your 

/public_html/app/design/adminhtml/default/default/template/sales/items/column/name.phtml file   

Show custom error messages on cart page

Hi in this article i will try to tell you all about how to show custom error messages or popups on cartpage

in the below folder
app/code/core/Mage/Checkout/controllers/CartController.php

near about line 537 you will find code something like this

 else {
                    $this->_getSession()->addError(
                        $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode))
                    );
                }




which contains a error message for wrong coupon code apply

which i have change to

else {
                    $this->_getSession()->addError(
               
                        $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode))
                    );
                    $myValue = 'Hello World';
                   Mage::getSingleton('customer/session')->setMyvalue($myValue);
                                              
                }



in this i have make use of magento sessions , i have set a session as setMyvalue
for the wrong code apply and than check the value of this in cart file

cart file path = under your theme /template/checkout/cart.phtm
i have retrieve the session value something like

 <?php $myValue=  Mage::getSingleton('customer/session')->getMyvalue(); ?> 
<?php if ($myValue!= ''){ ?>
do something:: you can do anything here like show your html ,js popups.....
<?php } else {?>
do somethindo something:: you can do anything here like show your html ,js popups.....
<?php }?>  

thats it ......


Get store code in Magento

$storeCode = Mage::app()->getStore()->getCode();
echo $storeCode;

Thursday 10 January 2013

Get all cms pages in header dynamically Magento

  Place this code in header file below topcontainer

  <?php $collection = Mage::getModel('cms/page')->getCollection()->addStoreFilter(Mage::app()->getStore()->getId());?>
<?php  $collection->getSelect()
->where('is_active = 1'); ?>
<ul id="nav">
<?php foreach ($collection as $page): ?>
<?php $PageData = $page->getData(); ?>
<?php// print_r($PageData);?>
<?php if($PageData['identifier']!='no-route' && $PageData['identifier']!='enable-cookies' && $PageData['identifier']!='home2') { ?>
<li>
<a href="/magento/index.php/<?php echo $PageData['identifier']?>"><span><?php echo $PageData['title'] ?></span></a>
</li>
<?php } ?>
<?php endforeach; ?>
</ul>


Note change this part of code "/magento/index.php/" according to your domain 

SIMPLE JAVASCRIPT CALCULATOR CODE

<!-- Opening a HTML Form.
Number 1: Number 2: Get Result:
-->
<script language="javascript" type="text/javascript"> 
function multiply(){ 
a=Number(document.calculator.number1.value); 
b=Number(document.calculator.number2.value); 
c=a*b; 
document.calculator.total.value=c; 


function addition(){ 
a=Number(document.calculator.number1.value); 
b=Number(document.calculator.number2.value); 
c=a+b; 
document.calculator.total.value=c; 


function subtraction(){ 
a=Number(document.calculator.number1.value); 
b=Number(document.calculator.number2.value); 
c=a-b; 
document.calculator.total.value=c; 


function division(){ 
a=Number(document.calculator.number1.value); 
b=Number(document.calculator.number2.value); 
c=a/b; 
document.calculator.total.value=c; 


function modulus(){ 
a=Number(document.calculator.number1.value); 
b=Number(document.calculator.number2.value); 
c=a%b; 
document.calculator.total.value=c; 

</script> 
 
</head> 
 
<body> 
 
<!-- Opening a HTML Form. -->  
<form name="calculator"> 
 
<!-- Here user will enter 1st number. -->  
Number 1: <input type="text" name="number1">  
  
 
<!-- Here user will enter 2nd number. -->  
Number 2: <input type="text" name="number2">  
 
 
<!-- Here result will be displayed. -->  
Get Result: <input type="text" name="total">  
 
 
<!-- Here respective button when clicked, calls only respective artimetic function. -->  
<input type="button" value="ADD" onclick="javascript:addition();"> 
<input type="button" value="SUB" onclick="javascript:subtraction();"> 
<input type="button" value="MUL" onclick="javascript:multiply();"> 
<input type="button" value="DIV" onclick="javascript:division();"> 
<input type="button" value="MOD" onclick="javascript:modulus();"> 
 
</form> 
 
</body> 
</html> 

Wednesday 9 January 2013

code to show category images on custom phtml files and link to their category pages

<?php

 $root_category = Mage::getModel('catalog/category')->load(2); // Put your root category ID here. like 2
$subcategories = $root_category->getChildren();
foreach(explode(',',$subcategories) as $subcategory) {
$category = Mage::getModel('catalog/category')->load($subcategory);
echo'<pre>';
//print_r($category);
echo  $category->getImageUrl(); //place this url in your image tag to show the image

  }

  ?>