Magento Coding Solutions

Remove assign category from product

/*-----------Remove product From assign category Start------------- */
$productId=5;
$product=Mage::getModel("catalog/product")->load($productId);
$productIdss=$product->getId();
$all_cats = $product->getCategoryIds($productIdss);
  foreach($all_cats as $_catId)
{
$product=Mage::getSingleton('catalog/category_api')->removeProduct($_catId,$productIdss);
}
/*-----------Remove product From assign category End------------- */

Magento programmatically remove product images

/* Remove Product media Image Start*/
$ptoductId=120;
$productImgRemov= Mage::getModel('catalog/product')->load($ptoductId);
$entityTypeId = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($entityTypeId, 'media_gallery');
$gallery = $productImgRemov->getMediaGalleryImages();
foreach ($gallery as $image)
$mediaGalleryAttribute->getBackend()->removeImage($productImgRemov, $image->getFile());
$productImgRemov->save();
/* Remove Product media Image End*/

get category in tree view in magento

<?php include "app/Mage.php";
    Mage::app();
$STORE_ID=5
$root_categories_id=Mage::app()->getStore($STORE_ID)->getRootCategoryId();
//$cat_mod = Mage::getModel('catalog/category')->setStoreId(STORE_ID)->load($root_category_id);
//$main_categories=Mage::getModel('catalog/category')->getCategories($root_category_id);



function getCategoryList($cateid){

$main_categories = Mage::getModel('catalog/category')->getCategories($cateid);

foreach($main_categories as $_cate)
{

$categories = Mage::getModel('catalog/category')->load($_cate->getId());
/*echo "<pre>";
print_r($categories);
echo "</pre>";*/
if ($categories->getIsActive())
{

echo "<li value='".$categories->getId()."'>";
for($m=1;$m<=substr_count($categories->path,'/');$m++){
echo "&nbsp"."&nbsp";
}?>
<a href="manage-category.php?Id=<?php echo $categories->getId(); ?>">
<?php
echo $categories->getName()."</a></li>";

$selected='';

//echo '<option value="'. $_category->getId().'" '.$selected.' >'. $space . $_category->getname().'</option>';

$children = $categories->getChildren();

if(count($children)>0)
{
getCategoryList($categories->getId());
}

}
}
}
?>


<div class="category-product">
<div id="narrow-by-list">
<p class="cate-name"><?php echo 'Category' ?> : <?php echo $cat_mod->getName() ?></p>
</div>

<ul id="treemenu1" class="treeview">
<?php getCategoryList($root_categories_id); ?>
</ul>
</div>

check user login or not in magento


Not: unauthorized user Redirect to login page with "$beforAutoUrl " URL and after login redirect to "$beforAutoUrl" url
====================================
if( !Mage::getSingleton( 'customer/session' )->isLoggedIn() ){
$session = Mage::getSingleton('customer/session');
$beforAutoUrl = Mage::getBaseUrl('web').str_replace('/clients/omegabanners/','',$_SERVER['REQUEST_URI']);
$beforAutoUrl="";
$session->setBeforeAuthUrl($beforAutoUrl);

Mage::app()->getResponse()->setRedirect(Mage::getUrl("customer/account/login"));
}else{

echo "User Loged In"
}

magento user login information

$session=Mage::getSingleton('customer/session', array('name'=>'frontend'));
$userId=$session->getId();

Magento get post data from url

$this->getRequest()->getParam(key);
$arrParams = Mage::app()->getRequest()->getParams();
print_r($arrParams);

Magento Get Admin Url with key


echo Mage::helper("adminhtml")->getUrl("module_name/action_name/");
Example :

Mage::helper("adminhtml")->getUrl("Ordermanager/adminhtml_ordermanagerbackend/");
Ordermanager:=module_name
adminhtml_ordermanagerbackend = my Module action_name

see below in xml
from : app\code\local\Ordermanager\Ordermanager\etc\config.xml

<menu>
 <ordermanager module="ordermanager">
<title>Ordermanager</title>
<sort_order>100</sort_order>
<children>
 <ordermanagerbackend module="ordermanager">
<title>Backend Page Title</title>
<sort_order>0</sort_order>
<action>ordermanager/adminhtml_ordermanagerbackend</action>
 </ordermanagerbackend>
 <ordermanager module="ordermanager">
   <title>Manage Ordermanager</title>
<sort_order>0</sort_order>
<action>ordermanager/adminhtml_ordermanager</action>
 </ordermanager>
</children>
 </ordermanager>
</menu>

magento login programmatically

<?php $email="customer email address";
 $password="customer password";

 $session = Mage::getSingleton('customer/session');
 $message=""; //error message to add to session

 try {
  $session->login( $email, $password );
  if ($session->getCustomer()->getIsJustConfirmed()) {
  //Customer is confirmed and successfully logged in
  }
 } catch (Mage_Core_Exception $e) {
  //error occured
  switch ($e->getCode()) {
  case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
  //email not confirmed actions here
  break;
  case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
  //Email or password invalid actions here
  $message = $e->getMessage();//echo the error message
  break;
  default:
  $message = $e->getMessage(); //Display other error messages
  }
  $session->addError($message);
 } catch (Exception $e) {
  //login failed because of some other error.
 }?>

magento user registration programmatically

$customer_email = 'test@testemail.com'; 
$customer_fname = 'test_firstname';    
$customer_lname = 'test_lastname';     
$passwordLength = 10;


$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->setEmail($customer_email);
$customer->setFirstname($customer_fname);
$customer->setLastname($customer_lname);
$customer->setPassword(md5());
$customer->save();

magento add product image programmatically

<?php
$productId=1;
$newProduct= Mage::getModel('catalog/product')->load($productId);

                    /*myimage*/
           
                $previewImage= Mage::getBaseDir().'/images/designs/1_0.png';
                if(file_exists($previewImage)){
                                $newProduct->setMediaGallery (array('images'=>array (), 'values'=>array ()));
                                $newProduct->addImageToMediaGallery ($previewImage, array ('thumbnail','small_image','image'), false, false);
                                }                     
                            }           
                                   
               
                $newProduct->save();
               
                ?>

get attribute value by attribute Id in magento

 $attributCode=23;
$attrV = Mage::getModel('eav/entity_attribute_option')->
getCollection()->setStoreFilter()->join('attribute','attribute.attribute_id=main_table.attribute_id', 'attribute_code')->addFieldToFilter('main_table.option_id',array('eq'=>$attributCode))->getFirstItem();

            $attDataV=$attrV->getData();
            print_r($attDataV);
            $viewNo=$attDataV['value'];

add custom options in magento admin sales order grid

Stap1: app\code\core\Mage\Adminhtml\Block\Sales\Order\Grid.php

   add custom column  like "Fedback"

    $this->addColumn('Feedback', array(
            'header' => Mage::helper('sales')->__('Feedback'),
            'align' =>'left',
            'index' => 'Feedback',
            'renderer'  => 'Mage_Adminhtml_Block_Sales_Order_renderer_Feedback'
            //’attr’ => ‘value’, // You can use it to pass extra custom value //
            ));


Step 2: Make "Renderer" folder app\code\core\Mage\Adminhtml\Block\Sales\Order\
Step3: make  app\code\core\Mage\Adminhtml\Block\Sales\Order\Renderer\Feedback.php

 <?php

class  Mage_Adminhtml_Block_Sales_Order_Renderer_Feedback extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract{
 public function render(Varien_Object $row)
    {
        $data= $row->getData();
        echo "oderId:".$data['entity_id'];
       $html = '<p>'.$row->getData(entity_id).'</p>';
  
       $html .= '<a  href="'.Mage::getBaseUrl('web').''">DST Design</a></p>';
        return $html;
    }
}
?>

Magento admin login not working in chrome

I think there is the problem with session cookie with the chrome browser. So just go through this directory /app/code/core/Mage/Core/Model/Session/Abstract/Varien.php file and comment out the line from 85 to 92 in magento


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

programaticaly Insert and select quary In magento

    
 INSERT QUERY

include('../app/Mage.php');
Mage::app();

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$sql="INSERT INTO opd_uploads SET extension='$extension', sessionId='$sessionId', ip='$ip', status=1, dateTime=now()";
$write->query($sql);
//lastInserted ID
$imageId = $write->lastInsertId();


SELECT QUERY

$read= Mage::getSingleton('core/resource')->getConnection('core_read');
       
         $value=$read->query("select * from opd_uploads WHERE id='".$imageRowId."'");
         $row = $value->fetch();
         $orgFilExt=$row['extension'];
       

Get store data Magento

Get store data
Mage::app()->getStore();
Store Id
Mage::app()->getStore()->getStoreId();
Store code
Mage::app()->getStore()->getCode();
Website Id
Mage::app()->getStore()->getWebsiteId();
Store Name
Mage::app()->getStore()->getName();
Is Active
Mage::app()->getStore()->getIsActive();
Store Home Url
Mage::app()->getStore()->getHomeUrl();

get Collection oder by and limit In Magento


hear  mydesign: is custom module
$limit=10
 $start=0
$modelColl=Mage::getModel('mydesign/mydesign')->getCollection()->addFieldToFilter('user_id',$userId);
            $modelColl->setOrder('mydesign_id','DESC');
            $modelColl->getSelect()->limit($limit,$start);

orders product by oder_id in magento


======================
get orderproduct By oder_id in magento
============================

$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
        $items = $order->getAllItems();
                        $itemcount=count($items);
                                             
                        $date=date ("Y-m-d H:i:s");
                        foreach ($items as $itemId => $item)
                        {
                       
                            $product=Mage::getModel('catalog/product')->load($item->getProductId());
                      }

Get Gallery Images in Magento by Product Id

<?php
include "../app/Mage.php";
Mage::app();

$product_id=$_REQUEST['product'];
$product=Mage::getModel('catalog/product')->load($product_id);
$mediaImages=$product->getMediaGalleryImages();
foreach($mediaImages as $_image){
  
    ?>
     <li>
        <a href="<?php echo Mage::helper('catalog/image')->init($product, 'thumbnail', $_image->getFile())->resize(364,418); ?>" title="<?php echo $_image->getLabel();?>" onclick="$('image').src = this.href; return false;">
            <img src="<?php echo Mage::helper('catalog/image')->init($product, 'thumbnail', $_image->getFile())->resize(76,70); ?>" width="76" height="70" alt="<?php echo $_image->getLabel(); ?>" />          
            </a>
     </li>
    <?php
  
  
    }
    ?>

Add css ,js in xml in magento

<reference name="head">
                <action method="addCss">
                    <stylesheet>css/pagination.css</stylesheet>
                </action>

<action method="addCss"><stylesheet>directory/file.css</stylesheet></action>
<action method="addItem"><type>skin_js</type><name>js/myjavascript.js</name></action>
            </reference>

Pagination In Magento programmatic

Stape1. ...
<style>
ul.pagination {
font-family: "Arial", "Helvetica", sans-serif;
font-size: 13px;
height: 100%;
list-style-type: none;
margin: 20px 0;
overflow: hidden;
padding: 0; }
ul.pagination li.details {
background-color: white;
border-color: #C8D5E0;
border-image: none;
border-style: solid;
border-width: 1px 1px 2px;
color: #1E598E;
font-weight: bold;
padding: 8px 10px;
text-decoration: none; }
ul.pagination li.dot {
padding: 3px 0; }
ul.pagination li {
float: left;
list-style-type: none;
margin: 0 3px 0 0; }
ul.pagination li:first-child {
margin-left: 0; }
ul.pagination li a {
color: black;
display: block;
padding: 7px 10px;
text-decoration: none; }
ul.pagination li a img {
border: medium none; }
ul.pagination li a.current {
background-color: white;
border-radius: 0 0 0 0;
color: #333333; }
ul.pagination li a.current:hover {
background-color: white; }
ul.pagination li a:hover {
background-color: #C8D5E0; }
ul.pagination li a {
background-color: #F6F6F6;
border-color: #C8D5E0;
border-image: none;
border-style: solid;
border-width: 1px 1px 2px;
color: #1E598E;
display: block;
font-weight: bold;
padding: 8px 10px;
text-decoration: none; }
</style>
Stape2...

<?php  
    function pagination($per_page = 10, $page = 1, $url = '', $total){

        $adjacents = "2";

        $page = ($page == 0 ? 1 : $page);
        $start = ($page - 1) * $per_page;

        $prev = $page - 1;
        $next = $page + 1;
        $lastpage = ceil($total/$per_page);
        $lpm1 = $lastpage - 1;

        $pagination = "";
        if($lastpage > 1)
        {
        $pagination .= "<ul class='pagination'>";
        $pagination .= "<li class='details'>Page $page of $lastpage</li>";
        if ($lastpage < 7 + ($adjacents * 2))
        {
        for ($counter = 1; $counter <= $lastpage; $counter++)
        {
        if ($counter == $page)
        $pagination.= "<li><a class='current'>$counter</a></li>";
        else
        $pagination.= "<li><a href='{$url}$counter'>$counter</a></li>";
        }
        }
        elseif($lastpage > 5 + ($adjacents * 2))
        {
        if($page < 1 + ($adjacents * 2))
        {
        for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
        {
        if ($counter == $page)
        $pagination.= "<li><a class='current'>$counter</a></li>";
        else
        $pagination.= "<li><a href='{$url}$counter'>$counter</a></li>";
        }
        $pagination.= "<li class='dot'>...</li>";
        $pagination.= "<li><a href='{$url}$lpm1'>$lpm1</a></li>";
        $pagination.= "<li><a href='{$url}$lastpage'>$lastpage</a></li>";
        }
        elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
        {
        $pagination.= "<li><a href='{$url}1'>1</a></li>";
        $pagination.= "<li><a href='{$url}2'>2</a></li>";
        $pagination.= "<li class='dot'>...</li>";
        for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
        {
        if ($counter == $page)
        $pagination.= "<li><a class='current'>$counter</a></li>";
        else
        $pagination.= "<li><a href='{$url}$counter'>$counter</a></li>";
        }
        $pagination.= "<li class='dot'>..</li>";
        $pagination.= "<li><a href='{$url}$lpm1'>$lpm1</a></li>";
        $pagination.= "<li><a href='{$url}$lastpage'>$lastpage</a></li>";
        }
        else
        {
        $pagination.= "<li><a href='{$url}1'>1</a></li>";
        $pagination.= "<li><a href='{$url}2'>2</a></li>";
        $pagination.= "<li class='dot'>..</li>";
        for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
        {
        if ($counter == $page)
        $pagination.= "<li><a class='current'>$counter</a></li>";
        else
        $pagination.= "<li><a href='{$url}$counter'>$counter</a></li>";
        }
        }
        }

        if ($page < $counter - 1){
        $pagination.= "<li><a href='{$url}$next'>Next</a></li>";
        // $pagination.= "<li><a href='{$url}$lastpage'>Last</a></li>";
        }else{
        //$pagination.= "<li><a class='current'>Next</a></li>";
        // $pagination.= "<li><a class='current'>Last</a></li>";
        }
        $pagination.= "</ul>\n";
        }
        return $pagination;
    }


    $page=1;
    if(isset($_GET['page']) && $_GET['page']!=''){
    $page=$_GET['page'];
    }
    //echo pagination(10,$page,Mage::getBaseUrl('web').'mydesign?page=',200);
?>

Step3) mydesign is my custom module

    <form action='' name="myDesignSave" method="post" >
      $modelCount=Mage::getModel('mydesign/mydesign')->getCollection()->addFieldToFilter('user_id',$userId);
            $rows=count($modelCount);
           
            $page=1;//Default page
            $limit=1;//Records per page
            $start=0;//starts displaying records from 0
            if(isset($_GET['page']) && $_GET['page']!=''){
            $page=$_GET['page'];
            }
            $start=($page-1)*$limit;
           
           
           
                            $modelColl=Mage::getModel('mydesign/mydesign')->getCollection()->addFieldToFilter('user_id',$userId);
            $modelColl->getSelect()->limit($limit,$start);


foreach($modelColl as $value){


}



   </form>
<?php
        echo pagination($limit,$page,Mage::getBaseUrl('web').'mydesign?page=',$rows);
        //call function to show pagination
        ?>


choose an option how to change in magento

from path :
/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php and
/app/design/frontend/evia/default/template/catalog/product/view/type/options/configurable.phtml

get directory paths, get Base URLs, get URLs in static block, get secure URL in Magento



1) Get Directory paths

 Mage::getBaseDir()  //output : /var/www/html/magento
Mage::getBaseDir('app')  //output : /var/www/html/magento/app
Mage::getBaseDir('media') //output : /var/www/html/magento/media
Mage::getBaseDir(‘design’) => Get design directory path
Mage::getBaseDir(‘code’) => Gives code directory file path
Mage::getBaseDir(‘lib’) => Gives lib directory file path
Mage::getBaseDir(‘skin’) => Gives skin directory file path
Mage::getBaseDir(‘var’) => Gives var directory file path
Mage::getBaseDir(‘cache’) => Gives cache directory file path
Mage::getBaseDir(‘log’) => Gives log directory file path

 
 
 
2) Get Base URL
 Mage::getBaseUrl() => Get base url path e.g. http://yourwebsite.com/
 Mage::getBaseUrl('media') => Get MEDIA folder path e.g. http://yourwebsite.com/media/
 Mage::getBaseUrl('js') => Get JS folder path e.g. http://yourwebsite.com/js/
 Mage::getBaseUrl('skin') => Get SKIN folder path e.g. http://yourwebsite.com/skin/

 3) Get Current URL
Mage::helper('core/url')->getCurrentUrl();


4) Get Home URL
Mage::helper('core/url')->getHomeUrl();

5) Create module your
Mage::getUrl('module/controller/action');

6)  Get secure URL(To get secure URL you just need to add one more parameter as bellow)
Mage::getUrl('',array('_secure'=>true))
Mage::getUrl('module/controller/action',array('_secure'=>true))

 
 7) Get URL path in Static Block

 i) Get Base URL
{{base url=''}}

ii) Get Skin URL
{{skin url='images/skinimage.jpg'}} 
iii) Get Media URL
{{media url='/mediaimage.jpg'}}
iv) Get Store URL
{{store url=''}}