Wednesday 2 December 2015

Magento Remove Decimals from product price

1 – Remove Decimals from product price in product and category page :

A – create currency class in path /app/code/local/Mage/Directory/Model/Currency.php
copy the content from file in core /app/code/core/Mage/Directory/Model/Currency.php and paste in your new file /app/code/local/Mage/Directory/Model/Currency.php

B – find this code in your new file (line 222)


return $this->formatPrecision($price, 2, $options, $includeContainer, $addBrackets);
and change with new line :
return $this->formatPrecision($price, 0, $options, $includeContainer, $addBrackets);


2 – For Remove Decimals from product price in product view page with custom options
A – create view class in path /app/code/local/Mage/Catalog/Block/Product/View.php
copy the content from file in core /app/code/core/Mage/Catalog/Block/Product/View.php and paste in your new file /app/code/local/Mage/Catalog/Block/Product/View.php
B – find this code in your new file (line 175)

$config = array(
            'productId'           => $product->getId(),
            'priceFormat'         => Mage::app()->getLocale()->getJsPriceFormat(),
            'includeTax'          => Mage::helper('tax')->priceIncludesTax() ? 'true' : 'false',
            'showIncludeTax'      => Mage::helper('tax')->displayPriceIncludingTax(),
            'showBothPrices'      => Mage::helper('tax')->displayBothPrices(),
            'productPrice'        => Mage::helper('core')->currency($_finalPrice, false, false),
            'productOldPrice'     => Mage::helper('core')->currency($_regularPrice, false, false),
            'priceInclTax'        => Mage::helper('core')->currency($_priceInclTax, false, false),
            'priceExclTax'        => Mage::helper('core')->currency($_priceExclTax, false, false),
            /**
             * @var skipCalculate
             * @deprecated after 1.5.1.0
             */
            'skipCalculate'       => ($_priceExclTax != $_priceInclTax ? 0 : 1),
            'defaultTax'          => $defaultTax,
            'currentTax'          => $currentTax,
            'idSuffix'            => '_clone',
            'oldPlusDisposition'  => 0,
            'plusDisposition'     => 0,
            'plusDispositionTax'  => 0,
            'oldMinusDisposition' => 0,
            'minusDisposition'    => 0,
            'tierPrices'          => $_tierPrices,
            'tierPricesInclTax'   => $_tierPricesInclTax,
        );
       
    and change with new line :
   
    $pf=Mage::app()->getLocale()->getJsPriceFormat();
        $pf['precision']=0;
        $pf['requiredPrecision']=0;
        $config = array(
            'productId'           => $product->getId(),
            'priceFormat'         => $pf,
            'includeTax'          => Mage::helper('tax')->priceIncludesTax() ? 'true' : 'false',
            'showIncludeTax'      => Mage::helper('tax')->displayPriceIncludingTax(),
            'showBothPrices'      => Mage::helper('tax')->displayBothPrices(),
            'productPrice'        => Mage::helper('core')->currency($_finalPrice, false, false),
            'productOldPrice'     => Mage::helper('core')->currency($_regularPrice, false, false),
            'priceInclTax'        => Mage::helper('core')->currency($_priceInclTax, false, false),
            'priceExclTax'        => Mage::helper('core')->currency($_priceExclTax, false, false),
            /**
             * @var skipCalculate
             * @deprecated after 1.5.1.0
             */
            'skipCalculate'       => ($_priceExclTax != $_priceInclTax ? 0 : 1),
            'defaultTax'          => $defaultTax,
            'currentTax'          => $currentTax,
            'idSuffix'            => '_clone',
            'oldPlusDisposition'  => 0,
            'plusDisposition'     => 0,
            'plusDispositionTax'  => 0,
            'oldMinusDisposition' => 0,
            'minusDisposition'    => 0,
            'tierPrices'          => $_tierPrices,
            'tierPricesInclTax'   => $_tierPricesInclTax,
        );


       
        3 – For Remove Decimals between store
A – create currency class in path /app/code/local/Mage/Core/Model/Store.php
copy the content from file in core /app/code/core/Mage/Core/Model/Store.php and paste in your new file /app/code/app/code/local/Mage/Core/Model/Store.php
B – find this code in your new file (line 991)


return round($price, 2);
and change with new line :

return round($price, 0);

4 -try the preview methode if you don’t have result ,
you can play too inside :
A – js/varien/js.js in code (line 222):


var precision = isNaN(format.precision = Math.abs(format.precision)) ? 2 : format.precision;
var requiredPrecision = isNaN(format.requiredPrecision = Math.abs(format.requiredPrecision)) ? 2 : format.requiredPrecision;
change to :


var precision = 0;
var requiredPrecision = 0;


B – lib/Zend/Currency.php (line 69) :

protected $_options = array(
        'position'  => self::STANDARD,
        'script'    => null,
        'format'    => null,
        'display'   => self::NO_SYMBOL,
        'precision' => 2,
        'name'      => null,
        'currency'  => null,
        'symbol'    => null,
        'locale'    => null,
        'value'     => 0,
        'service'   => null,
        'tag'       => 'Zend_Locale'
    );
change to :

protected $_options = array(
        'position'  => self::STANDARD,
        'script'    => null,
        'format'    => null,
        'display'   => self::NO_SYMBOL,
        'precision' => 0,
        'name'      => null,
        'currency'  => null,
        'symbol'    => null,
        'locale'    => null,
        'value'     => 0,
        'service'   => null,
        'tag'       => 'Zend_Locale'
    );



Related link:-
http://magento.stackexchange.com/questions/36600/remove-precision-from-price-of-a-product

Wednesday 25 November 2015

Get base product image path in Magento

echo Mage::getModel('catalog/product_media_config')
        ->getMediaUrl( $product->getImage() ); //getSmallImage(), getThumbnail()

Monday 16 November 2015

Magento programmatically add comment to order

// get the last order
$lastOrderId = $this->_getOnepage()->getCheckout()->getLastOrderId();
$order = Mage::getModel('sales/order')->load($lastOrderId);

// Add the comment and save the order (last parameter will determine if comment will be sent to customer)
$order->addStatusHistoryComment('This comment is programatically added to last order in this Magento setup');
$order->save();

Monday 2 November 2015

unique array in php

array_unique
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>



Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Getting Configurable Product from Simple Product ID in Magento

$simpleProductId = 465;
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
                  ->getParentIdsByChild($simpleProductId);

$product = Mage::getModel('catalog/product')->load($parentIds[0]);
echo $product->getId();

Monday 26 October 2015

Display associated posts on a Magento Product page

<?php echo $this->getLayout()
        ->createBlock('wordpress/post_associated')
            ->setTemplate("wordpress/post/associated.phtml")
            ->setTitle('Related Blog Posts')
            ->setEntity('product')
            ->setCount(5)
            ->toHtml() ?>
 Display associated products on a blog post page

                        <?php echo $this->getLayout()
    ->createBlock('wordpress/post_associated_products')
        ->setTemplate('wordpress/post/associated/products.phtml')
        ->setTitle('Related Products')
        ->toHtml() ?>

Monday 19 October 2015

How to remove white space around the product image in Magento

<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize(270,396); ?>" width="270" height="396"  />

Thursday 15 October 2015

Magento Log file created custom page

                $customererror='';               
                try {
                            $address->save();
                            $customer->save();
                        }                           
                         catch (Exception $ex) {
                            $customererror=$ex->getMessage();
                           
                            Mage::log($customererror,null,'customer.log');   
                        }

Monday 12 October 2015

Reading a file line by line in php

<?php
$handle = fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>

Monday 5 October 2015

Facebook image sharing

<meta property="og:title" content="<?php echo $Brand?>"/>
<meta property="og:image" content="<?php echo $imgurl.'?ts='.time();?>"/>
<meta property="og:image:secure_url" content="<?php echo $imgurl.'?ts='.time();?>"/>
<meta property="og:url" content="<?php echo $curUrl?>" />
<meta property="og:description" content="<?php echo $ProName?>"/>

================OR========================
<?php $product = Mage::registry('current_product');
if ($product): ?>
<meta property="og:title" content="<?php echo $product->getName(); ?>" />
<meta property="og:type" content="product" />
<meta property="og:url" content="<?php echo $this->helper('catalog/product')->getProductUrl($product); ?>" />
<meta property="og:image" content="<?php echo $this->helper('catalog/image')->init($product, 'image')->resize(300, 300); ?>" />
<meta property="og:description" content="<?php echo strip_tags($product->getShortDescription()); ?>" />
<meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName() ?>" />
<?php endif; ?>
================OR=========================
<?php /* Open Graph Protocol for Facebook and SEO START */ ?>
<?php if(Mage::registry('current_product')): ?>
 <?php $product = Mage::registry('current_product'); ?>
 <meta property="og:title" content="<?php echo ($product->getName()); ?>" />
 <meta property="og:type" content="product" />
 <meta property="og:image" content="<?php echo $this->helper('catalog/image')->init($product, 'small_image')->resize(200,200);?>" />
 <meta property="og:url" content="<?php echo Mage::registry('product')->getProductUrl(); ?>" />
 <meta property="og:description" content="<?php echo strip_tags(($product->getShortDescription())); ?>" />
 <meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName(); ?>" />
<?php elseif(Mage::registry('current_category')): ?>
 <meta property="og:title" content="<?php echo $this->getTitle() ?>" />
 <meta property="og:type" content="product.group" />
 <meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl();?>" />
 <meta property="og:description" content="<?php echo strip_tags($this->getDescription()) ?>" />
 <meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName(); ?>" />
<?php elseif((Mage::getSingleton('cms/page')->getIdentifier() == 'home' &&
 Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')) : ?>
 <meta property="og:title" content="<?php echo $this->getTitle() ?>" />
 <meta property="og:type" content="website" />
 <meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl();?>" />
 <meta property="og:description" content="<?php echo strip_tags($this->getDescription()) ?>" />
 <meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName(); ?>" />
<?php else: ?>
 <meta property="og:title" content="<?php echo $this->getTitle() ?>" />
 <meta property="og:type" content="article" />
 <meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl();?>" />
 <meta property="og:description" content="<?php echo strip_tags($this->getDescription()) ?>" />
 <meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName(); ?>" />
<?php endif; ?>
<?php /* Open Graph Protocol for Facebook and SEO END */ ?>

Friday 18 September 2015

Configurable product add to cart on custom page in magento


==============================Price============

 Price section :- <span class="con_price">
                <?php echo Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(); ?>
                </span>

=============================================
 <?php /*********Configurable product add to cart **********/ ?>
                               <?php
            $productAttributeOptions = $_product->getTypeInstance(true)
            ->getConfigurableAttributesAsArray($_product);
            $super_attributedcode='';
            $super_attributedfrontend_label='';
            $super_a_id='';
            foreach($productAttributeOptions as $supperattributed){
                $super_attributedcode=$supperattributed['attribute_code'];
                $super_a_id=$supperattributed['attribute_id'];
                $super_attributedfrontend_label=$supperattributed['frontend_label'];
            }
           
            $conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
            $childProducts = $conf->getUsedProductCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('status', array('eq' => 1))
            ->addFilterByRequiredOptions();
            ?>
           
            <span class="attributed_label"><?php echo $super_attributedfrontend_label; ?>: </span>
            <select class="con_productselectoption" name="con_productselectoption" id="con_product__<?php echo $_product->getId(); ?>">
            <?php
            foreach($childProducts as $_simproduct)
            {
                $sim_productid=$_simproduct->getId();
                $_sproduct= Mage::getModel('catalog/product')->load($sim_productid);
                $childPrice =  number_format($_sproduct->getPrice(),2);
                $childRetailPrice = number_format($_sproduct->getRetailPrice(),2);
                $childFinalPrice = number_format($_sproduct->getFinalPrice(),2);
               
                $attr = $_sproduct->getResource()->getAttribute($super_attributedcode);
                $option_id = $attr->getSource()->getOptionId($_sproduct->getAttributeText($super_attributedcode));
               
                $params = array(
               
                'product'=> $_product->getId(),
                Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => Mage::helper('core/url')->getEncodedUrl(),
                'form_key'=>Mage::getSingleton('core/session')->getFormKey()
                );
               
                $addToCartUrl= $this->getUrl("checkout/cart/add/", $params ).'?super_attribute['.$super_a_id.']='.$option_id;
               
            ?>
                 <option value="<?php echo $option_id; ?>" data-formatedprice="<?php echo Mage::helper('core')->currency($childFinalPrice, true, false); ?>" data-price="<?php echo $childFinalPrice; ?>"  data-carturl="<?php echo $addToCartUrl ?>"  ><?php echo $_sproduct->getAttributeText($super_attributedcode); ?></option>
                <?php
            }
           
            ?>
            </select>
           
            <a href="#" class="cls-add-to-cart" ><span><span><?php echo $this->__("Add To cart") ?></span></span></a>

================JQury=========================


    jQuery(document).ready(function(){
        var superattributedid='';
        var con_productid='';
        var option_price='';
   
    jQuery(".con_productselectoption").each(function(){
       
        option_price=jQuery(this).find("option:selected").data("formatedprice");
        jQuery(this).closest("li").find(".con_price").html(option_price);
        jQuery(this).closest("li").find(".cls-add-to-cart").attr("href",jQuery(this).find("option:selected").data("carturl"));
       
    });
   
    jQuery(".con_productselectoption").change(function(){
        option_price=jQuery(this).find("option:selected").data("formatedprice");
        jQuery(this).closest("li").find(".con_price").html(option_price);
        jQuery(this).closest("li").find(".cls-add-to-cart").attr("href",jQuery(this).find("option:selected").data("carturl"));
       
    });
    });

======================End=================








                     

Monday 17 August 2015

Phone number validation

<script type="text/javascript">
//<![CDATA[

  
    Validation.add('validate-mobile','<?php echo Mage::helper('contacts')->__('Please enter your mobile number.'); ?>',function (v, elm) {
          
        var reMax = new RegExp(/^maximum-length-[0-9]+$/);
        var reMin = new RegExp(/^minimum-length-[0-9]+$/);
      
        var result = true;
      
        if(Validation.get('IsEmpty').test(v))
        {
           result =false;
        }
      
      
        $w(elm.className).each(function(name, index) {
            if (name.match(reMax) && result) {
               var length = name.split('-')[2];
               result = (v.length <= length);
            }
            if (name.match(reMin) && result && !Validation.get('IsEmpty').test(v)) {
                var length = name.split('-')[2];
                result = (v.length >= length);
            }
          
        });
        return result;
    });
  
  
    var contactForm = new VarienForm('mobile_appForm',false);
  
  
  
 
//]]>
jQuery(document).ready(function(){
    var contactForm = new VarienForm('mobile_appForm',false);
    jQuery("#mobileappbuttom").click(function(e){
            if(contactForm.validator && contactForm.validator.validate()){
                e.preventDefault();
                var base_url=jQuery.trim(jQuery("#base_url").val());
                var mobile_number=jQuery("#mobile_number").val();
                jQuery.ajax({
                    url: base_url+'contacts/index/mobileapp/',
                    type:        'post',
                    data:({'mobile_number':mobile_number}),
                    success: function(msg){
                       jQuery("#aleart-text").text(msg);
                       //jQuery("#aleart-texterror").hide();
                        Effect.Appear('aleart-text', { duration: 0.2, delay: 1 });
                    }
                });
              
            }else {
                jQuery("#aleart-text").css({"display":"none"});
              //  jQuery("#aleart-texterror").text("Please enter your mobile number.");
            }
          
          
        });
  
    });
</script>

Thursday 6 August 2015

How to write mobile number length validation in magento by prototype

<input type="text" id="mobile" name="mobile" title="Mobile" class="input-text required-entry validate-length maximum-length-10 minimum-length-10 validate-digits">

how to get parent Category Id by sub category - Magento

echo $cat_idd = $this->getCurrentCategory()->getParentCategory()->getId();

=============================================
$pre_cat        =       Mage::getModel('catalog/category')->load($catarry[0]);
       
        $cat_idd   = $pre_cat->getParentCategory()->getId();

Monday 13 July 2015

Category attributed remove

 require_once("app/Mage.php");
 Mage::app('default');
 Mage::app()->setCurrentStore(
Mage_Core_Model_App::ADMIN_STORE_ID);
 $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
 $entityTypeId = $setup->getEntityTypeId('catalog_category');

 $setup->removeAttribute($entityTypeId,'category_video');

Wednesday 8 July 2015

Custom mail send

      //send coupon code by email start
                $to= $customer_mail;
                $sender=Mage::getStoreConfig('trans_email/ident_general/email');
                $subject="Dokan.in Coupon Code for FB Like";
                $logo_img= Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'/email/dokan-logo.png';
                $baseurl= Mage::getBaseUrl();
               
                $message .='<body style="font-family: Arial;">
                                <table cellpadding="0" cellspacing="0" border="0" width="650" align="center" style="border:1px solid #ccc;background:#ffffff">
                                    <tr><td height="20"></td></tr>
                                    <tr><td style="text-align: center;"><a href="'.$baseurl.'" target="_blank"><img src="'.$logo_img.'" alt="" /></a></td></tr>
                                    <tr><td style="font-weight: bold; font-size: 30px; color: #e32915; text-align: center;">Apply '.$couponCode.'in your next purchase.</td></tr>
                                    <tr><td height="50"></td></tr>
                                    <tr><td height="18"></td></tr>
                                    <tr><td style="text-align: center;"><a href="'.$baseurl.'" target="_blank" style="font-weight: bold; font-size: 44px; color: #0849ca; text-decoration: none;">www.dokan.in</a></td></tr>
                                    <tr><td style="padding:2px 0; font-size: 15px; font-weight: bold; color: #333; text-align: center;">BUY GROCERY &amp; VEGETABLES ONLINE</td></tr>
                                    <tr><td height="20"></td></tr>
                                    <tr><td style="padding:12px 0 10px; font-size: 15px; font-weight: bold; color: #333; text-align: center; background: #ffd21d;">DELIVERY AREA: CHANDANNAGAR, CHINSURAH, MANKUNDU</td></tr>
                                </table>
                            </body>';
                                    
                   $headers = "MIME-Version: 1.0" . "\r\n";
                   $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                   $headers .= 'From:Dokan.in coupon code<'.$sender . ">\r\n";
                   mail($to,$subject,$message,$headers);
               

Programmatically coupon code created in magento

                  $couponCode=Mage::helper('core')->getRandomString(16);
               
              
                $coupon = Mage::getModel('salesrule/rule');
                $coupon->setName("Coupon for ".$customer_mail." on ".date('Y-m-d H:i:s'))
               ->setDescription(null)
               ->setFromDate(date('Y-m-d'))
               ->setCouponType(2)
               ->setCouponCode($couponCode)
               ->setUsesPerCoupon(1)
               ->setUsesPerCustomer(1)
               ->setCustomerGroupIds(array(1,2,3,4))
               ->setIsActive(1)
               ->setStopRulesProcessing(0)
               ->setIsAdvanced(1)
               ->setProductIds('')
               ->setSortOrder(0)
               ->setSimpleAction('by_fixed')
               ->setDiscountAmount(250)
               ->setDiscountQty(null)
               ->setDiscountStep('0')
               ->setSimpleFreeShipping('0')
               ->setApplyToShipping('0')
               ->setIsRss(0)
               ->setWebsiteIds(array(1));
                $coupon->loadPost($coupon->getData());
                $coupon->save();

Tuesday 30 June 2015

Magento send mail load by template id

                        $post = array();
                        $post['customer'] = $finelurl;
                        $postObject = new Varien_Object();
                        $postObject->setData($post);
                        $emailTemplate  = Mage::getModel('core/email_template')->load(5); //Templated id Forgot Password
                       
                        $emailTemplate->setSenderName(Mage::getStoreConfig('trans_email/ident_general/name'));
                        $emailTemplate->setSenderEmail(Mage::getStoreConfig('trans_email/ident_general/email'));
                        $emailTemplate->setTemplateSubject('Password Reset Confirmation Hisconfe');
                        $emailTemplate->send($Secondaryemail, 'test', array('data' => $postObject));

Thursday 18 June 2015

New order email confirmation not being sent (magento 1.9.1)

If your mail system(smtp, zend_mail) works fine; disabling mailQueue may solve your problem.

/app/code/core/Mage/Core/Model/Email/Template.php
Change Line 407
if ($this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue) {

To
if (false /\*$this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue\*/) {


====================================================================
magento.stackexchange.com/questions/45571/new-order-email-confirmation-not-being-sent-magento-1-9-1

app/code/core/Mage/Checkout/Model/Type/Onepage.php line# 812 chnage $order->queueNewOrderEmail(); to $order->sendNewOrderEmail();

app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php line # change 1564 $order->queueNewOrderEmail(); to $order->sendNewOrderEmail();

Monday 15 June 2015

programmatically get the shipping tax by order increment id in magento

$order = Mage::getModel('sales/order')->loadByIncrementId("increment_id");
//shipping cost
$shippingCost = $order->getShippingAmount();
//shipping cost in base currency
$shippingBaseCost = $order->getBaseShippingAmount();
//shipping tax
$shippingTax = $order->getShippingTaxAmount();
//shipping tax in base currenty
$shippingBaseTax = $order->getBaseShippingTaxAmount();
//shipping cost including tax
$shippingCostIncludingTax = $order->getShippingInclTax();
//shipping cost including tax in base currency
$shippingBaseCostIncludingTax = $order->getBaseShippingInclTax();

Tuesday 9 June 2015

To get some basic order details, subtotal, shipping cost, discount, tax and grand total. Magento


$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);

echo "order subtotal: ".$order->getSubtotal()."<br>";
echo "shipping: ".$order->getShippingAmount()."<br>";
echo "discount: ".$order->getDiscountAmount()."<br>";
echo "tax: ".$order->getTaxAmount()."<br>";
echo "grand total".$order->getGrandTotal()."<br><br><br>";

Tuesday 12 May 2015

Magento Previous-Next Buttons on Product Details Page

<?php
// Prev-Next links $_product = $this->getProduct(); if(!$_product->getCategoryIds()) return; // if product is not in any category, do not display prev-next :)
$cat_ids = $_product->getCategoryIds(); // get all categories where the product is located
$cat = Mage::getModel('catalog/category')->load( $cat_ids[0] ); // load first category, you should enhance this, it works for me
$order = Mage::getStoreConfig('catalog/frontend/default_sort_by');
$direction = 'asc'; // asc or desc
$category_products = $cat->getProductCollection()->addAttributeToSort($order, $direction);
$category_products->addAttributeToFilter('status',1); // 1 or 2
$category_products->addAttributeToFilter('visibility',4); // 1.2.3.4
$cat_prod_ids = $category_products->getAllIds(); // get all products from the category
$_product_id = $_product->getId();
$_pos = array_search($_product_id, $cat_prod_ids); // get position of current product
$_next_pos = $_pos+1;
$_prev_pos = $_pos-1; // get the next product url
if( isset($cat_prod_ids[$_next_pos]) ) {
$_next_prod = Mage::getModel('catalog/product')->load( $cat_prod_ids[$_next_pos] );
} else {
$_next_prod = Mage::getModel('catalog/product')->load( reset($cat_prod_ids) ); } // get the prev product url
if( isset($cat_prod_ids[$_prev_pos]) )
{
$_prev_prod = Mage::getModel('catalog/product')->load( $cat_prod_ids[$_prev_pos] );
} else {
$_prev_prod = Mage::getModel('catalog/product')->load( end($cat_prod_ids) ); } ?>
<div>
    <?php if($_prev_prod != NULL): ?>
    <a href="<?php print $_prev_prod->getUrlPath();
    if($search_parameter):?>?search=1<?php endif;?>">
    <span><?php echo $this->__('Previous') ?></span></a>
    <?php endif; ?> <?php if($_next_prod != NULL): ?> <a href="<?php print $_next_prod->getUrlPath(); if($search_parameter):?>?search=1<?php endif;?>">
    <span><?php echo $this->__('Next') ?></span></a> <?php endif; ?>
</div> 

Magento - using getPriceHtml on custom page template

<?php $_product = Mage::getModel('catalog/product')->load($product->getId());
      $productBlock = $this->getLayout()->createBlock('catalog/product_price');
      echo $productBlock->getPriceHtml($_product);
 ?>

Loop through each character in a string in PHP

<?php
$str = "String to loop through"
$strlen = strlen( $str );
for( $i = 0; $i <= $strlen; $i++ ) {
$char = substr( $str, $i, 1 );
// $char contains the current character, so do your processing here
}
?>
Once I had the loop set up I simply added an is_ numeric() check and inserted a break command the first time the check returned false – here is my use case:
<?php
$str = "123?param=value"
$strlen = strlen( $str );
$id = "";
for( $i = 0; $i <= $strlen; $i++ ) {
$char = substr( $str, $i, 1 );
if( ! is_numeric( $char ) ) { break; }
$id .= $char;
}
// $id now contains the ID I need, in this case: 123
?>

Filter Product Collection for Multi Select Attribute Option value in Magento

$brandLabel = $_product->getAttributeText('manufacturer');
           
            $option_id = $attr->getSource()->getOptionId($brandLabel);

            $attrcode="manufacturer";

$product_collection=Mage::getModel("catalog/product")->getCollection();
   $product_collection->addAttributeToFilter($attrcode,$option_id);
            foreach($product_collection as $_product){
                $_product = Mage::getModel('catalog/product')->load($_product->getId());
            }

Friday 10 April 2015

How to override Admin controller Action in Magento

>> Hi! friends this example will help you to override admin controller action. I had to replicate admin product edit section as there were two types of products. First one was normal Magento products another was Used products. Client wanted to manage them separately. So, I override admin product controller action. How ?


 First You need to create a new module. Create a xml file within app/etc/modules/JR_Overridecontroller.xml
                        <?xml version="1.0"?>
                        <config>
                            <modules>
                                <AB_Overridecontroller>
                                    <active>true</active>
                                    <codePool>local</codePool>
                                </AB_Overridecontroller>
                            </modules>
                        </config>




 Now make the config.xml within app/code/local/AB/Overridecontroller/etc/config.xml
                         <?xml version="1.0"?>
                        <config>
                            <modules> 
                               <AB_Overridecontroller> 
                                 <version>1.0.0</version> 
                               </AB_Overridecontroller> 
                             </modules>
                         
                            <admin>
                                <routers>
                                    <adminhtml>
                                        <args>
                                            <modules>
                                                <AB_Overridecontroller before="Mage_Adminhtml">AB_Overridecontroller</AB_Overridecontroller>
                                            </modules>
                                        </args>
                                    </adminhtml>
                                </routers>
                            </admin>
                        </config> 



 So, now make the controller file that you need to modify within app/code/local/AB/Overridecontroller/controllers/Catalog/ProductController.php
                   <?php
                        include_once("Mage/Adminhtml/controllers/Catalog/ProductController.php");
                        class Ab_Overridecontroller_Catalog_ProductController extends Mage_Adminhtml_Catalog_ProductController
                        {
                            public function editAction(){
                               
                                // Here is your overridden controller method.....
                               
                            }
                        }
                    ?> 

Tuesday 24 February 2015