Thứ Sáu, 5 tháng 4, 2013

Print array contents in log file of magento

In Magento You can print your log in Exception.log using

Mage::logException($e->getMessage());

If you want to put the log to your custom log file, then you can use write below line

Mage::log('Your Query', Zend_Log::DEBUG, custom.log);

But the problem is that , It will not print any Array data, If you want to print Array data in to log file then you can use any one of the below method

Mage::getModel('core/log_adapter', 'custom.log')->log($arrayvariable);

or

Mage::log('Your Data :'.print_r($arrayvariable, true), Zend_Log::DEBUG, 'custom.log');


Thứ Ba, 11 tháng 12, 2012

How to create custom cron job in magento

Magento default have a cron.php file located in the root directory. To set a cron in magento you have to create your own module first, and in the config.xml you have to declare the method which will fired and the time. Below is a dump of a etc/config.xml file of a custom cron module

<?xml version="1.0"?>

<config>

<modules>

<Wl_Cronset>

<version>0.1.0</version>

</Wl_Cronset>

</modules>

<crontab>

<jobs>

<Wl_Cronset>

<schedule>

<cron_expr>01 00 * * *</cron_expr>

</schedule>

<run>

<model>cronset/expired::productExpired</model>

</run>

</Wl_Cronset>

</jobs>

</crontab>

<global>

<models>

<cronset>

<class>Wl_Cronset_Model</class>

</cronset>

</models>

</global>

</config>



As per mentioned in this xml your cron will be fired every day @ night 00:01 min

Now you have to write your own functionality in your module Model file, Here my model file name is Expired and the function which will trigger is productExpired().

<?php

class Wl_Cronset_Model_Expired extends Mage_Core_Model_Abstract

{

public function productExpired()

{

// Your code goes here

}

}

?>



Now login to your server to call the magento root cron.php and set to be fired in every minute.

Thứ Hai, 30 tháng 7, 2012

How to Add country and state Dropdown in magento admin


I din't able to create this in proper way like magento does but if you will have all the state of all country then I think this is the perfect solution. If you don't have all state for all country then this module is not solved your problem. If any one knows the correct way then please add the solution via comment. I am describing here How I exactly did.


Open your form which is in Yournamespace/Modulename/Block/Adminhtml/Modulename/Edit/Tab/Form.php then add below fields



$country = $fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => 'Country',
'values' => Mage::getModel('adminhtml/system_config_source_country') ->toOptionArray(),
'onchange' => 'getstate(this)',
));

$fieldset->addField('state', 'select', array(
'name' => 'state',
'label' => 'State',
'values' => Mage::getModel('modulename/modulename')
->getstate('AU'),
));

/*
* Add Ajax to the Country select box html output
*/
$country->setAfterElementHtml("<script type=\"text/javascript\">
function getstate(selectElement){
var reloadurl = '". $this
->getUrl('modulename/adminhtml_modulename/state') . "country/' + selectElement.value;
new Ajax.Request(reloadurl, {
method: 'get',
onLoading: function (stateform) {
$('state').update('Searching...');
},
onComplete: function(stateform) {
$('state').update(stateform.responseText);
}
});
}
</script>");

Now Create State Action in modulenamecontroller.php file which will be like this



public function stateAction() {
$countrycode = $this->getRequest()->getParam('country');
$state = "<option value=''>Please Select</option>";
if ($countrycode != '') {
$statearray = Mage::getModel('directory/region')->getResourceCollection() ->addCountryFilter($countrycode)->load();
foreach ($statearray as $_state) {
$state .= "<option value='" . $_state->getCode() . "'>" . $_state->getDefaultName() . "</option>";
}
}
echo $state;
}


Wysiwyg Editor not working in custom module created by Module creator


When you create a module using module creator then if you try to turn on the Wysiwyg editor of magento then you need to add some function in the Edit.php file which resides under Namespace/Modulename/Block/Adminhtml/Modulename/Edit.php



protected function _prepareLayout() {
parent::_prepareLayout();
if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
}
}

Now turn on the Wysiwyg editor in your code which may be like below



$fieldset->addField('summary', 'editor', array(
'name' => 'summary',
'label' => Mage::helper('modulename')->__('Description'),
'title' => Mage::helper('modulename')->__('Description'),
'style' => 'height:100px;',
'wysiwyg' => true,
'required' => true,
));


Thứ Hai, 23 tháng 7, 2012

Join custom table to product collection in magento


For your custom module if you want to join your custom table data with Magento default product collection then you need to join tables with the entiry_id of the product and your product_id stored in your custom table. Here I have just used the resource model collection to join the table. I tried with getmodel feature of Magento don't know why it doesn't able to create the Product grid in the backend. So I used resource model and it worked. If you are only joining the table, not to generate the Product grid, then you can use getmodel instead of resource model.

$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('name')
->addAttributeToSelect('sku')
->addAttributeToSelect('price')
->addAttributeToSelect('status')
->addAttributeToSelect('visibility')
->addAttributeToFilter('type_id', array('eq' => 'simple'))
->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->addAttributeToFilter('visibility', array('neq' => 1));

$collection->getSelect()->join(array('mep' => "mage_brand_product"), "e.entity_id = mep.product_id", array('mep.*'));




Thứ Năm, 17 tháng 5, 2012

addFiledToFilter Condition In Magento


As I already mentioned on the previous post that we only can give the condition of attribute name to filter the result. There is another method to filter result that you can use in your customer Module. Let you are having a customer module which is responsible to show some banner on the homepage. For that let you have some place to upload image and also have feature to give sort order and enable disable feature. Here in the below code I will show how to filter the result with addFieldtoFilter



$banner = Mage::getModel('mymodulename/banner')->getCollection();



Now I wish to show banner whose status are active. I already have a field name/column name 'status' in my custom table.



$banner -> addFieldToFilter('status', array('eq' => 1));


Now I will sort the result according to sort order in my table. I already have a field name 'sort_order' in my table. To sort according to that column I will write



$banner -> setOrder('sort_order', 'DESC');


Thứ Tư, 16 tháng 5, 2012

addAttributeToFilter Condition In Magento


addAttributeToFilter Condition is used to Filter the collection query of magento . we can use to to filter the result of category collection, Product Collection, Customer collection, Order collection etc.


When you use this condition into the collection make sure your filterable option should be an attribute not should be a table column or fieldname.


Below is the example to fetch all products and using addAttributeToFilter to filter the result



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



Below are all types of condition which you can use To Filter the result



$collection -> addAttributeToFilter('status', array('eq' => 1));

$collection -> addAttributeToFilter('status', array('neq' => 0));

$collection -> addAttributeToFilter('id' , array('in' => array(1,2,3,4)));

$collection -> addAttributeToFilter('id' , array('nin' => array(5,6)));

$collection -> addAttributeToFilter('sku' , array('like' => "%a%"));

$collection -> addAttributeToFilter('sku' , array('nlike' => "test%"));

$collection -> addAttributeToFilter('weight', array('gt' => 10));

$collection -> addAttributeToFilter('weight', array('lt' => 1));

$collection -> addAttributeToFilter('name' , 'notnull');

$collection -> addAttributeToFilter('sort_description' , 'null');


Thứ Ba, 27 tháng 3, 2012

How to refresh magento cache using magento php code

create a file in the root folder of your magento for example refreshcache.php and write the below code to refresh your magento cache without logging to Admin panel
require_once 'app/Mage.php';

umask( 0 );

Mage :: app( "default" );

$ver = Mage :: getVersion();

$userModel = Mage :: getModel( 'admin/user' );

$userModel -> setUserId( 0 );

Mage :: getSingleton( 'admin/session' ) -> setUser( $userModel );

echo "Refreshing cache...\n";

Mage :: app() -> cleanCache();

$enable = array();

foreach ( Mage :: helper( 'core' ) -> getCacheTypes() as $type => $label ) {

$enable[$type] = 1;

}

Mage :: app() -> saveUseCache( $enable );

echo "Cache refreshed";

Thứ Tư, 28 tháng 12, 2011

How to override catalogsearch model class in magento

In magento if you wish to override some controller then definately you will get lots of site which will describe how to do that but for model class, you will have some result. So I think to share my knowledge here. I am going to override default catalog search Model of magento. For that I will create an module with name space name Mage and module name Searchby. I hope you people know how to create an module so I will show you how to override model class only

Go to config.xml of your custom module then write the below code to override the catalogsearch model class

<?xml version="1.0" encoding="UTF-8"?>

<config>

    <modules>

        <Mage_Searchby>

            <version>0.1.0</version>

        </Mage_Searchby>

    </modules>

    <frontend>

        <routers>

            <searchby>

                <use>standard</use>

                <args>

                    <module>Mage_Searchby</module>

                    <frontName>searchby</frontName>

                </args>

            </searchby>

        </routers>        

    </frontend>

    <global>

        <models>

            <catalogsearch>

                <rewrite>

                    <layer>Mage_Searchby_Model_Layer</layer>

                </rewrite>

            </catalogsearch>

        </models>

    </global>

</config>

Now create an Layer.php file inside yourmodulename/Model then write the below code

<?php

class Mage_Searchby_Model_Layer extends Mage_CatalogSearch_Model_Layer

{

    public function prepareProductCollection($collection)

    {

        //Code to be executed

    }

}?>

That's all thanks

Thứ Sáu, 25 tháng 11, 2011

How to add search by category in magento mini search



There is no free extension in magento commerce which will help you to search your store with particular category. I tried from myself and able to do, I am sharing my exprerience here with.

First create the drop down list of all category in form.mini.phtml

<select name="category" id="category_search_field">

<option value="">-- Any Category --</option>

<?php foreach ($catalog->getStoreCategories() as $_category): ?>

<?php if($_category->hasChildren()): ?>

<option class="parent-cat" value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>

<?php foreach ($_category->getChildren() as $subcategory):

if($subcategory->getIsActive()) : ?>

<option value="<?php echo $subcategory->getId(); ?>"<?php echo ($this->getRequest()->getQuery('category') == $subcategory->getId() ? ' selected="selected"': "") ?>><?php echo $subcategory->getName(); ?></option>

<?php endif; endforeach; ?>

<?php elseif($_category->getIsActive()): ?>

<option value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>

<?php endif; ?>

<?php endforeach ?>

</select>

Now go to app/code/core/Mage/CatalogSearch/Helper and open the Data.php and add the below code

public function getStoreCategories()

{

$helper = Mage::helper('catalog/category');

return $helper->getStoreCategories();

}

public function getSelectedCategory()

{

$catid = (int)addslashes($_REQUEST['category']);

$cat="";

if($catid>1)

$cat = Mage::getModel('catalog/category')->load($catid);

return $cat;

}

Now go to app/code/core/Mage/CatalogSearch/Model and open the Layer.php

replace

public function prepareProductCollection($collection)

{

$collection

->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())

->addSearchFilter(Mage::helper('catalogsearch')->getQuery()->getQueryText())

->setStore(Mage::app()->getStore())

->addMinimalPrice()

->addFinalPrice()

->addTaxPercents()

->addStoreFilter()

->addUrlRewrite();

Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);

Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);

return $this;

}

with

public function prepareProductCollection($collection)

{

if(Mage::helper('catalogsearch')->getSelectedCategory()!="")

{

$collection

->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())

->addSearchFilter(Mage::helper('catalogsearch')->getQuery()->getQueryText())

->setStore(Mage::app()->getStore())

->addMinimalPrice()

->addFinalPrice()

->addTaxPercents()

->addStoreFilter()

->addCategoryFilter(Mage::helper('catalogsearch')->getSelectedCategory())

->addUrlRewrite();

}

else

{

$collection

->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())

->addSearchFilter(Mage::helper('catalogsearch')->getQuery()->getQueryText())

->setStore(Mage::app()->getStore())

->addMinimalPrice()

->addFinalPrice()

->addTaxPercents()

->addStoreFilter()

->addUrlRewrite();

}

Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);

Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);

return $this;

}

save and Enjoy.

Thứ Tư, 16 tháng 11, 2011

cache is not generating in magento

Magento stores cache inside the cache folder which resides under Var folder of your root magento ,But if your cache folder or var folder have not correct file permisson that is 777 then magento will not be able to generate any cache. So change Var folder permission to 777 , you will see the effect.

Thứ Hai, 31 tháng 10, 2011

How To Display Best Selling Products On Magento Store

To promote best selling products on your site Magento use so many way to show bestseller product, One of them I am going to show. Below code will fetch the all the list of all product which have already sell.

<?php

$_productCollection = Mage::getResourceModel('reports/product_collection')

->addOrderedQty()

->setOrder('ordered_qty', 'desc');

?>



This is the collection of all the product which already have sell.

Now use foreach loop to show some number of product and it details. I wish to show only the name of the product which has sell most. And I will show on the left sidebar of the page.

<div class="block best-seller">

<div class="right-title-bg"><h3>Best Selling Product</h3></div>

<div class="block-content">

<ul class="best-selling-item">

$count = 0;

foreach($_productCollection as $product):

$id = $product->getId();

$prod = Mage::getModel('catalog/product')->load($id);?>

<li><a href="<?php echo $prod->getProductUrl();?>" title="<?php echo $prod->getName();?>"><?php echo $prod->getName();?></a></li>

<?php

$count++ ;

if($count==$totalPerPage)

break;

endforeach;

?>

</ul>

</div>

</div>



If you wish to show all the details of the product then you also can do that as you will get the product Id from $prod->getId(); and from product Id you can fetch each and every details of the product

Thứ Bảy, 29 tháng 10, 2011

How to print product collection query in magento

Let you have write a product collection with some attribute to select some product, but you are not getting proper result then you must need to print the sql query to see whether you have write the correct syntax in magento default collection. then write the below code to get the sql query .

<?php

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

->addAttributeToFilter('bestseller', array('eq' => 1))

->addAttributeToSelect('*');

echo $productcollection->getSelect()->assemble();

?>



Thứ Ba, 27 tháng 9, 2011

How to delete all sales order in magento

In Magento Connect you will find some extension which will delete all cancel order and Pending Order, But it never delete all processed order. To delete all orders following code snippet can be used.

<?php

require 'app/Mage.php';

Mage::app('admin')->setUseSessionInUrl(false);                                                                              

$sales_orders = Mage::getModel('sales/order')->getCollection()->getData();

foreach($sales_orders as $sales_order){

    $id = 0;

    $id = $sales_order['increment_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."

?>



Chủ Nhật, 25 tháng 9, 2011

How to use or mysql condition in $collection data of magento

Magento provide  addAttributeToFilter to use and operator in $collection, But using of OR operator is little bit different . I was guess that there must be and OrAttributeToFilter , But I was wrong I think magento forgot to write this function, Lastly I found the solution to use mysql OR in magento . In addAttributeToFilter we have to write the condition in the form of array.

protected function _prepareCollection()

{

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

   $collection->addAttributeToFilter(

      array(

          array('attribute'=>'category_ids','finset'=>2),

          array('attribute'=>'category_ids','finset'=>3)

      )

   );

}





use your own attribute name and value to get the data

Thứ Sáu, 16 tháng 9, 2011

How to upload and read csv file in magento

To upload CSV file and to read that file line by line , Please write the below code in magento



if(isset($_FILES['import_file']['name']) && $_FILES['import_file']['name'] != '')

{

    $uploaderFile = new Varien_File_Uploader('import_file');

    $uploaderFile->setAllowedExtensions(array());

    $uploaderFile->setAllowRenameFiles(false);

    $uploaderFile->setFilesDispersion(false);

    $uploaderFilepath = Mage::getBaseDir('media') . DS . 'importcsv' . DS ;

    $uploaderFile->save($uploaderFilepath, $_FILES['import_file']['name'] );

    $file = $_FILES['import_file']['name'];

    $filepath = $uploaderFilepath.$file;

    $i = 0;

    if(($handle = fopen("$filepath", "r")) !== FALSE) {

        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){            

            if($i>0 && count($data)>1){

                updateData($data);

            }          

            $i++;

        }

    }

    else{

        Mage::getSingleton('adminhtml/session')->addError("There is some Error");

        $this->_redirect('*/*/index');

    }

}

    function updateData($data)

    {

        //Write your code here and Update it to magento tables

    }



Thứ Ba, 30 tháng 8, 2011

How to get contact us email address in magento

Here’s the code to get Contacts email:



<?php echo Mage::getStoreConfig('contacts/email/recipient_email');?>

Or you can change it from admin -> System-> Configuration. From the left tab select Contacts then On the right side you will see Email Options Tab. From that tab you can see there is a field for send Emails To.Change th evalue to your require email address

Thứ Năm, 4 tháng 8, 2011

How to uncheck Radio button by jquery








Write the Below code to Unchecked Radio Button by Jquery




<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$('input[name="rd"][type="radio"]:checked').each(function(){
$(this).attr("checked", false);
});
});
});
</script>






<form action="" name="aa" method="post">
<input type="radio" name="rd" value="1"/>
<input type="radio" name="rd" value="2"/>
<input type="radio" name="rd" value="3"/>
<input type="button" id="btn" value="Click" />
</form>

How to change value and fetch value of Minimum Order Amounts of free shipping in magento


First of all to make Minimum Order Amounts of Free Shipping to [STORE VIEW] instead of [WEBSITE] then Go to app->code->core->Mage->Shipping->etc->System.xml


then change the value of <show_in_store> to 1 under carriers -> groups -> freeshipping ->free_shipping_subtotal.


Now to fetch the value of the Minimum Order Amount according to store view write the below code



<?php echo Mage::getStoreConfig('carriers/freeshipping/free_shipping_subtotal'); ?>

Thứ Sáu, 29 tháng 7, 2011

How to remove validation on zip code in magento checkout page


In the World some of the country has no zip code like Ireland, But magento has default zip code validation to make that optional for specific country magento has added a new feature in admin panel. To make Zip code optional please follow the following steps.


Login to your your magento admin panel then go to System -> Configuration->General. From Country option tab you can see there is an option " Postal code is optional for the following countries " Select the country which you want to Optional/Not validate . then click on save config to save your settings. To be more clear on this please see the below screenshot.