Magento Coding Solutions

add customoptions in product programmatic

<?php $mageFilename = 'app/Mage.php';
    require_once $mageFilename;
    Mage::App();

$module=Mage::getModel('catalog/product')->getCollection();

foreach($module as $_product){
$productId=$_product->getId();
//echo "</br>";
$options =  array(
        'is_delete' => 0,
        'title' => 'addmorproduct',
        'optgroup ' => 'text',
        'type' => 'field',
        'is_require' => 0,
        'sort_order' => 0,
        'pric' => 0.00,
        'price_type' => 'fixed',
        'sku' => '',      
       );
     $proAdd = Mage::getModel('catalog/product')->load($productId);
$flage=0;
foreach ($proAdd->getOptions() as $option) {
//$optionValue = $option->getId();
//echo $option->getGroupByType().'--';
if($option->getGroupByType()=='text'){
//echo $option->getTitle();

// echo $options['title'].'=='.$option->getTitle();
// echo "</br>";
if($options['title']==$option->getTitle()){
 $optionId = $option->getId();
 $flage++;
break;
}else{
$flage=0;
}
}
}
echo 'flage'.$flage;
if($flage==0){
//echo 'Insert';
$optionInstance = $proAdd->getOptionInstance();
 $proAdd->setHasOptions(1);
 if (isset($options['is_require']) && ($options['is_require'] == 1)) {
$proAdd->setRequiredOptions(1);
 }
 $optionInstance->addOption($options);
 $optionInstance->setProduct($proAdd);
 $proAdd->save();
 $flage=0;
}
}

delete order items in magento

<?php require 'app/Mage.php';
Mage::app('admin')->setUseSessionInUrl(false);                                                                                                              
//replace your own orders numbers here:
$test_order_ids=array('100000001','100000002','100000003');
foreach($test_order_ids as $id){
    try{
        Mage::getModel('sales/order')->loadByIncrementId($id)->delete();
        echo "order #".$id." is removed".PHP_EOL;
    }catch(Exception $e){
        echo "order #".$id." could not be remvoved: ".$e->getMessage().PHP_EOL;
    }
}
echo "complete."
?>

magento call a .phtml file in template

 .phtml file location is "opc/onepage/incart.phtml" is location

echo $this->getLayout()->createBlock('core/template')->setTemplate('opc/onepage/incart.phtml')->toHtml();

how to get cart total in custom php page in magento

<?php
    $mageFilename = '../app/Mage.php';
    require_once $mageFilename;
    Mage::init();
$coreSession = Mage::getSingleton('core/session', array('name' => 'frontend'));

 $cart = Mage::getModel('checkout/cart')->getQuote();
 $pricecartTotal=0;
    foreach ($cart->getAllItems() as $item) {
       $productName = $item->getPrice();
  $pricecartTotal=$pricecartTotal+$item->getPrice();
       //echo $productPrice = $item->getProduct()->getPrice();
       //echo $productName = $item->getProduct()->getName();
    }

/* $cartObjTotal= Mage::getModel('checkout/cart')->getQuote();
$pricecartTotal=0;
foreach($cartObjTotal->getAllItems() as $item) {
$pricecartTotal=$pricecartTotal+$item->getPrice();
} */
echo number_format($pricecartTotal,2)
?>

change cart price Programmatically in magento

 foreach($this->getQuote()->getAllItems() as $item) {

 $productId = $item->getProductId();
 $product = Mage::getModel('catalog/product')->load($productId);
 //if($product->getAttributeText('is_dummy') == 'Yes') {
$price = 2;
$item->setCustomPrice($price);
// we need this since Magento 1.4
$item->setOriginalCustomPrice($price);

// }
}
$this->getQuote()->save();


or

$cartObj= Mage::getModel('checkout/cart')->getQuote();
foreach($cartObj->getAllItems() as $item) {
//echo "CART ID:".$item->getId();
// echo $productId = $item->getProductId();
 $product = Mage::getModel('catalog/product')->load($productId);
 //  if($item->getId()== 2) {
$price = 20;
$item->setCustomPrice($price);
// we need this since Magento 1.4
$item->setOriginalCustomPrice($price);

     // }
}
$cartObj->save();

Database server does not support the InnoDB storage engine when i install magento


location : app\code\core\Mage\Install\Model\Installer\Db\Mysql4.php

Replace below code
 public function supportEngine()
    {
        $variables  = $this->_getConnection()
            ->fetchPairs('SHOW VARIABLES');
        return (!isset($variables['have_innodb']) || $variables['have_innodb'] != 'YES') ? false : true;
    }

 To  this code
public function supportEngine()
{
$variables  = $this->_getConnection()
->fetchPairs('SHOW ENGINES');
return (isset($variables['InnoDB']) && $variables['InnoDB'] != 'NO');
}

add custom options programmatic

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

),

);

$proAdd = Mage::getModel('catalog/product')->load($productId);
$optionInstance = $proAdd->getOptionInstance();

foreach($options as $option){

$proAdd->setHasOptions(1);

if (isset($option['is_require']) && ($option['is_require'] == 1)) {
$proAdd->setRequiredOptions(1);
}

$optionInstance->addOption($option);
$optionInstance->setProduct($proAdd);
$proAdd->save();
}

custom magento massage


$urld='your custom url';
 Mage::getSingleton('core/session')->addSuccess("Your request for product was Deactivate");
Mage::app()->getFrontController()->getResponse()->setRedirect($urld);

How can we add in code a product to the cart with a custom option type file in Magento?

It works in Magento 1.7 but I haven't tested it on another versions

// the path of the file, relative to Magento base directory.
// For example /media/image.jpg
$image = "YOURFILE.JPG";
// the ID of the product
$product_id  = XXX;

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

$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
    'product' => $product_id,
    'qty' => 1,
    'options' => array(
        12345 => array(
                'quote_path' => $image,
                'secret_key' => substr(md5(file_get_contents(Mage::getBaseDir() . $image)), 0, 20)),
    )
);

$cart->addProduct($product, $params);
$cart->save();

Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

delete order items by order Id in magento

<?php
       $order_id=7;
$order = Mage::getModel('sales/order')->load($order_id);
$base_grand_total = $order->getBaseGrandTotal();
    $base_subtotal = $order->getBaseSubtotal();
$grand_total = $order->getGrandTotal();
    $subtotal = $order->getSubtotal();
    $base_subtotal_incl_tax = $order->getBaseSubtotalInclTax();
    $subtotal_incl_tax = $order->getSubtotalInclTax();
    $total_item_count = $order->getTotalItemCount();
    $items = $order->getAllItems();
    foreach($items as $item){      

        if($item->getParentItemId() == '' || $item->getParentItemId() == null){

            $product_id = $item->getProductId();

/************Deleted Condition *************/
$catId=$item->getQuote_item_id();
$read= Mage::getSingleton('core/resource')->getConnection('core_read');
$value=$read->query("Select * from  mpb_sales_flat_quote_item_option where item_id='".$catId."'");
$row = $value->fetch();
 //print_r($row);

/**************************/
//echo "CODE=====".$row['code'];
                      /************ Apply your won condition ************************/
if($row['code']!='incart'){        
            //remove item price from total price of order
            $item_price = $item->getPrice();
            $item->delete();

            $order->setBaseGrandTotal($base_grand_total-$item_price);
            $order->setBaseSubtotal($base_subtotal-$item_price);
                $order->setGrandTotal($grand_total-$item_price);
            $order->setSubtotal($subtotal-$item_price);

            $order->setBaseSubtotalInclTax($base_subtotal_incl_tax-$item_price);
            $order->setSubtotalInclTax($subtotal_incl_tax-$item_price);
            $order->setTotalItemCount($total_item_count-1);
            $order->save();

            }

        }

    }
?>

Magento Ordered Items delete

<?php
       $order_id=7;
$order = Mage::getModel('sales/order')->load($order_id);
$base_grand_total = $order->getBaseGrandTotal();
    $base_subtotal = $order->getBaseSubtotal();
$grand_total = $order->getGrandTotal();
    $subtotal = $order->getSubtotal();
    $base_subtotal_incl_tax = $order->getBaseSubtotalInclTax();
    $subtotal_incl_tax = $order->getSubtotalInclTax();
    $total_item_count = $order->getTotalItemCount();
    $items = $order->getAllItems();
    foreach($items as $item){      

        if($item->getParentItemId() == '' || $item->getParentItemId() == null){

            $product_id = $item->getProductId();

/************Deleted Condition *************/
$catId=$item->getQuote_item_id();
$read= Mage::getSingleton('core/resource')->getConnection('core_read');
$value=$read->query("Select * from  mpb_sales_flat_quote_item_option where item_id='".$catId."'");
$row = $value->fetch();
//print_r($row);

/**************************/
//echo "CODE=====".$row['code'];
                      /************ Apply your won condition ************************/
if($row['code']!='incart'){        
            //remove item price from total price of order
            $item_price = $item->getPrice();
            $item->delete();

            $order->setBaseGrandTotal($base_grand_total-$item_price);
            $order->setBaseSubtotal($base_subtotal-$item_price);
                $order->setGrandTotal($grand_total-$item_price);
            $order->setSubtotal($subtotal-$item_price);

            $order->setBaseSubtotalInclTax($base_subtotal_incl_tax-$item_price);
            $order->setSubtotalInclTax($subtotal_incl_tax-$item_price);
            $order->setTotalItemCount($total_item_count-1);
            $order->save();

            }

        }

    }
?>

how to get attribute position by attribute option id in magento

      $attributeId = 134;
$collection =Mage::getResourceModel('eav/entity_attribute_option_collection')
                ->setPositionOrder('asc')
                ->setAttributeFilter($attributeId)
->addFilter('option_id',5)
               // ->setStoreFilter(0)
                ->load();
                echo "<pre>";
                //print_r($collection);
foreach($collection as $va){
print_r($va->getData());
}


-------------------------------------------------
$attributeId = 134;
$collection =Mage::getResourceModel('eav/entity_attribute_option_collection')
                ->setPositionOrder('asc')
               // ->setAttributeFilter($attributeId)
->addFilter('option_id',5)
               // ->setStoreFilter(0)
                ->load();
                echo "<pre>";
                //print_r($collection);
foreach($collection as $va){
print_r($va->getData());
}

Get Associated Products By product id

$pid=5; //Note: should be Conferrable product Id


$product = Mage::getModel('catalog/product')->load($pid);
$associatedProducts=$product->getTypeInstance()->getUsedProducts();
foreach($associatedProducts as $associatedProduct){
              // print_r($associatedProduct->getData());
$cid=$associatedProduct->getEntity_id();

                }

same product Add to cart as different product in magento

$asspId=2; //product Id
"testpricez" behave as option

$proAdd=Mage::getModel('catalog/product')->load($asspId);
$randT=rand(time(),10);
$renDta=$asspId.'_'.$randT;
$proAdd->addCustomOption('testpricez', $renDta);
$cart = Mage::getSingleton('checkout/cart');
$cart->addProduct($asspId, array(
'qty' => $qty,
)
);
$cart->save();

magento redirect url

$redirectUrl=abc.com/module name
Mage::app()->getFrontController()->getResponse()->setRedirect($redirectUrl);

with arguments
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl($path, $arguments));

magento getUrl custom module without index/index/

"designeruser" ia a custom module rewrite Url
http://localhost/magentotest/designeruser/index/index/id/1/ to
http://localhost/magentotest/designeruser/id/1/

$store_id=1;
$request_path = 'designeruser/id/2/' ;
$target_path='designeruser/index/index/id/2';
$oUrlRewriteCollection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('target_path', $target_path);
if(count($oUrlRewriteCollection)==0){
    echo "target path does exist";
$rewriteModel = Mage::getModel('core/url_rewrite');
$id_path ='designeruser/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();
}

magento rewrite url

"designeruser" ia a custom module rewrite Url
http://localhost/magentotest/designeruser/index/index/id/1/ to
http://localhost/magentotest/designeruser/id/1/



$store_id=1;

$request_path = 'designeruser/id/2/' ;
$target_path='designeruser/index/index/id/2';
$rewriteModel = Mage::getModel('core/url_rewrite');
$id_path ='designeruser/index/index/id/2';
$rewriteModel->setData('request_path', $request_path);
$rewriteModel->setData('target_path', $target_path);
$rewriteModel->setData('id_path',$id_path);
$rewriteModel->setData('store_id', $store_id);
$rewriteModel->setData('is_system', 0);
$rewriteModel->save();




$store_id=1;
$request_path = 'designeruser/id/2/' ;
$target_path='designeruser/index/index/id/2';
$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 ='designeruser/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();
}

Magento get url with or without parameters

Magento lets you get url with or without parameters as below:
// get base url
Mage::getUrl()
// http://dltr.org/

// get base url and index.html page
Mage::getUrl('index.html')
// http://dltr.org/index.html

// get brands page with id parameter
Mage::getUrl('brands/brand', array('id' => 1));
// http://dltr.org/brands/brand/id/1

// get secure url
Mage::getUrl('brands/brand', array('id' => 1,'_secure' => true));
// https://dltr.org/brands/brand/id/1

// or get secure url based on current page. good for ajax urls.
Mage::getUrl('brands/brand', array('id' => 1,'_secure' => Mage::app()->getStore()->isCurrentlySecure()));
// http(s)?://dltr.org/brands/brand/id/1



 But i used this code not working 
when add magento "rewrite" then working propely

You can use Below code 

$store_id=1;
$request_path = 'designeruser/id/2/' ;
$target_path='designeruser/index/index/id/2';
$oUrlRewriteCollection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('target_path', $target_path);
if(count($oUrlRewriteCollection)==0){
    echo "target path does exist";
 $rewriteModel = Mage::getModel('core/url_rewrite');
 $id_path ='designeruser/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(); 
} 


how to call phtml file in static block in magento


 /*****File Location :
  /public_html/new/app/design/frontend/default/default/template/easytabs/catalogproductrelatedright.phtml
*****/
call in STATIC BLOCK
{{block type="core/template" name="catalogproductrelatedright" template="easytabs/catalogproductrelatedright.phtml"}}

{{block type="core/template"  template="easytabs/catalogproductrelatedright.phtml"}}

RELATED PRODUCT CALL IN STATIC BLOCK

{{block type="catalog/product_list_related" name="catalog.product.related" before="-"  template="catalog/product/list/related.phtml" }}


IN CATALOG XML
<block type="catalog/product_list_related" name="catalog.product.related" before="-" template="catalog/product/list/related.phtml"/>

Get Product by Category Id

<style> .prodectDiv{background: none repeat scroll 0 0 #F2F2F2; float: left; height: 140px;  margin: 5px; padding: 2px;  text-align: center;  width: 140px;}
.pname{pading-top:1px; text-align:center;}
.pname a{color: #fff;}
</style>

<div style="float:left;width:100%;" >
<?php
//echo "<pre>";
$categoryid = 40;
$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
//echo "Design".count($collection);
$i=1;
foreach($collection as $_product){?>
<div class="prodectDiv" >
<a href="<?php echo $_product->getProductUrl() ?>"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(120); ?>" width="120" height="120" alt="" /></a>
<p class="pname" >
<a href="<?php echo $_product->getProductUrl(); ?>"><?php echo substr($_product->getName(),0,20); ?></a>
</p>
</div>
<?php


$i++;
} ?>
</div>

get page Type

Magento get current page name: like(catalog,checkout )

$page_type = Mage::app()->getFrontController()->getRequest()->getRouteName();
if($page_type=='cms'){ $page_type=str_replace('/','-_-',Mage::getSingleton('cms/page')->getIdentifier()); }
echo $page_type;

associative product Id by super_attribute in magento


Example:
          $productId=40/* Configrabel Product Id*/
         $option= array(140=>20,141=>16,142=>30); /*super_attribute Id In array*/

$productId=$_REQUEST['product'];
$option=$_REQUEST['super_attribute'];
$product=Mage::getModel('catalog/product')->load($productId);
$optionvalue=$option;
if($product->getTypeId() == "configurable"):
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($product);
$simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
foreach($simple_collection as $simple_product){
$Select_materials=$simple_product->getSelect_materials();
$Color_printed=$simple_product->getColor_printed();
$Number_of_side=$simple_product->getNumber_of_side();
$Select_size=$simple_product->getSelect_size();
$Hole=$simple_product->getHole();
if (in_array($Select_materials, $optionvalue)) {
  if (in_array($Color_printed, $optionvalue)) {
if (in_array($Number_of_side, $optionvalue)) {
  if (in_array($Select_size, $optionvalue)) {
if (in_array($Hole, $optionvalue)) {
$simpleproductId=$simple_product->getId();
$assPro=Mage::getModel('catalog/product')->load($simpleproductId);
return $simpleproductId.','.$assPro->getWidth().','.$assPro->getHeight();
break;
}
}
  }
}
 }
}
endif;

get associative product Id by super_attribute in magento


$proIdS=120 /* Configrabel Product Id*/
$childIds = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($proIdS);

$asso='';
foreach($childIds[0] as $key=>$val)
{
//echo $val;
//echo "====";
$associatedProduct = Mage::getModel('catalog/product') ->load($val);
$assProduct_color=$associatedProduct->getProduct_color();
$assProduct_size=$associatedProduct->getProduct_size();
$assDecoration_type=$associatedProduct->getDecoration_type();

//echo $assDecoration_type.'===='.$assProduct_color.'==='. $assProduct_size;
//echo "<pre></br>";
$matchAss=object;
$matchAss=array('140'=>$assDecoration_type,'141'=>$assProduct_color,'142'=>$assProduct_size);

//print_r($matchAss);



$flag = true;

foreach($super_attribute as $keyAs=>$valAs){
if($valAs!=$matchAss[$keyAs]){
$flag = false;
break;
}
}
if($flag){
$asso = $val;
break;
}
}
echo $asso;

Delete product from cart programmatically magento



$id = '969'; // replace product id with your id

$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach($items as $item):
if($item->getProduct()->getId() == $id):
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
endif;
endforeach; 

Retrieve attribute code in configurable product in magento

echo $_attribute->getProductAttribute()->getAttributeCode();
Mage::getModel('eav/entity_attribute')->load($_attribute->getAttributeId())->getAttributeCode();


/**
 * get attribute collection
 */
$attribute = $_product->getResource()->getAttribute('my_attribute');
/**
 * get attribute type
 */
$attribute->getAttributeType();
/**
 * get attribute Label
 */
$attribute->getFrontendLabel();
/**
 * get attribute default value
 */
$attribute->getDefaultValue();
/**
 * check if the attribute is visible
 */
$attribute->getIsVisible();
/**
 * check if the attribute is required
 */
$attribute->getIsRequired();
/**
 * get attribute value
 */
$attributeValue = Mage::getModel('catalog/product')->load($_product->getId())->getMyAttribute();

get all product in cart item magento

$cart = Mage::getSingleton('checkout/cart');
$productIds = array();
foreach($cart->getQuote()->getAllVisibleItems() as $item) {
$productIds[] = $item->getProduct()->getId();
}

echo "<pre>";
print_r($productIds);
echo "</pre>";

pdo_mysql extension is not installed


i am writing below code
    require_once("../../app/Mage.php");

Mage::app();

to occur error  



Fatal error: Uncaught exception 'Zend_Db_Adapter_Exception' with message 'The PDO extension is required for this adapter but the extension is not loaded' in /home/mp345/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php:342 Stack trace: #0 /home/mp345/public_html/lib/Zend/Db/Adapter/Abstract.php(247): Zend_Db_Adapter_Pdo_Abstract->setFetchMode(2) #1 /home/mp345/public_html/app/code/core/Mage/Core/Model/Resource.php(165): Zend_Db_Adapter_Abstract->__construct(Array) #2 /home/mp345/public_html/app/code/core/Mage/Core/Model/Resource.php(110): Mage_Core_Model_Resource->_newConnection('pdo_mysql', Object(Mage_Core_Model_Config_Element)) #3 /home/mp345/public_html/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(320): Mage_Core_Model_Resource->getConnection('core_write') #4 /home/mp345/public_html/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(350): Mage_Core_Model_Resource_Db_Abstract->_getConnection('write') #5 /home/mp345/public_html/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(335): Mage_Core_Model_Res in /home/mp345/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php on line 342


solution

create a file php.ini in rootpath with code



extension=pdo.so;
extension=pdo_sqlite.so;
extension=sqlite.so;

extension=pdo_mysql.so;



Get product attribute label & value in Magento


$_product->getData('attribute_code')
AND 
if you need label of the product attribute
$_product->getAttributeText('attribute_code')
or 
$_product->getResource()->getAttribute('attribute_code')->getFrontend()->getValue($_product);

magento admin login information

$user = Mage::getSingleton('admin/session');
echo $userId = $user->getUser()->getUserId();
echo "</br>";
echo $userEmail = $user->getUser()->getEmail();
echo "</br>";
$userFirstname = $user->getUser()->getFirstname();
$userLastname = $user->getUser()->getLastname();
$userUsername = $user->getUser()->getUsername();
$userPassword = $user->getUser()->getPassword();

file upload in magento programaticaly

include("../app/Mage.php");
Mage::app();
$path = Mage::getBaseDir('media') . DS . 'clipart' . DS .'clipart'.DS;
$uploader = new Varien_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg','png','gif','jpeg','eps'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$destFile = $path.$_FILES['image']['name'];
$filename = $uploader->getNewFileName($destFile);
$uploader->save($path, $filename);