12/11/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.

7/30/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,
        ));

7/24/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.*'));

5/17/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');

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');

3/28/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";