Magento Coding Solutions

program to delete Products Image by Category Magento

Step 1:
create a .php file "deleteProductImage.php" on root directory

<?php
require_once "app/Mage.php";
umask(0);
Mage::app('admin');
Mage::setIsDeveloperMode(true);
echo "<pre>";
if(!empty($_REQUEST['catId'])){
$categoryId=$_REQUEST['catId'];
}else{
echo "please Pass CategoryId!";
exit;
}

$limit=1000;
$start=0;
if(!empty($_REQUEST['start'])){
$start=$_REQUEST['start'];
}
if(!empty($_REQUEST['limit'])){
$limit=$_REQUEST['limit'];
}

$productCollection = Mage::getModel('catalog/category')
                    ->load($categoryId)
                    ->getProductCollection();
$productCollection->getSelect()->limit($limit,$start);



/* print_r($collection);
die; */
/*  ->load($categoryId)
                    ->getProductCollection(); */
foreach($productCollection as $product){
//print_r($product);
/* echo $product->getId();
echo "---</br>"; */
//echo $product->getId();
/* echo "<br/>";
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product'; */
//echo "<br/>";

$MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
/* echo "<pre>";
print_r($MediaGallery);
echo "</pre>"; */
if(count($MediaGallery)>0){

foreach($MediaGallery as $eachImge){
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
$MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
$DirImagePath=str_replace("/",DS,$eachImge['file']);
$DirImagePath=$DirImagePath;
// remove file from Dir

$io     = new Varien_Io_File();
$io->rm($MediaCatalogDir.$DirImagePath);

$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
}
}else{
echo $product->getSku();
echo "</br>";

}


}
?>

Step 2:
Calling form url as
abc.com/deleteProductImage.php?catId=52limit=100start=0

Note: abc.com : your website.
          catId : pass category Id
         limit: how many product you want to delete.
         start : delete from product.




Magento. Listing Sub-Categories On A Category Page

Step 1 .
 create a "Static Block"
 and put in Content area below code.
{{block type="core/template" template="catalog/category/sub.phtml"}}

  



Step 2.
create "sub.phtml" file in  "/your template/catalog/category/sub.phtml"
 <div class="category-products">

<ul class="products-grid">
<?php
$category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
$categories = $category->getCollection()
->addAttributeToSelect(array('name', 'thumbnail'))
->addAttributeToFilter('is_active', 1)
->addIdFilter($category->getChildren());
$catDat =explode(',',$category->getChildren());
if(count($catDat)>0){
$categorycount = 0;
foreach($catDat as $catId){
$_category=Mage::getModel('catalog/category')->load($catId);

if($_category->getIsActive()){

if ($categorycount == 0){
$class = "first";
}elseif ($categorycount == 4){
$class = "last";
}else{
$class = "";
}
?>

<li class="item <?=$class?> catitm" align="center">
<div class="itemimg"><?php //echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>
<a href="<?php echo $_category->getURL() ?>" title="<?php echo $this->htmlEscape($_category->getName()) ?>"><img src="<?php  echo $_category->getImageUrl(); ?>" alt="<?php echo $this->htmlEscape($_category->getName()) ?>"     style="width: 425px !important;height: 425px;"/></a>
</div>
<h3><a href="<?php echo $_category->getURL() ?>" title="<?php echo $this->htmlEscape($_category->getName()) ?>"><?php echo $this->htmlEscape($_category->getName()) ?></a></h3>
</li>

<?php

if($categorycount == 4){
$categorycount = 0;
echo "</ul>\n\n<ul class=\"products-grid\">";
}else{
$categorycount++;
}


}


}

}?>

</ul>

</div>
Output is :



program to delete Products Image Magento

<?php
require_once "app/Mage.php";
umask(0);
Mage::app('admin');
Mage::setIsDeveloperMode(true);

$productCollection=Mage::getResourceModel('catalog/product_collection');
foreach($productCollection as $product){
echo $product->getId();
echo "<br/>";
         $MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
        echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
echo "<br/>";

$MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
echo "<pre>";
//print_r($MediaGallery);
echo "</pre>";

    foreach($MediaGallery as $eachImge){
        $MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
        $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
        $DirImagePath=str_replace("/",DS,$eachImge['file']);
        $DirImagePath=$DirImagePath;
        // remove file from Dir

        $io     = new Varien_Io_File();
         $io->rm($MediaCatalogDir.$DirImagePath);

        $remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
    }


}
?>

magento custom search

Step1. create search input box. when you want to applied

<div class="row srchby">
<div class="col-sm-12"><h3 class="blue-font" align="center">Search our database</h3></div>

<form role="search" action="<?=Mage::getBaseUrl()?>catalogsearch/result/" method="get" class="form-inline">
<input type="hidden" name="cat" id="searchCatId" value="<?=$categoryid?>" >
    <div class="form-group"><input type="text" name="q" class="form-control"  placeholder="Enter Part No. / Model No" id="searchCat" value=""></div>
<div class="form-group"><input type="submit" value="Search Now"></div>
</form>

</div>
<style>
#getproductCat{
    position: absolute;
z-index: 999;
margin-left: 27.90%;
margin-top: -2%;
display: none;
}
</style>
<div class="row">
<div id="getproductCat">
<div class="product_instant_search_popup clearfix">
  <a href="javascript:void(0)" onclick="removeddCatSearch()"><img src="<?php echo $this->getSkinUrl('images/FME_instantsearch/close.png');?>" alt="" class="close" width="20px"></a>
<?php 


$a=1;
?>

<div class="related">
<ul id="listCatSearch">

</ul>
</div>
</div>
</div>
</div>
Step 2. create ajax to call indexController 
<script>
// instantsearch is my module.
jQuery(document).on('keyup','#searchCat',function(obj){
var seaechData=jQuery(this).val();
var catId=jQuery('#searchCatId').val();
var dataString ='seaechData='+seaechData+'&catId='+catId;
//alert('asdasd'+seaechData);
var urlPost= '<?php echo $this->getUrl('instantsearch/index/searchcat')?>';
jQuery('#listCatSearch').html('');
jQuery.ajax({
type: "POST",
url: urlPost,
data: dataString,
cache: false,
success: function(result){
//alert(result);
jQuery('#getproductCat').show();
jQuery('#listCatSearch').html(result);
 
}
}); 
});
function removeddCatSearch(){
jQuery('#listCatSearch').html('');
jQuery('#getproductCat').hide();
}
</script>

Step 3:
create function in IndexController in any module

public function searchcatAction(){
if(!empty($_REQUEST['seaechData'])){
$q = $_REQUEST['seaechData'];
$categoryid = $_REQUEST['catId']; 
$category = new Mage_Catalog_Model_Category();
if(!empty($categoryid)){
$category->load($categoryid);
}
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
if(!empty($q)){
$collection->addAttributeToFilter('name', array('like' => '%'.$q.'%'));
}
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'))->limit(100);
$_productCollection=$collection;
//echo $_productCollection->count();
$result='';
if($_productCollection->count()>0){
foreach ($_productCollection as $_product){
$result.='<li id="is-'.$_product->getid().'">
<a href="'.$_product->getProductUrl().'">'.ucfirst($_product->getName()).'</a>

</li>';
}


}else{
$result.='<li id="is-0">No Recorde Found!</li>';
}
echo $result;
}
}



How display success message after submit the form


1.  Set Your Message.
             Mage::getSingleton("core/session")->addSuccess("Add success message"); 
             Mage::getSingleton("core/session")->addError("Please login");
            Mage::getSingleton("core/session")->addNotice("Add notification message");
2. Display Your Message Wherever You Want.(Optional If use custom Extension Or not Defined)

         <?php echo $this->getChildHtml('global_messages'); ?>

3. Define Block in Layout. (Optional If use custom Extension Or not Defined)
       <block type="core/messages" name="global_messages" as="global_messages"/>

magento to create SEO base URL pragmatically


Hear : "rushfee" is custom module;
we are create a custom link (SEO Link) like
 http://localhost/magento/rushfee/type/pingback/shape/round

$store_id=1;
$request_path = 'rushfee/type/pingback/shape/round' ;
$target_path='rushfee/index/index/type/pingback/shape/round';
$oUrlRewriteCollection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('target_path', $target_path); //check rewrite url exit or not
if(count($oUrlRewriteCollection)==0){
    echo "target path does exist";
 $rewriteModel = Mage::getModel('core/url_rewrite');
 $id_path =$target_path; //'rushfee/index/index/id/2';
 $rewriteModel->setData('request_path', $request_path);
 $rewriteModel->setData('target_path', $target_path);
 $rewriteModel->setData('id_path',$id_path);
// $rewriteModel->setOptions('RP');
 $rewriteModel->setData('store_id', $store_id);
 $rewriteModel->setData('is_system', 0);
 $rewriteModel->save();
}

you can get url data
echo $this->getRequest()->getParam('type');
echo $this->getRequest()->getParam('shape');

Use of $installer v $this in install scripts

$installer = $this;
you can uses instance of $this is 
$installer = new Mage_Eav_Model_Entity_Setup; 
or
$installer =new Mage_Catalog_Model_Resource_Setup;



$installer = new Mage_Sales_Model_Resource_Setup('core_setup');   
$installer->startSetup();

$installer->addAttribute("quote_address", "prepaiddiscount_total", array("type"=>"varchar"));
$installer->addAttribute("order", "prepaiddiscount_total", array("type"=>"varchar"));
$installer->endSetup();

add custom option in magento

$productId=ProductId
$proAdd=Mage::getModel('catalog/product')->load($productId);
$options =  array(
'is_delete' => 0,
'title' => 'addmorproduct',
'optgroup ' => 'text',
'type' => 'field',
'is_require' => 0,
'sort_order' => 0,
'pric' => 0.00,
'price_type' => 'fixed',
'sku' => '',
);

$optionInstance = $proAdd->getOptionInstance()->unsetOptions();
$proAdd->setHasOptions(1);
if (isset($options['is_require']) && ($options['is_require'] == 1)) {
$proAdd->setRequiredOptions(1);
}
$optionInstance->addOption($options);
$optionInstance->setProduct($proAdd);
$proAdd->save();

unset($optionInstance);
unset($proAdd);
echo $productId." Add options Successfully!</br> ";

Adding new Attribute option in magento

<?php $arg_attribute = "attribute code";
$dataArry=array('M','L','SL','XXL');

$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
foreach($dataArry as $dataVal){
$option['attribute_id'] = $attr_id;
$option['value'][][0] = $dataValh;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
}
?>

get shipping address , Billing address and item details by orderid programmatic in magento

<?php $orderId=$this->getOrderId();
 $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
 $shipping_address_data = $order->getShippingAddress();
      $billing_address_data = $order->getBillingAddress();
 $country1 = Mage::getModel('directory/country')->loadByCode($shipping_address_data['country_id']);
 $ctryname1=$country1->getName();
 $country2 = Mage::getModel('directory/country')->loadByCode($billing_address_data['country_id']);
 $ctryname2=$country2->getName();

 /**Billing and Shipping Information start**/
 $shipbillhtml='';
 $shipbillhtml.='<table class=orderconftab>';
 $shipbillhtml.='<tr><td><h3>Shipping Address</h3></td><td><h3>Billing Address</h3></td></tr>';
 $shipbillhtml.='<tr><td>'.$shipping_address_data['firstname'].' '.$shipping_address_data['lastname'].'</td><td>'.$billing_address_data['firstname'].' '.$billing_address_data['lastname'].'</td></tr>';
 $shipbillhtml.='<tr><td>'.$shipping_address_data['street'].'</td><td>'.$billing_address_data['street'].'</td></tr>';
 $shipbillhtml.='<tr><td>'.$shipping_address_data['city'].', '.$shipping_address_data['region'].', '.$shipping_address_data['postcode'].'</td><td>'.$billing_address_data['city'].', '.$billing_address_data['region'].', '.$billing_address_data['postcode'].'</td></tr>';
 $shipbillhtml.='<tr><td>'.$ctryname1.'</td><td>'.$ctryname2.'</td></tr>';
 $shipbillhtml.='<tr><td>'.$shipping_address_data['telephone'].'</td><td>'.$billing_address_data['telephone'].'</td></tr>';
      $shipbillhtml.='</table>';
      echo $shipbillhtml;
 /**Billing and Shipping Information end**/

 /**Payment Method Start**/
 $payment_method = $order->getPayment()->getMethodInstance()->getTitle();
      echo '<h3 class=orderconfpm>Payment Method</h3>';
      echo '<p>'.$payment_method.'<p>';
 /**Payment Method end**/
 /**Ordered Item Start**/
      $ordered_items = $order->getAllItems();
      echo '<table class=orderconfdetail>
    <thead>
   <th>Product Name</th>
<th class="a-center">Price</th>
<th class="a-center">Qty</th>
<th class="a-center">Subtotal</th>
</thead>';
      foreach($ordered_items as $item) {
$itemsubtotal=Mage::helper('core')->currency($item->getPrice()*$item->getQtyToInvoice());
$productId=$item->getProductId();
$product = Mage::getModel('catalog/product')->load($productId);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$thumbnailUrl = $productMediaConfig->getMediaUrl($product->getThumbnail());
$productImage='<img src="'.$thumbnailUrl.'" height="50px" />';
echo '<tr>';
echo '<td>'.$productImage.$item->getName().'</td>';
echo '<td>'.Mage::helper('core')->currency($item->getPrice()).'</td>';
echo '<td>'.$item->getQtyToInvoice().'</td>';
echo '<td>'.$itemsubtotal.'</td>';
echo '</tr>';
}
echo '<tr><td colspan="3">Subtotal</td><td>'.Mage::helper('core')->currency($order->getSubtotal()).'</td></tr>';
echo '</table>';
echo '<h5 class="grand_total">Grand Total: '.Mage::helper('core')->currency($order->getBaseGrandTotal()).'</h5>';
/**Ordered Item end**/
 ?>

Get configurable product collection in magento

/* **
Get product Collection only configurable product
**
*/
                        $notAssocative=array();
$collectionConfigurable = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('type_id', array('eg'=>'configurable'));
foreach($collectionConfigurable->getData() as $notAss){
array_push($notAssocative,$notAss['entity_id']);
}
print_r($notAssocative);

get simple produt collection not associative product

$collection = Mage::getResourceModel('catalog/product_collection')
//->addAttributeToFilter('type_id', array('eg'=>'configurable'))
->addAttributeToFilter('type_id', array('eg'=>'simple'))
->addAttributeToSelect('*'); //or just the attributes you need

$collection->getSelect()->joinLeft(array('link_table' => 'catalog_product_super_link'),
'link_table.product_id = e.entity_id',array('product_id')
);

$collection->getSelect()->where('link_table.product_id IS NULL');
$notAssocative=array();
foreach($collection->getData() as $notAss){
array_push($notAssocative,$notAss['entity_id']);
}

print_r($notAssocative);

listing filterable options in product listing page in magento programmatically

<?php /*Create filter dependencies*/
$_filters = Mage::getSingleton('Mage_Catalog_Block_Layer_State')->getActiveFilters();
foreach ($_filters as $_filter){
echo '<div class="filters">'.$this->stripTags($_filter->getLabel()).'  <a href="'.$_filter->getRemoveUrl().'" title="Remove This Item"> X </a> </div>';
} ?>
<?php
/* *Get catalog Max price nad min price*/
        if (!($currentCategory = Mage::registry('current_category'))) {
            $currentCategory = Mage::getModel('catalog/category')->load(Mage::app()->getStore()->getRootCategoryId());
        }
$max_price=Mage::getSingleton('catalog/layer')->setCurrentCategory($currentCategory)->getProductCollection()->getMaxPrice();
   $minPrice=Mage::getSingleton('catalog/layer')->setCurrentCategory($currentCategory)->getProductCollection()->getMinPrice();

/** show catalog filtering Customize */
$_category = $currentCategory;
$category_id= $_category->getId();

$layer = Mage::getModel("catalog/layer");
$category = Mage::getModel("catalog/category")->load($category_id);
$layer->setCurrentCategory($category);
$attributes = $layer->getFilterableAttributes();


$filter='';
$filterList='';
foreach($attributes as $attribute){
if($attribute->getAttributeCode() == 'price'){
$filterBlockName = 'catalog/layer_filter_price';
}elseif($attribute->getBackendType() == 'decimal'){
$filterBlockName = 'catalog/layer_filter_decimal';
}else{
$filterBlockName = 'catalog/layer_filter_attribute';
}
$result = Mage::app()->getLayout()->createBlock($filterBlockName)->setLayer($layer)->setAttributeModel($attribute)->init();

$count = count($result->getItems());
if($count > 0){
if($attribute->getAttributeCode() == 'price'){

$filterList.='<div class="col-sm-4 col-md-4">
<div class="accordian_menu">
<a href="javascript:void(0)" class="heading">'.$attribute->getFrontendLabel().'<strong class="arrow"></strong>
</a>
<div class="submenu">
<div class="cheqbutton">
<div class="checkbox_btn">
<div class="range_slider padding_15">          
<input id="range_02" />
<script>
jQuery(document).ready(function () {
jQuery("#range_02").ionRangeSlider({
type: "double",                                          
min: '.$minPrice.',
max: '.$max_price.',
from: 0,
to: '.$max_price.',
postfix: "€"
});
});
</script>                          
 </div>
</div>
</div>

</div>
</div>
</div>';

}elseif($attribute->getAttributeCode() == 'shoes_color'){

$filterList.='<div class="col-sm-4 col-md-4">
<div class="accordian_menu">
<a href="javascript:void(0)" class="heading">Couleur<strong class="arrow"></strong>
</a>
<div class="submenu">
<div class="cheqbutton">
<div class="checkbox_btn">
<div class="color_style padding_15">
<ul>';
foreach($result->getItems() as $option) {
$filterList.=' <li class="color_box"><a href="'.$this->urlEscape($option->getUrl()).'" style="background:url('.Mage::helper('attributeoptionimage')->getAttributeOptionImage($option->getValue()).')"></a></li>';
}
$filterList.='</ul>
 </div>
</div>
</div>
</div>
</div>
</div>';

}elseif($attribute->getAttributeCode() == 'color'){
$filterList.='<div class="col-sm-4 col-md-4">
<div class="accordian_menu">
<a href="javascript:void(0)" class="heading">Couleur<strong class="arrow"></strong>
</a>
<div class="submenu">
<div class="cheqbutton">
<div class="checkbox_btn">
<div class="color_style padding_15">
<ul>';
foreach($result->getItems() as $option) {
$filterList.=' <li class="color_box"><a href="'.$this->urlEscape($option->getUrl()).'" style="background:url('.Mage::helper('attributeoptionimage')->getAttributeOptionImage($option->getValue()).')"></a></li>';
}
$filterList.='</ul>
 </div>
</div>
</div>

</div>
</div>
</div>';


}elseif($attribute->getAttributeCode() == 'shoes_size'){

$filterList.='<div class="col-sm-4 col-md-4">
<div class="accordian_menu">
<a href="javascript:void(0)" class="heading">'.$attribute->getFrontendLabel().'
<strong class="arrow"></strong>
</a>
<div class="submenu">
<div class="cheqbutton">
<div class="checkbox_btn">
<div class="size_list padding_15">
<ul>';
foreach($result->getItems() as $option) {
$filterList.='<li><a class="sizes" href="'.$this->urlEscape($option->getUrl()).'">'.$option->getLabel().'</a></li>';
}
$filterList.='</ul>
</div>
</div>
</div>

</div>
</div>
</div>';

}elseif($attribute->getAttributeCode() == 'size'){


$filterList.='<div class="col-sm-4 col-md-4">
<div class="accordian_menu">
<a href="javascript:void(0)" class="heading">'.$attribute->getFrontendLabel().'
<strong class="arrow"></strong>
</a>
<div class="submenu">
<div class="cheqbutton">
<div class="checkbox_btn">
<div class="size_list padding_15">
<ul>';
foreach($result->getItems() as $option) {
$filterList.='<li><a class="sizes" href="'.$this->urlEscape($option->getUrl()).'">'.$option->getLabel().'</a></li>';
}
$filterList.='</ul>
</div>
</div>
</div>

</div>
</div>
</div>';


}elseif($attribute->getAttributeCode() == 'marque'){


$filterList.='<div class="col-sm-4 col-md-4">
<div class="accordian_menu">
<a href="javascript:void(0)" class="heading">Marques
<strong class="arrow"></strong>
</a>
<div class="submenu">
<div class="cheqbutton">
<div class="checkbox_btn">';

$l=0;
$k=0;
foreach($result->getItems() as $option) {
//print_r($option->getData());
$_itemUrl = "'".$this->urlEscape($option->getMSelected() ? $option->getRemoveUrl() : $option->getUrl())."'";
if($l<2){
$filterList.='<div>
<input id="checkbox'.$l.'" type="checkbox" name="checkbox" value="1" ><label for="checkbox'.$l.'" onClick="serchFilter('.$_itemUrl.')"><span></span>'.$option->getLabel().'</label>
</div>';
}else{
if($k==0){
$filterList.='<a href="javascript:void(0)" class="drop">+ de Marques
<strong class="arrow"></strong>
</a>
<ul class="submenu">'; }

$filterList.='<li><div>
<input id="checkbox'.$l.'" type="checkbox" name="checkbox" value="1" ><label for="checkbox'.$l.'" onClick="serchFilter('.$_itemUrl.')"><span></span>'.$option->getLabel().'</label>
</div></li>';

$k++;
}
$l++;
}

$filterList.='</ul></div>

</div>

</div>
</div>
</div>';


}else{


}
}



}
echo $filterList;
?>

get Product Media image by productId Magento

 <?php $_images = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages(); ?>  
<?php if($_images){?>          
<?php $i=0; foreach($_images as $_image)
print_r($_image);
if ($i++ < 5) { $i++; ?>
<img class="gallery" src="<?php echo $this->helper('catalog/image')->init($product, 'thumbnail', $_image->getFile())->resize(255); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel());?>" title="<?php $this->htmlEscape($_image->getLabel());?>" />
<?php } ?>
<?php } ?>

getMedia Image By product Id in magento

  $_product = Mage::getModel('catalog/product')->load($product->getId());

  $product->getMediaGalleryImages();        // This returns nothing
  $_product->getMediaGalleryImages(); 
 
 
 
<?php
$model = Mage::getModel('catalog/product') //getting product model
$_product = $model->load($productid); //getting product object for particular product id
echo $_product->getShortDescription(); //product's short description
echo $_product->getDescription(); // product's long description
echo $_product->getName(); //product name
echo $_product->getPrice(); //product's regular Price
echo $_product->getSpecialPrice(); //product's special Price
echo $_product->getProductUrl(); //product url
echo $_product->getImageUrl(); //product's image url
echo $_product->getSmallImageUrl(); //product's small image url
echo $_product->getThumbnailUrl(); //product's thumbnail image url  
?>