Get table name

Mage::getSingleton('core/resource')->getTableName('tablename')

Yet another raw sql example

$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
 
$query = 'SELECT COUNT(id) AS rows FROM table';
$sql = $readConnection->prepare($query);
$sql->execute();
$data = $sql->fetch();
printf("Rows: %d\n", $data['rows']);

Difference between addFieldToFilter and addAttributeToFilter

addFieldToFilter() is used to filter Non-EAV collections.

addAttributeToFilter() is used to filter EAV collections.

Between

gteq – greater than or equal (>=)
lteq – less then or equal (<=) gt – greater then (>)
lt – less (<) Doing BETWEEN with AND

$result = Mage::getModel('modulename/tablename')
		->getCollection()
		->addFieldToFilter('field1',array('gteq' => $value))
		->addFieldToFilter('field2',array("lteq" => $value));

Doing BETWEEN with OR

$result = Mage::getModel('modulename/tablename')
		->getCollection()
		->addFieldToFilter(
			array('bin_start', 'bin_end'),
			array(
				array('gteq' => $binDigits),
				array('lteq' => $binDigits),
                            )
                        );

Magento Iterate with Pages

        $tableDataCollection = Mage::getResourceModel('modulename/tablename_collection')->setPageSize(50);
 
	// Set number of pages and current page
        $pages = $tableDataCollection->getLastPageNumber();
        $currentPage = 1;
 
	// Interate
        do {
            $tableDataCollection->setCurPage($currentPage);
            $tableDataCollection->load();
 
            foreach ($tableDataCollection as $tableRow) {
		echo $tableRow->getId()."\n";
            }
 
            $currentPage++;
 
            //Clear collection and free memory
            $tableDataCollection->clear();
        } while ($pages => $currentPage);

Running Magento from command line

Method 1

<?php
 
require_once dirname(__DIR__) . '/../../../../../app/Mage.php';
$app = Mage::app();
Mage::register('isSecureArea', true);
// your code goes here

or

<?php
 
require_once dirname(__DIR__) . '/../../../../../app/Mage.php';
 
/**
 * Class My Shell Class
 */
class My_Shell_Class {
 
    /**
     * Constructor
     */
    public function __construct() {
        Mage::app();
        Mage::register('isSecureArea', true);
    }
 
    /**
     * Custom function
     */
    public function myFunction() {
	// your code goes here
    }
}
 
$shell = new My_Shell_Class();
$shell->myFunction();

Method 2, using approach similar to indexer.php

<?php
 
require_once dirname(__FILE__) . '/../../../../../../shell/abstract.php';
 
class My_Shell_Class extends Mage_Shell_Abstract
{
 
    /**
     * Run mandatory method 
     *
     */
    public function run()
    {
        if ($this->getArg('status')) {
 
            printf("Your code goes here\n");
 
            printf("Your param1 value".$this->getArg('status')."\n");
 
        } else {
            echo "
Usage:  php -f myshell.php -- [options]
 
     status                   Execute status logic
  --status param1        Execute status logic depending on param1 value
 
  help                 This help
		";
        }
    }
}
 
$shell = new My_Shell_Class();
$shell->run();

Add a custom action to grid

1. In your Grid.php action do the following

 
<?php
...
 
        $this->addColumn('action',
            array(
                'header' => Mage::helper('promolink')->__('Action'),
                'width' => '50px',
                'type' => 'action',
                'getter' => 'getId',
                'actions' => array(
                    array(
                        'caption' => Mage::helper('promolink')->__('Delete'),
                        'url' => array('base' => '*/*/delete'),
                        'field' => 'id'
                    )
                ),
                'filter' => false,
                'renderer'  => 'Vendorname_Modulename_Block_Adminhtml_Template_Grid_Renderer_Youraction',
                'sortable' => false,
                'index' => 'id',
                'is_system' => true,
        ));
..

2. Create a file Vendorname/Modulename/Block/Adminhtml/Template/Grid/Renderer/Youraction.php
and add the following to it:

 
<?php
 
class Vendorname_Modulename_Block_Adminhtml_Template_Grid_Renderer_Youraction extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Action
{
    public function render(Varien_Object $row)
    {
	$value = $row->getData('id');
        if($value == $row->getData('id')) {
            return '<a href="'.$this->getUrl('adminhtml/promolink_index/delete',array('id'=>$row->getData('id'))).'">Delete</a>';
            }
        else {
            return false;
        }
    }

Passing post data back to form

1. Add the following to the file: Vendorname/Modulename/controllers/Adminhtml/Modulename/IndexController.php

 
<?php
...
    public function saveAction() {
        if ( $this->getRequest()->getPost() ) {
            try {
                $postData = $this->getRequest()->getPost();
 
		}
		catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($postData);
 
                $this->_redirect('*/*/edit');
                return;			
		}
...

2. Add this parts of code to IndexController.php as well

<?php
 
...
    public function editAction() {
 
            if ($data = Mage::getSingleton('adminhtml/session')->getFormData()) {
                Mage::register('modulename_data', $modulename->addData($data));
                Mage::getSingleton('adminhtml/session')->setFormData(null);
            }
 
        $this->loadLayout();
        $this->renderLayout();
    }

3. Then add the following to this file: Vendorname/Modulename/Block/Adminhtml/Modulename/Form.php

 
<?php
...
    protected function _prepareForm() {
 
        $form = new Varien_Data_Form();
 
        $vendor = Mage::registry('modulename_data');
        $formValues = $vendor->getData();
 
        $form->setValues($formValues);
        return parent::_prepareForm();
    }

Add a sql like to filter column in grid

 
<?php
 
protected function _addColumnFilterToCollection($column)
{
if ($column->getId() == 'name') {
$this->getCollection()->addFieldToFilter($column->getId(), array('like' => $column->getFilter()->getValue() . '%'));
...
$this->getCollection()->addFieldToFilter($column->geId(), $column->getFilter()->getCondition());
...
$this->getCollection()->addFieldToFilter('name', array('like' => '%' . $name . '%'));
else {
parent::_addColumnFilterToCollection($column);
}
 
return $this;
}

Display grid in admin form using custom field type

Step 1. Create new field type. Add the file app/local/code/Vendorname/Modulename/Block/Adminhtml/Modulename/Edit/Form/Renderer/Fieldset/Productgrid.php

 
<?php
 
class Vendorname_Modulename_Block_Adminhtml_Modulename_Edit_Form_Renderer_Fieldset_Productgrid extends Varien_Data_Form_Element_Abstract
{
    protected $_element;
 
    public function getElementHtml()
    {
        return Mage::helper('core')->getLayout()->createBlock('modulename/adminhtml_modulename_edit_form_renderer_fieldset_product_grid')->toHtml();
    }
}

Step 2. Add Grid to app/local/code/Vendorname/Modulename/Block/Adminhtml/Modulename/Edit/Form/Renderer/Fieldset/Product/Grid.php

 
<?php
 
class Vendorname_Modulename_Block_Adminhtml_Modulename_Edit_Form_Renderer_Fieldset_Product_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
 
    public function __construct()
    {
        parent::__construct();
        $this->setId('productsId');
        $this->setDefaultSort('id');
        $this->setUseAjax(true);
    }
 
    protected function _prepareCollection()
    {
 
        $collection = Mage::getModel('catalog/product')->getCollection()
            ->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
 
        $this->setCollection($collection);
 
        return parent::_prepareCollection();
    }
 
    protected function _prepareColumns()
    {
        $this->addColumn('grid_id', array(
            'header'    => Mage::helper('modulename')->__(''),
            'index' => 'entity_id',
            'type' => 'radio',
            'html_name' => 'grid_id',
            'align' => 'center',
            'filter' => false,
        ));
 
        $this->addColumn('id', array(
            'header' => Mage::helper('modulename')->__('ID'),
            'sortable' => true,
            'width' => '60px',
            'index' => 'entity_id'
        ));
 
        $this->addColumn('product_name', array(
            'header' => Mage::helper('modulename')->__('Name'),
            'index' => 'name'
        ));
 
        $this->addColumn('sku', array(
            'header' => Mage::helper('modulename')->__('SKU'),
            'width' => '120px',
            'index' => 'sku'
        ));
 
        return parent::_prepareColumns();
    }
 
    public function getGridUrl()
    {
        return $this->getUrl('*/*/product', array('_current' => true));
    }
}

Step 3. Add custom field to your Form in the file app/local/code/Vendorname/Modulename/Block/Adminhtml/Modulename/Edit/Form.php

 
<?php
 
class Vendorname_Modulename_Block_Adminhtml_Modulename_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
	...
 
        $fieldsetData->addType('product_grid', 'Vendorname_Modulename_Block_Adminhtml_Modulename_Edit_Form_Renderer_Fieldset_Productgrid');
 
        $fieldsetData->addField('product_id_grid', 'product_grid', array(
            'name'      => 'product_id_grid',
            'label'     => Mage::helper('modulename')->__('Product'),
            'class'     => 'required-entry',
            'required'  => true,
            'onclick' => "",
            'onchange' => "",
            'disabled' => false,
            'readonly' => false,
            'tabindex' => 1
        ));