Add Label for New Product in Magento Product List

Add following code to display new label for new products.

<?php  $now = date(‘Y-m-d’);
$newsFrom= substr($_product->getData(‘news_from_date’),0,10);
$newsTo=  substr($_product->getData(‘news_to_date’),0,10);

if (($now>=$newsFrom && $now<=$newsTo)||($now>=$newsFrom && $newsFrom!=” && $newsTo==” ))
{?><img alt=”” src=”<?php echo $this->getSkinUrl(‘images/icon-new.png’);?>”><?php }?>

Add Dropdown Attribute Value in Magento Product Grid

If you have to show “size” dropdown attribute in magento product grid, then take following steps.

In _prepareCollection() function, add following line.

->joinAttribute(‘size’,’catalog_product/size’, ‘entity_id’, null,’left’, $store->getId())

OR

->addAttributeToSelect(‘size’)

Now, In _prepareColumns() function, add following code.

$attribute = Mage::getModel(‘eav/config’)->getAttribute(‘catalog_product’, ‘size’);
$options = array();
foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {
if($option[‘value’] != ”){
$options[$option[‘value’]] = $option[‘label’];
}
}
$this->addColumn(‘size’,
array(
‘header’=> Mage::helper(‘catalog’)->__(‘Size’),
‘width’ => ’80px’,
‘index’ => ‘size’,
‘type’  => ‘options’,
‘options’ => $options,
));

Thats it!!

Magento warning array_key_exists()

When you have face array_key_exists() type of error in Magento then please following below steps.

-> Open file app\code\core\Mage\Captcha\Model\Observer.php

-> Go to line no. 166.

-> Replace array_key_exists  function with  property_exists function.

Thats it….

 

 

 

Add Category Tree Structure in Magento

public function getCategories()
{
/*$category = Mage::getModel(‘catalog/category’);
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$arr = array();
if ($ids)
{
foreach ($ids as $id)
{
$cat = Mage::getModel(‘catalog/category’);
$cat->load($id);
//$arr[$id] = $cat->getName();
$arr[] = array(‘value’=> $id,’label’=> $cat->getName());
}
}
return $arr;    */
$categories = Mage::getModel(‘catalog/category’)
->getCollection()
->addAttributeToSelect(‘*’)
->addIsActiveFilter();

$all = array();
$prestr=”;
foreach ($categories as $c)
{
//$all[$c] = $c->getName();
$prestr=”;
$level=$c->getLevel();

if($level > 1){
for($i=1;$i< $level;$i++)
{
$prestr.=’- ‘;

}
}

$all[] = array(‘value’=> $c->getId(),’label’=> $prestr.$c->getName());
}

return $all;
}

 

Alternatively,

public function getCategories()
{
$model  =   Mage::getModel(‘catalog/category’);
$rootCategoryId = Mage::app()->getWebsite(true)->getDefaultStore()->getRootCategoryId();
$category = $model->load($rootCategoryId);

$result=array();
$all= Mage::helper(‘brand’)->getCategoriesCustom($category,$rootCategoryId,$result);
return $all;

}

In Data.php File,

public function getCategoriesCustom($parent,$curId,$result){

if($parent->getLevel() == 1){
$result[]=array(‘value’=> $curId,’label’=> $this->getCatNameCustom($parent));
}
else{
$result[]=array(‘value’=> $parent->getId(),’label’=> $this->getCatNameCustom($parent));
}

try{
$children = $parent->getChildrenCategories();

if(count($children) > 0){
foreach($children as $cat){
$result=$this->getCategoriesCustom($cat,$curId,$result);
}
}
}
catch(Exception $e){
return ”;
}
return $result;
}

public function getCatNameCustom($category){
$level = $category->getLevel();
$html = ”;
for($i = 0;$i < $level;$i++){
$html .= ‘-‘;
}
if($level == 1)    return $html.’ ‘.$this->__(“All Categories”);
else return $html.’ ‘.$category->getName();
}

 

 

Add Multiselect field in Magento Admin Form

Add following code into _prepareForm() function in Form.php file.

$fieldset->addField(‘news_id’, ‘multiselect’, array(
‘label’     => Mage::helper(‘designer’)->__(‘News’),
‘required’  => false,
‘style’      => ‘width:400px’,
‘name’      => ‘news_id’,
‘values’    => Mage::getSingleton(‘designer/news’)->getNewsAll(),
));

Create new file News.php in Model folder and add following code into this file.

class Namespace_Designer_Model_News extends Mage_Core_Model_Abstract{

public function getNewsAll(){
// $news1 = Mage::getModel(‘news/state’)->getCollection();
$result = array();
$news = Mage::getModel(‘news/state’)->getCollection();
foreach ($news as $news1)
{
$addressLabel = $news1->getTitle();
//if (($addressLabel = $news1->getTitle()))
$result[] = array(‘value’=>$news1->getId(),’label’=>$addressLabel);
}

return $result;

}
}

Add following code into saveAction() function in DesignerController.php file.

$news_id1 = $data[‘news_id’];
$news_id = implode(“,”, $news_id1);

Set this $news_id in $model collection.

For Example,

$model = Mage::getModel(‘designer/designer’);
$model->setData($data)->setDesignerOptionId($newOption[‘option_id’])->setDesignerId($newOption[‘option_id’])->setNewsId($news_id);

Now, Convert these news ids into array by following code.

For Example,

$latest_news_id = $designers[‘news_id’];

if (isset($latest_news_id)) {
$latest_news_id = explode(‘,’,$latest_news_id);
if (is_array($latest_news_id)) {
$latest_news_id = array_unique($latest_news_id);
}
}
$news1 = Mage::getModel(‘news/state’)->getCollection()->addFieldToFilter(‘id’, array(‘in’ => $latest_news_id))->setOrder(‘id’,’desc’);
$news1->getSelect()->limit(3)->order(‘rand()’);

Image Resize in Magento

<?php 
/* Image */
      $image_width = 216;
      $image_height = 109;
   $fileName = $post['image'];
   
    if(!file_exists("./media/blog/resized/".$image_width."x".$image_height))     mkdir("./media/blog/resized/".$image_width."x".$image_height,0777);
  
  $folderURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."blog/";
    $imageURL = $folderURL . $fileName;
   
 
    $basePath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS ."blog". DS . $fileName;
   $newPath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS ."blog". DS . "resized" . DS .$image_width."x".$image_height. DS . $fileName;
   
    //if width empty then return original size image's URL
   
        //if image has already resized then just return URL
        if (file_exists($basePath) && is_file($basePath) && !file_exists($newPath)) {
            
            $imageObj = new Varien_Image($basePath);
            $imageObj->constrainOnly(TRUE);
            $imageObj->keepAspectRatio(FALSE);
            $imageObj->keepFrame(TRUE);
            $imageObj->backgroundColor(array(255,255,255));
            $imageObj->resize($image_width, $image_height);
            $imageObj->save($newPath);
        }
      $resizedURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . "blog/resized" . '/' .$image_width."x".$image_height."/". $fileName;
?>

 <p><a href="<?php echo $post->getAddress(); ?>" ><img src="<?php echo $resizedURL; ?>" /></a></p>

Add Extra Menu Item and Links to System Configuration Section in Custom Module in Magento

Add following code in app/code/local/[Name_Space]/[Module_Name]/etc/config.xml for add extra  menu item.

<adminhtml>
<menu>
            <news module="news">
                <title>News</title>
                <sort_order>71</sort_order>               
                <children>
                    <items module="news">
                        <title>Manage Items</title>
                        <sort_order>0</sort_order>
                        <action>news/adminhtml_news</action>
                    </items>
                    <items1 module="news">
                        <title>Import News Data</title>
                        <sort_order>1</sort_order>
                        <action>adminhtml/system_config/edit/section/news</action>
                    </items1>
                </children>
            </news>
        </menu>
  </adminhtml>

Note that here news will be the same as section name in system.xml file.