Skip to content

Magento: My Favorite Functions List

this for copy paste purposes, i made this list since i fall in love with Magento,
here we go:

public function getProductCategory($cat_id)
{
$data = array();
$category = new Mage_Catalog_Model_Category();
$category->load($cat_id);
$prodCollection = $category->getProductCollection();
foreach ($prodCollection as $product) {

$obj = Mage::getModel(‘catalog/product’);
$_product = $obj->load($product->getId()); // Enter your Product Id in $product_id
if(($_product->getPrice()>0) && $_product->isSaleable()):

if(($_product->getSpecialPrice() < $_product->getPrice()) &&
($_product->getSpecialPrice()!=”)):
$discount = round(100 – (($_product->getSpecialPrice()/$_product->getPrice())*100),0);
else:
$discount = 0;
endif;
$flag = “”;

if(($_product->getNewsFromDate()!=”) || ($_product->getNewsToDate()!=”) )
$flag = “new”;

if($discount>0)
$flag = “save”;

$data[] = array(
“product_id”=>$product->getId(),
“product_name”=>$_product->getName(),
“short_desc”=>$_product->getShortDescription(),
“desc”=>$_product->getDescription(),
“price”=>$_product->getPrice(),
“special_price”=>$_product->getSpecialPrice(),
“final”=>$_product->getFinalPrice(),
“image_url”=>$_product->getImageUrl(),
“product_url”=>$_product->getProductUrl(),
“discount”=> $discount,
“news_from_date”=>$_product->getNewsFromDate(),
“news_to_date”=>$_product->getNewsToDate(),
“flag”=>$flag

);
endif;
}

return $data;

}

public function getProductNew()
{
$tmp = array();
$collection = Mage::getModel(‘catalog/product’)->getCollection()
->addAttributeToSelect(‘*’)
->addAttributeToFilter(‘news_from_date’, array(
‘notnull’ => true,
))
->addAttributeToFilter(‘news_to_date’, array(
‘notnull’ => true,
))
->addAttributeToSort(‘updated_at’, ‘DESC’);
foreach($collection as $items):
if(!empty($items[“news_from_date”]) && ($items->getPrice()>0) &&  $items->isSaleable()):

if(($items->getSpecialPrice() < $items->getPrice()) &&
($items->getSpecialPrice()!=”)):
$discount = round(100 – (($items->getSpecialPrice()/$items->getPrice())*100),0);
else:
$discount = 0;
endif;
$flag = “”;

if(($items->getNewsFromDate()!=”) || ($items->getNewsToDate()!=”) )
$flag = “new”;

if($discount>0)
$flag = “save”;

$tmp[] = array(
“nama”=>$items[“name”],
“nama2″=>$items->getName(),
“product_name”=>$items->getName(),
“short_desc”=>$items->getShortDescription(),
“desc”=>$items->getDescription(),
“price”=>$items->getPrice(),
“special_price”=>$items->getSpecialPrice(),
“final”=> $items->getFinalPrice()<1 ? $items->getPrice() : $items->getFinalPrice() ,
“image_url”=>$items->getImageUrl(),
“product_url”=>$items->getProductUrl(),
“product_id”=>$items[“entity_id”],
“news_from_date”=>$items[“news_from_date”],
“news_to_date”=>$items[“news_to_date”],
“discount”=> $discount,
“flag”=>$flag

);
endif;
endforeach;
return $tmp;

}

public function getProductInfo($theId)
{
$obj = Mage::getModel(‘catalog/product’);
$_product = $obj->load($theId); // Enter your Product Id in $product_id

if(($_product->getSpecialPrice() < $_product->getPrice()) &&
($_product->getSpecialPrice()!=”)):
$discount = round(100 – (($_product->getSpecialPrice()/$_product->getPrice())*100),0);
else:
$discount = 0;
endif;
$flag = “”;

if(($_product->getNewsFromDate()!=”) || ($_product->getNewsToDate()!=”) )
$flag = “new”;

if($discount>0)
$flag = “save”;

$data = array(
“product_id”=>$_product->getId(),
“product_name”=>$_product->getName(),
“short_desc”=>$_product->getShortDescription(),
“desc”=>$_product->getDescription(),
“price”=>$_product->getPrice(),
“special_price”=>$_product->getSpecialPrice(),
“final”=>$_product->getFinalPrice(),
“image_url”=>$_product->getImageUrl(),
“product_url”=>$_product->getUrl(),
“discount”=> $discount,
“news_from_date”=>$_product->getNewsFromDate(),
“news_to_date”=>$_product->getNewsToDate(),
“flag”=>$flag

);
return $data;
}

public function cacheImage($product_id,$size)
{
$product_collection = Mage::getModel(‘catalog/product’)->load($product_id);
return Mage::helper(‘catalog/image’)->init($product_collection, ‘thumbnail’)->resize($size);
}

public function sendEmail()
{
//$emailSender = Mage::getSingleton(‘customer/session’)->getCustomer()->getEmail();
//$nameSender = Mage::getSingleton(‘customer/session’)->getCustomer()->getName();

$storeID = Mage::app()->getStore()->getStoreid();
$senderEmailAddr = Mage::getStoreConfig(‘trans_email/ident_support/email’,$storeID );
$senderName = Mage::getStoreConfig(‘trans_email/ident_support/name’, $storeID);

$templateId = Mage::getStoreConfig(‘mailreport/group/mailid’);
$sender = Array(‘name’  => $senderName,’email’ => $senderEmailAddr);

//$recipient = Array(‘name’  => $nameRecipient,’email’ => $emailRecipient);

$mailTemplate = Mage::getModel(‘core/email_template’);
$mailTemplate->setDesignConfig(array(‘area’=>’frontend’, ‘store’=>$storeID))
->sendTransactional(
$templateId,
$sender,
$recipient[’email’],
$recipient[‘name’],
array(‘data’ => $postObject)
);

}

public function kirimEmailSimple($msg,$subject,$recipient_name,$recipient_email)
{
$sender = Array(‘name’ => Mage::getStoreConfig(‘trans_email/ident_general/name’),
’email’ => Mage::getStoreConfig(‘trans_email/ident_general/email’));

$mail = Mage::getModel(‘core/email’);
$mail->setToName($recipient_name);
$mail->setToEmail($recipient_email);
$mail->setBody($msg);
$mail->setSubject($subject);
$mail->setFromEmail($sender[“email”]);
$mail->setFromName($sender[“name”]);
$mail->setType(‘html’);
$mail->send();
}

public function sqlExecute($sql)
{
Mage::getSingleton(‘core/resource’)->getConnection(‘core_write’)->query($sql);
}

public function fetchSql($query)
{
$resource = Mage::getSingleton(‘core/resource’);
$readConnection = $resource->getConnection(‘core_read’);
$results = $readConnection->fetchAll($query);

return $results;
}

public function currency($finalPrice)
{
return Mage::helper(‘core’)->currency($finalPrice, true, false);
}

public function isLoggedIn()
{
return Mage::getSingleton(‘customer/session’)->isLoggedIn();
}

public function getCurrencyCode()
{
return Mage::app()->getStore()->getCurrentCurrencyCode();
}

public function getCurrencySymbol()
{
return Mage::app()->getLocale()->currency(
Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();
}

public function getCurrentStoreCode()
{
return  Mage::app()->getStore()->getCode();
}

public function getItemsCount()
{
$val = Mage::getModel(‘checkout/cart’)->getQuote()->getItemsCount();

if(!$val){
return 0;
}else
return $val;

}
public function getQtyCount()
{

$val = Mage::getModel(‘checkout/cart’)->getQuote()->getItemsQty();

if(!$val){
return 0;
}else
return $val;
}

public function getSubTotal()
{
return Mage::getModel(‘checkout/cart’)->getQuote()->getSubtotal();
}

public function getGrandTotal()
{
return Mage::getModel(‘checkout/cart’)->getQuote()->getGrandTotal();
}

public function getJsUrl()
{
return Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
}

public function getMediaUrl()
{
return Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
}

public function getCurrentUrl()
{
return Mage::helper(‘core/url’)->getCurrentUrl();
}

public function getProductRatings($productId)
{

$reviews = Mage::getModel(‘review/review’)
->getResourceCollection()
->addStoreFilter(Mage::app()->getStore()->getId())
->addEntityFilter(‘product’, $productId)
->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
->setDateOrder()
->addRateVotes();
/**
* Getting average of ratings/reviews
*/
$avg = 0;
$ratings = array();
if (count($reviews) > 0) {
foreach ($reviews->getItems() as $review) {
foreach( $review->getRatingVotes() as $vote ) {
$ratings[] = $vote->getPercent();
}
}
$avg = array_sum($ratings)/count($ratings);
}

if(!$avg):
return 0;
else:
return $avg;
endif;
}

public function getSubCat($catID)
{
$datas = array();
$children = Mage::getModel(‘catalog/category’)->load($catID)->getChildren();
$children = explode(“,”,$children);
foreach ($children as $category) {
//echo $category->getName();
$mod = Mage::getModel(‘catalog/category’)->load($category);
$datas[] = array(
“id”=>$category,
“name”=>$mod->getName(),
“url”=>$mod->getUrl(),

);
}

return $datas;
}

public function getCurrentPageInfo()
{
$info = array(
“controller” => Mage::app()->getRequest()->getControllerName(),
“action” => Mage::app()->getRequest()->getActionName(),
“route” => Mage::app()->getRequest()->getRouteName(),
“module” => Mage::app()->getRequest()->getModuleName(),

);

return $info;
}

public function getCurrentCustomer(){
$cust = Mage::getSingleton(‘customer/session’)->getCustomer();
$addr =  Mage::getModel(‘customer/address’);
//print_r(Mage::getSingleton(‘customer/session’)->getCustomer()->getData());
$addr->load($cust->getDefaultBilling());
//print_r($addr->getData());
$cust_data = array(
“name”=> $cust->getName(),
“cust_id”=>$cust->getId(),
“email”=>$cust->getEmail(),
“phone”=> $addr->getTelephone()

);

return $cust_data;
}

public function modelInsert($model,$data){

Mage::getModel($model)->setData($data)->save();
}

public function modelUpdate($model,$id,$data){

Mage::getModel($model)->setId($id)->setData($data)->save();
}

public function modelDelete($model,$id){

Mage::getModel($model)->setId($id)->delete();
}

public function modelSelect($model,$id){

return Mage::getModel($model)->load($id);
}

public function getStaticBlock($blockId){
return Mage::app()->getLayout()->createBlock(‘cms/block’)->setBlockId($blockId)->toHtml();

}

public function isHomePage()
{
$routeName = Mage::app()->getRequest()->getRouteName();
$identifier = Mage::getSingleton(‘cms/page’)->getIdentifier();

if($routeName == ‘cms’ && $identifier == ‘home’) {
return 1;
} else {
return 0;
}

}

public function getTemplate($blocktype,$template_path)
{
if(!$blocktype)
$blocktype = ‘core/template’;

return Mage::app()->getLayout()->createBlock($blocktype)->setTemplate($template_path)->toHtml();
}

public function runAction()
{

$this->insertProduct(‘1112001’ , ‘1,50,57,94,144’ ,  ‘130’ ,  ‘PINCEAU BISEAUTE’ ,  ” ,  ” ,  ” ,  ” ,  ” ,  ” ,  ” ,  ‘1 g’ ,  ‘175000’ ,  ” ,  ‘1112002,1112003,1112004,1112005,1112006,1112007’ );

}

public function insertProduct($SKU,$CAT,$BRAND,$NAME,$COLOR,$SHADE,
$ACTION,$HOWTOUSE,$TYPES,$INGRD,$DESC,$SIZE,$RPRICE,$NOTES,$LINK)
{
$data = array(
‘type_id’ => ‘simple’,
‘sku’ => $SKU,
‘weight’ => 1,
‘name’ => $NAME,
‘bb_brand’ => $BRAND ,
‘color’ => $COLOR,
‘bb_typeofskin’ => $TYPES,
‘bb_shades’ => $SHADE,
‘bb_notes’ => $NOTES,

‘ob_size’ => $SIZE,
‘ob_product_code’ => $SKU,
‘ob_ingredients’ => $INGRD,
‘ob_howtouse’ => $HOWTOUSE,
‘ob_tips’ => $HOWTOUSE,
‘ob_action’ => $ACTION,

‘status’ => 1,
‘tax_class_id’ => 0,

‘attribute_set_id’ => 58,
‘description’ => $DESC,
‘short_description’ => $DESC,
‘price’=> $RPRICE

);

$stok = array(
‘manage_stock’ => 1,
‘is_in_stock’ => 1,
‘qty’ => 10,
‘use_config_manage_stock’ => 0
);
$cat_id = array();
$zCAT = explode(‘,’,$CAT);
foreach($zCAT as $vCAT)
$cat_id[] = $vCAT;

$waw = Mage::getModel(‘catalog/product’)->setData($data);
$waw->setStockData($stok);
$waw->setCategoryIds($cat_id);
$waw->setWebsiteIds(array(2));

/* set attribute disini */

//$waw->setData(‘ob_size’,’ SET DATA oB size’);

try
{
$waw->save();
echo ‘SUCCESS – PRODUCT NAME : ‘. $NAME.'<br>’;
//$this->setCrossUpSellSKU($waw->getId(),$LINK);
}
catch(Exception $e)
{
echo ‘FAILED – PRODUCT NAME : ‘. $NAME.'<br>’;
echo $e->getMessage();
}
/* set crossell & upsell */

}

public function cobaAction()
{
$mod = Mage::getModel(‘catalog/category’)->getCollection()
->addAttributeToSelect(‘*’)
// ->getData()
;
foreach($mod as $_categories):
$mod_cat = Mage::getModel(‘catalog/category’)->load($_categories->getId());
echo ‘<pre>’;
print_r($mod_cat->getData());
echo ‘</pre>’;

endforeach;

}

public function kategoriAction()
{
$mod = Mage::getModel(‘catalog/category’)->getCollection()
->addAttributeToSelect(‘*’)
// ->getData()
;
echo ‘category name,category id,parent id,path’.'<br>’;
foreach($mod as $_categories):
$mod_cat = Mage::getModel(‘catalog/category’)->load($_categories->getId());
//echo ‘<pre>’;
//print_r($mod_cat->getData());
//echo ‘</pre>’;
if($mod_cat->getLevel()>1)
{
/*
echo $mod_cat->getName().’,’. $mod_cat->getId().’,’. $mod_cat->getParentId().
‘,”‘. str_replace(‘/’,’,’,$mod_cat->getPath()).
‘”‘.'<br>’;
*/

echo $mod_cat->getName().
‘|’. str_replace(‘/’,’,’,$mod_cat->getPath()).’|’.$mod_cat->getId().
‘|’.$mod_cat->getLevel().
”.'<br>’;
}
endforeach;
}

public function atributAction()
{
$attr_model = Mage::getModel(‘catalog/resource_eav_attribute’);

//Load the particular attribute by id
//Here 73 is the id of ‘manufacturer’ attribute
$attr_model->load(970);

//$this->addAttributeOption(‘bb_shades’,’New value’);
//$this->addAttributeOption(‘bb_brand’,’New value’);

echo ‘<pre>’;
print_r($attr_model->getData());
echo ‘</pre>’;
}
public function linkAction()
{
/*
[link_type_id] => 4
4 upsell
5 crossell
*/
$mage = Mage::getModel(‘catalog/product_link’)->getCollection()
//->addAttributeToSelect(‘*’);
->addFieldToFilter(‘product_id’,183)
;

echo ‘<pre>’;
print_r($mage->getData());
}
public function produkAction()
{
$this->simpleProduct();
print ‘bikin udah’;
$cob = Mage::getModel(‘catalog/product’)->load(183);

echo ‘<pre>’;
print_r($cob->getData());
echo ‘</pre>’;
}

public function simpleProduct()
{
$data = array(
‘type_id’ => ‘simple’,
‘sku’ => ‘coba-sku2234324’,
‘weight’ => 1,
‘name’ => ‘coba ahh’,
‘ob_size’ => ‘ob size’,
‘ob_product_code’ => ‘product code here’,
‘ob_ingredients’ => ‘ob_ingredients here’,
‘ob_howtouse’ => ‘ob_howtouse here’,
‘ob_tips’ => ‘ob_tips here’,
‘ob_action’ => ‘ob_action here’,
‘status’ => 1,
‘tax_class_id’ => 0,
‘ob_howtouse’ => ‘ob_howtouse here’,
‘attribute_set_id’ => 58,
‘description’ => ‘desc here’,
‘short_description’ => ‘s desc here’,
‘price’=> 2

);
$stok = array(
‘manage_stock’ => 1,
‘is_in_stock’ => 1,
‘qty’ => 10,
‘use_config_manage_stock’ => 0
);
$cat_id = array(51,52);

$waw = Mage::getModel(‘catalog/product’)->setData($data);
$waw->setStockData($stok);
$waw->setCategoryIds($cat_id);
$waw->setWebsiteIds(array(2));

/* set attribute disini */

$waw->setData(‘ob_size’,’ SET DATA oB size’);

$waw->save();
echo ‘produk id nya: ‘.$waw->getId();

/* set crossell & upsell */

$this->setCrossUpSell($waw->getId(),’193,187,184,185’);

}

public function skuAction()
{

echo ‘get ID by sku ‘.Mage::getModel(‘catalog/product’)->getIdBySku(‘OB15’);
$mm = Mage::getModel(‘catalog/product’)

//->loadBySku(‘OB15’)
->loadByAttribute(‘sku’,’OB15′);
;
echo ‘<pre>’;
print_r($mm->getData());
}

public function runlinkAction()
{
$this->setCrossUpSellSKUSKU(‘OB104’, ‘OB121,OB78,OB141’);

}

public function setCrossUpSellSKUSKU($PID,$SKU)
{
$link_product = explode(‘,’,$SKU);

foreach($link_product as $val)
{
$prod_id = Mage::getModel(‘catalog/product’)->getIdBySku($val);
$SKU_PID = Mage::getModel(‘catalog/product’)->getIdBySku($PID);
try{
$this->setLinkBoth($SKU_PID,$prod_id);
echo ‘SUKSES : ‘.$PID.'<br>’;
}
catch(Exception $ww)
{
echo ‘GAGAL : ‘.$PID.'<br>’;
}
}
}

public function setCrossUpSellSKU($PID,$SKU)
{
$link_product = explode(‘,’,$SKU);

foreach($link_product as $val)
{
$prod_id = Mage::getModel(‘catalog/product’)->getIdBySku($val);
$this->setLinkBoth($PID,$prod_id);
}
}

public function setCrossUpSell($PID,$comma_pid)
{
$link_product = explode(‘,’,$comma_pid);

foreach($link_product as $val)
$this->setLinkBoth($PID,$val);

}

public function setLinkBoth($PID,$LINKED_ID)
{
$this->setLinkProduct($PID,$LINKED_ID,’crossell’);
$this->setLinkProduct($PID,$LINKED_ID,’upsell’);

}

public function setLinkProduct($PID,$LINKED_ID,$LINK_TYPE)
{
/*
4 upsell
5 crossell
*/
$link_type_ref = array(
‘upsell’ => 4,
‘crossell’ => 5,

);

$array = array(
‘product_id’ => $PID,
‘linked_product_id’ => $LINKED_ID,
‘link_type_id’ => $link_type_ref[$LINK_TYPE]
);

try{
Mage::getModel(‘catalog/product_link’)
->setData($array)
->save();
}
catch(Exception $ww)
{
echo ‘GAGAL DI : ‘.$LINKED_ID.'<br>’;
}
}

public function addAttributeOption($attribute_code, $attribute_value) {
$attribute_model = Mage::getModel(‘eav/entity_attribute’);
$attribute_options_model= Mage::getModel(‘eav/entity_attribute_source_table’) ;

$attribute_code = $attribute_model->getIdByCode(‘catalog_product’, $attribute_code);
$attribute = $attribute_model->load($attribute_code);

$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);

$value[‘option’] = array($attribute_value,$attribute_value);
$result = array(‘value’ => $value);
$attribute->setData(‘option’,$result);
$attribute->save();
}

public function getattributeAction()
{
$option_arr = array();
$attribute = Mage::getModel(‘eav/config’)->getAttribute(‘catalog_product’, ‘color’);
foreach ($attribute->getSource()->getAllOptions(false) as $option) {
//$option_arr[$option[‘value’]] = $option[‘label’];

echo $option[‘label’].’|’.$option[‘value’].'<br>’;
}

//echo ‘<pre>’;
//print_r($option_arr);
}

public function runcatAction()
{
$this->setCatBySku(‘1112001’ , ‘1,50,57,94,144,73,51’);
$this->setCatBySku(‘1112002’ , ‘1,50,57,94,144,73,51’);
$this->setCatBySku(‘1112003’ , ‘1,50,57,94,144,73,51’);

}

public function setCatBySku($SKU,$CAT_LIST)
{
$cat_id = array();
$zCAT = explode(‘,’,$CAT_LIST);
foreach($zCAT as $vCAT)
$cat_id[] = $vCAT;

$PIDs = Mage::getModel(‘catalog/product’)->getIdBySku($SKU);
$waw = Mage::getModel(‘catalog/product’)->setId($PIDs);
$waw->setCategoryIds($cat_id);

try
{
$waw->save();
echo ‘BERHASIL’;
echo ‘<br>’;
}catch(Exception $z)
{
echo ‘GAGAL’ . $z->getMessage();
echo ‘<br>’;
}
}

public function runimageAction()
{
$this->setImage(1,’img5.jpg’);
}

public function setImage($id,$filename)
{
$productData = Mage::getModel(‘catalog/product’)
->setId($id);

$importDir = Mage::getBaseDir(‘media’) . DS . ‘import’.DS;

$setImageType = array (‘image’, ‘small_image’, ‘thumbnail’);
//echo
$filePath = $importDir.$filename;
$productData->addImageToMediaGallery($filePath, $setImageType , false, false);

try{

$productData->save();

echo ‘BRASILLL’.'<br>’;
}
catch(Exception $zz)
{
echo ‘GAGAL yoo’.'<br>’;
}

}

public function removeImage($id)
{

$_product = Mage::getModel(‘catalog/product’)->load($id);
$mediaApi = Mage::getModel(“catalog/product_attribute_media_api”);
try {
$items = $mediaApi->items($_product->getId());
foreach($items as $item) {
$mediaApi->remove($_product->getId(), $item[‘file’]);
}

echo ‘IMAGE REMOVED’ . ‘<br>’;;
} catch (Exception $exception){
//var_dump($exception);
//die(‘Exception Thrown’);
echo ‘FAILED to REMOVE’ . ‘<br>’;;
}

$product = Mage::getModel(‘catalog/product’)->load($id);
//get all images
$mediaGallery = $product->getMediaGallery();
//if there are images
if (isset($mediaGallery[‘images’])){
//loop through the images
foreach ($mediaGallery[‘images’] as $image){
//set the first image as the base image
Mage::getSingleton(‘catalog/product_action’)->updateAttributes(array($product->getId()), array(‘image’=>$image[‘file’]), 0);
//stop
break;
}
}
}

Share

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *