How to override _prepareCollection and _prepareColumns in Magento Admin - magento

How to override _prepareCollection and _prepareColumn from core to local. I want to add new column in a grid. How to do this?
protected function _prepareCollection()
{
$collection = Mage::getModel('players/players')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('player_id', array(
'header' => Mage::helper('players')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'player_id',
));
$this->addColumn('name', array(
'header' => Mage::helper('players')->__('Name'),
'align' =>'left',
'index' => 'name',
));
return parent::_prepareColumns();
}

Well there are two ways to do it. The first, while easier is not preferred, is to "local include hack" it and move the grid from core/Mage/../.. to local/Mage../.. and simply make your changes are required.
The alternative is to do a rewrite of the file in a module config.xml:
<blocks>
<customadminhtml>
<class>Namespace_CustomAdminhtml_Block</class>
</customadminhtml>
<adminhtml>
<rewrite>
<sales_order_grid>Namespace_CustomAdminhtml_Block_Adminhtml_Sales_Order_Grid</sales_order_grid>
</rewrite>
</adminhtml>
</blocks>
In the rewritten file I would not both trying to override the "_prepareCollection" call. How are you going to call it and set the collection, logically, you can't insert your changes in there properly and still maintain original functionality. Instead I would override the "setCollection" method. By doing this you maintain the logic of the original _prepareCollection function and can insert your logic into the flow:
/**
* #brief Add customer_email to sales order
* #param Mage_Sales_Model_Resource_order_grid_collection $collection
*/
public function setCollection($collection)
{
/** #var Mage_Eav_Model_Config $eav */
$eav = Mage::getModel('eav/config');
$attribute = $eav->getAttribute('customer', 'customer_number');
$connection = $collection->getConnection();
$collection->join(array('sfo' => 'sales/order'), 'main_table.entity_id=sfo.entity_id', 'customer_email');
if ($attribute->getId()) {
$collection->getSelect()
->joinLeft(array('c' => $connection->getTableName('customer_entity_varchar')),
'main_table.customer_id = c.entity_id AND c.attribute_id = '.$attribute->getId(),
array('customer_number' => 'value'));
}
parent::setCollection($collection);
}
Finally, you can add the column by overriding the normal "_prepareColumns" function, just call the parent before hand:
public function _prepareColumns()
{
parent::_prepareColumns();
$this->addColumnAfter('customer_email', array(
'header' => Mage::helper('customer')->__('Customer Email'),
'width' => '50px',
'index' => 'customer_email',
), 'shipping_name');
$this->sortColumnsByOrder();
return $this;
}

Related

Add another tab with Product Grid to Category edit page in Mangento

I am trying to add another tab to the category edit page that contains another product grid. I need to do this because i want to add to each category page a zone that contains the products that are selected in this grid.
Can anyone help me finish the module ? or is there a easier or existing module to do this ?
PS: Complete code is greatly appreciated :)
This is where i got so far:
etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Forideas_Promotion>
<version>0.1.0</version>
</Forideas_Promotion>
</modules>
<global>
<resources>
<forideas_promotion_setup>
<setup>
<module>Forideas_Promotion</module>
<class>Forideas_Promotion_Model_Resource_Setup</class>
</setup>
</forideas_promotion_setup>
</resources>
<helpers>
<promotion>
<class>Forideas_Promotion_Helper</class>
</promotion>
</helpers>
<models>
<forideas_promotion>
<class>Forideas_Promotion_Model</class>
</forideas_promotion>
<promotion_resource>
<entities>
<category_product>
<table>category_product</table>
</category_product>
</entities>
</promotion_resource>
</models>
<events>
<adminhtml_catalog_category_tabs>
<observers>
<forideas_promotion_observer>
<class>forideas_promotion/observer</class>
<method>addCategoryTab</method>
</forideas_promotion_observer>
</observers>
</adminhtml_catalog_category_tabs>
</events>
</global>
<adminhtml>
<layout>
<updates>
<forideas_category_promotion>
<file>forideas_promotion.xml</file>
</forideas_category_promotion>
</updates>
</layout>
</adminhtml>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<Forideas_Promotion before="Mage_Adminhtml">Forideas_Promotion_Adminhtml</Forideas_Promotion>
</modules>
</args>
</adminhtml>
</routers>
</admin>
</config>
Block/Adminhtml/Category/Edit/Tab/Product.php:
<?php
class Forideas_Promotion_Block_Adminhtml_Category_Edit_Tab_Product
extends Mage_Adminhtml_Block_Widget_Grid {
public function __construct(){
parent::__construct();
$this->setId('product_grid');
$this->setDefaultSort('position');
$this->setDefaultDir('ASC');
$this->setUseAjax(true);
if ($this->getCategory()->getId()) {
$this->setDefaultFilter(array('in_products'=>1));
}
}
protected function _prepareCollection() {
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToSelect('price');
$adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
$collection->joinAttribute('product_name', 'catalog_product/name', 'entity_id', null, 'left', $adminStore);
if ($this->getCategory()->getId()){
$constraint = '{{table}}.category_id='.$this->getCategory()->getId();
}
else{
$constraint = '{{table}}.category_id=0';
}
$collection->joinField('position',
'promotion/category_product',
'position',
'product_id=entity_id',
$constraint,
'left');
$this->setCollection($collection);
parent::_prepareCollection();
return $this;
}
protected function _prepareMassaction(){
return $this;
}
protected function _prepareColumns(){
$this->addColumn('in_products', array(
'header_css_class' => 'a-center',
'type' => 'checkbox',
'name' => 'in_products',
'values'=> $this->_getSelectedProducts(),
'align' => 'center',
'index' => 'entity_id'
));
$this->addColumn('product_name', array(
'header'=> Mage::helper('catalog')->__('Name'),
'align' => 'left',
'index' => 'product_name',
));
$this->addColumn('sku', array(
'header'=> Mage::helper('catalog')->__('SKU'),
'align' => 'left',
'index' => 'sku',
));
$this->addColumn('price', array(
'header'=> Mage::helper('catalog')->__('Price'),
'type' => 'currency',
'width' => '1',
'currency_code' => (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
'index' => 'price'
));
$this->addColumn('position', array(
'header'=> Mage::helper('catalog')->__('Position'),
'name' => 'position',
'width' => 60,
'type' => 'number',
'validate_class'=> 'validate-number',
'index' => 'position',
'editable' => true,
));
}
protected function _getSelectedProducts(){
$products = $this->getCategoryProducts();
if (!is_array($products)) {
$products = array_keys($this->getSelectedProducts());
}
return $products;
}
public function getSelectedProducts() {
$products = array();
$selected = Mage::registry('current_category')->getSelectedProducts();
if (!is_array($selected)){
$selected = array();
}
foreach ($selected as $product) {
$products[$product->getId()] = array('position' => $product->getPosition());
}
return $products;
}
public function getRowUrl($item){
return '#';
}
public function getGridUrl(){
return $this->getUrl('*/*/productsGrid', array(
'id'=>$this->getCategory()->getId()
));
}
public function getCategory(){
return Mage::registry('current_category');
}
protected function _addColumnFilterToCollection($column){
// Set custom filter for in product flag
if ($column->getId() == 'in_products') {
$productIds = $this->_getSelectedProducts();
if (empty($productIds)) {
$productIds = 0;
}
if ($column->getFilter()->getValue()) {
$this->getCollection()->addFieldToFilter('entity_id', array('in'=>$productIds));
}
else {
if($productIds) {
$this->getCollection()->addFieldToFilter('entity_id', array('nin'=>$productIds));
}
}
}
else {
parent::_addColumnFilterToCollection($column);
}
return $this;
}
}
controllers/Adminhtml/Promotion/Category/ProductController.php:
<?php
require_once ("Mage/Adminhtml/controllers/Catalog/ProductController.php");
class Forideas_Promotion_Adminhtml_Promotion_Category_ProductController extends Mage_Adminhtml_Catalog_ProductController
{
public function productsAction(){
//$this->_initEntity(); //if you don't have such a method then replace it with something that will get you the entity you are editing.
$this->loadLayout();
$this->getLayout()->getBlock('category.edit.tab.product')
->setCategoryProducts($this->getRequest()->getPost('category_products', null));
$this->renderLayout();
}
public function productsgridAction(){
//$this->_initCategory();
$this->loadLayout();
$this->getLayout()->getBlock('category.edit.tab.product')
->setCategoryProducts($this->getRequest()->getPost('category_products', null));
$this->renderLayout();
}
}
Model/Observer.php
<?php
class Forideas_Promotion_Model_Observer{
public function addCategoryTab($observer)
{
$block = $observer->getEvent()->getTabs();
$block->addTab('features', array(
'label' => Mage::helper('catalog')->__('Some Label here'),
'url' => Mage::helper('adminhtml')->getUrl('adminhtml/promotion_category_product/productsgrid', array('_current' => true)),
'class' => 'ajax',
));
}
}
sql/setup/install-0.1.0.php
$this->startSetup();
$table = $this->getConnection()
->newTable($this->getTable('promotion/category_product'))
->addColumn('rel_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'identity' => true,
'nullable' => false,
'primary' => true,
), 'Relation ID')
->addColumn('category_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Category ID')
->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Product ID')
->addColumn('position', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'nullable' => false,
'default' => '0',
), 'Position')
->addIndex($this->getIdxName('promotion/category_product', array('product_id')), array('product_id'))
->addForeignKey($this->getFkName('promotion/category_product', 'category_id', 'promotion/category', 'entity_id'), 'category_id', $this->getTable('promotion/category'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->addForeignKey($this->getFkName('promotion/category_product', 'product_id', 'catalog/product', 'entity_id'), 'product_id', $this->getTable('catalog/product'), 'entity_id', Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->setComment('Category to Product Linkage Table');
$this->getConnection()->createTable($table);
$this->endSetup();
I found the answer to your 'ajax loader will not disappear' problem. This is due to the fact that the HTML that is returned from the AJAX call actually refers to the original table, catalog_category_products_table. But the Javascript is looking for your own table name but can't find it and thus the infinite Please wait loader.
The solution is to create your own controller that extends Mage_Adminhtml_Catalog_CategoryController and load your own block with your gridname there. Then, in the block where you extended Mage_Adminhtml_Block_Catalog_Category_Tab_Product, you will define getGridUrl() and return the path to your newly created controller. Now everything will just work fine.
Don't know for what purpose you have uploaded all these code. As far as I can see it doesn't refer to your question. If you want to add new tab do following:
config.xml
<adminhtml>
<events>
<adminhtml_catalog_category_tabs>
<observers>
<add_new_tab>
<type>singleton</type>
<class>company_module/observer</class>
<method>addNewCategoryTab</method>
</add_new_tab>
</observers>
</adminhtml_catalog_category_tabs>
</events>
</adminhtml>
Model/Observer.php
class Company_Module_Model_Observer
{
public function addNewCategoryTab($observer)
{
$tabs = $observer->getTabs();
$tabs->addTab('prod', array(
'label' => Mage::helper('catalog')->__('Other Products'),
'content' => $tabs->getLayout()->createBlock(
'adminhtml/catalog_category_tab_product',
'category.product.grid'
)->toHtml(),
));
}
Than use your block extended from adminhtml/catalog_category_tab_product with yours rewrited _prepareCollection method. (Don't forget to put you block inside createBlock method)

Adding Status Column to Customer Information -> Orders in Magento

I've been attempting to add a "Status" column in the Orders grid that's shown when you view the Customer Information -> Orders tab.
I've been able to add the column, and the filter populates with the correct status values, but it breaks the default sorting and you can't filter by any item or sort.
I know there's probably a much better way of adding the column, but all the examples I found related to the main Orders table and I couldn't figure out how to modify it for this use case.
Here's my extension code - in /Pnp/Customer/Block/Customer/Edit/Tab/Orders.php
<?php
class Pnp_Customer_Block_Customer_Edit_Tab_Orders extends Mage_Adminhtml_Block_Customer_Edit_Tab_Orders
{
public function __construct()
{
parent::__construct();
$this->setId('customer_orders_grid');
$this->setUseAjax(true);
$this->setDefaultSort('created_at');
$this->setDefaultDir('DESC');
$this->setSaveParametersInSession(true);
}
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('sales/order_grid_collection')
->addFieldToSelect('entity_id')
->addFieldToSelect('increment_id')
->addFieldToSelect('customer_id')
->addFieldToSelect('created_at')
->addFieldToSelect('grand_total')
->addFieldToSelect('order_currency_code')
->addFieldToSelect('store_id')
->addFieldToSelect('billing_name')
->addFieldToSelect('shipping_name')
->addFieldToSelect('status')
->addFieldToFilter('customer_id', Mage::registry('current_customer')->getId())
->setIsCustomerMode(true);
$this->setCollection($collection);
return $this;
}
protected function _prepareColumns()
{
parent::_prepareColumns();
$this->addColumn('status', array(
'header' => Mage::helper('sales')->__('Status'),
'index' => 'status',
'type' => 'options',
'width' => '70px',
'options' => Mage::getSingleton('sales/order_config')->getStatuses()
));
return parent::_prepareColumns();
}
}
Thanks in advance for any help you can offer!
Many thanks to the answers so far.
I've nearly got there with a combination of Harit and Emipro Technologies answers, here's what I have so far:
etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Pnp_Customer>
<version>0.4.0</version>
</Pnp_Customer>
</modules>
<global>
<models>
<pnp_statusgrid>
<class>Pnp_Customer_Model</class>
</Pnp_statusgrid>
</models>
</global>
<adminhtml>
<events>
<core_block_abstract_prepare_layout_before>
<observers>
<statusgrid_column_append>
<type>model</type>
<class>Pnp_Customer_Model_Observer</class>
<method>appendCustomColumn</method>
</statusgrid_column_append>
</observers>
</core_block_abstract_prepare_layout_before>
</events>
</adminhtml>
</config>
Model/Observer.php
<?php
class Pnp_Customer_Model_Observer extends Varien_Event_Observer
{
/**
* Adds column to admin customers grid
*
* #param Varien_Event_Observer $observer
* #return Pnp_Customer_Model_Observer
*/
public function appendCustomColumn(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
if (!isset($block)) {
return $this;
}
if ($block->getType() == 'adminhtml/customer_edit_tab_orders') {
/* #var $block Mage_Adminhtml_Block_Customer_Grid */
$block->addColumn('status', array(
'header' => Mage::helper('customer')->__('Status'),
'type' => 'options',
'options' => Mage::getSingleton('sales/order_config')->getStatuses(),
'width' => '70px',
'index' => 'status',
'renderer' => 'Pnp_Customer_Block_Customer_Edit_Tab_Renderer_Status',
}
}
}
Block/Customer/Edit/Tab/Orders.php
<?php
class Pnp_Customer_Block_Customer_Edit_Tab_Orders extends Mage_Adminhtml_Block_Customer_Edit_Tab_Orders
{
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('sales/order_grid_collection')
->addFieldToSelect('entity_id')
->addFieldToSelect('increment_id')
->addFieldToSelect('customer_id')
->addFieldToSelect('created_at')
->addFieldToSelect('grand_total')
->addFieldToSelect('order_currency_code')
->addFieldToSelect('store_id')
->addFieldToSelect('billing_name')
->addFieldToSelect('shipping_name')
->addFieldToSelect('status')
->addFieldToFilter('customer_id', Mage::registry('current_customer')->getId())
->setIsCustomerMode(true);
$this->setCollection($collection);
return $this;
}
}
Block/Customer/Edit/Tab/Renderer/status.php
<?php
class Pnp_Customer_Block_Customer_Edit_Tab_Renderer_Status extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {
public function render(Varien_Object $row)
{
if (!$value = $this->getColumn()->getIndex()){
return $this;
}
$value = $row->getData('increment_id');
$order = Mage::getModel('sales/order')->loadByIncrementId($value);
return '<span >'.$order['status']'</span>';
}
}
?>
Everything is working except the column shows the status name as underscored, i.e. payment_pending. I looked at the object being returned and can't see the label version. As a final thing to get the above finished, would anyone be able to point me in the right direction to print the human readable version of the attribute?
Final Edit:
I managed to figure it out - I changed:
return '<span >'.$order['status']'</span>';
to
return '<span >'.$order->getStatusLabel().'</span>';
This is definately work add renderer
change your column by
$this->addColumn('status', array(
'header' => Mage::helper('customer')->__('Status'),
'index' => 'status',
'type' => 'options',
'options' => $this->_getorderstatus(),
'renderer' => 'Pnp_Customer_Block_Customer_Edit_Renderer_Status',
));
Add new function in same file
protected function _getorderstatus(){
$ordstatus = (array) Mage::getModel('sales/order_status')->getResourceCollection()->getData();
$orderstatus=array();
foreach($ordstatus as $item){
$orderstatus[$item['status']]=$item['label'];
}
return $orderstatus;
}
status.php put function like
public function render(Varien_Object $row)
{
if (!$value = $this->getColumn()->getIndex()){
return $this;
}
$value = $row->getData('increment_id');
$order = Mage::getModel('sales/order')->loadByIncrementId($value);
return '<span >'.$order['status'].'</span>';
}
An easier and reliable way to achieve this is through observer.
Create a Module
Inside app/code/local/My/Module/etc/config.xml
<global>
<models>
<my_customgrid>
<class>My_Module_Model</class>
</my_customgrid>
</models>
</global>
<adminhtml>
<events>
<core_block_abstract_prepare_layout_before>
<observers>
<customgrid_column_append>
<type>model</type>
<class>My_Module_Model_Observer</class>
<method>appendCustomColumn</method>
</customgrid_column_append>
</observers>
</core_block_abstract_prepare_layout_before>
</events>
</adminhtml>
What it does is, it allows you to observe the block before its layout is prepared.
Create a file called Observer.php for your module and write down following:
class My_Module_Model_Observer extends Varien_Event_Observer {
/**
*
* #param Varien_Event_Observer $observer
* #return \My_Module_Model_Observer
*/
public function appendCustomColumn(Varien_Event_Observer $observer) {
$block = $observer->getBlock();
if (!isset($block)) {
return $this;
}
if ($block->getType() == 'adminhtml/customer_grid') {
/* #var $block Mage_Adminhtml_Block_Customer_Grid */
$block->addColumnAfter('field', array(
'header' => 'Your Field',
'type' => 'text',
'index' => 'field',
), 'email');
}
}
}
Follow this link for more information:
http://www.atwix.com/magento/add-column-to-customers-grid-alternative-way/
Hope it helps.

Adding data from customer_entity_varchar to order grid magento

I am trying to add 'accountno' field to order grid from customer_entity_varchar table. To achieve this I changed _prepareCollection() method in Grid.php like this:
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$customerEntityVarchar = Mage::getSingleton('core/resource')->getTableName('customer_entity_varchar');
$collection->getSelect()->join(array(
'customer_entity_varchar_table'=>$customerEntityVarchar),
'`main_table`.`customer_id`=`customer_entity_varchar_table`.`entity_id`
AND `customer_entity_varchar_table`.`attribute_id`=122',
array('accountno' => 'value'));
print_r($collection->getSelect()->__toString());
$this->setCollection($collection);
return parent::_prepareCollection();
}
In attribute_id=122' 122 is the attribute_id ofaccountno`
When I print_r the select query and execute it in phpmyadmin, it gets me the accurate results back but when I try to add Column to grid in _prepareColumns() method, it shows the field blank.
My _prepareColumns method looks like this:
protected function _prepareColumns()
{
$this->addColumn('real_order_id', array(
'header'=> Mage::helper('sales')->__('Order #'),
'width' => '80px',
'type' => 'text',
'index' => 'increment_id',
));
$this->addColumnAfter('accountno', array(
'header' => Mage::helper('sales')->__('Account No'),
'index' => 'accountno',
), 'real_order_id');
//rest of the code here
}

Add custom fields in review form

I am looking forward to create a custom fields 'Email Id' & One drop-down in Review form .
I have tried this one but not saving the data, its hows the fields only
app\code\core\Mage\Review\Model\Mysql4\Review.php
protected function _afterSave(Mage_Core_Model_Abstract $object)
{
$detail = array(
'title' => $object->getTitle(),
'detail' => $object->getDetail(),
'nickname' => $object->getNickname(),
'email' => $object->getEmail(), // New field 1
'fname' => $object->getFname(), // New field 2
);
Now add email,fname in the review_detail table in the database also go to app\code\core\Mage\Adminhtml\Block\Review\Edit\Form.php also add :
$fieldset->addField('fname', 'text', array( // New field 2
'label' => Mage::helper('review')->__('First Name'),
'required' => true,
'name' => 'fname'
));
$fieldset->addField('email', 'text', array( // New field 1
'label' => Mage::helper('review')->__('Email'),
'required' => true,
'name' => 'email'
));
before to
$fieldset->addField('nickname', 'text', array(
'label' => Mage::helper('review')->__('Nickname'),
'required' => true,
'name' => 'nickname'
));
Modify the Mage core class is a bit scary, which will be difficult to upgrade magento core class in the future. You can override the specific class by your own custom module (See module creator if you want to setup one)
Module's config.xml, add the models rewrite in as below:
<global>
<models>
<review_mysql4>
<rewrite>
<review>[[Your Company]]_[[Your Module]]_Model_Review</review>
</rewrite>
</review_mysql4>
</models>
...
</global>
And the specified class will extend from the Magento core class you want to override:
class [[Your Company]]_[[Your Module]]_Model_Review
extends Mage_Review_Model_Mysql4_Review
{
protected function _afterSave(Mage_Core_Model_Abstract $object)
{
....
}
}
Ps. to add the new field in magento review_detail table:
$installer = $this;
$installer->startSetup();
$installer->run("ALTER TABLE review_detail ADD COLUMN email VARCHAR(255) NULL");
$installer->endSetup();
Finally i have solved it...
Open
app\code\core\Mage\Review\Model\Resource\Review.php
you will find this code in line about 150
protected function _afterSave(Mage_Core_Model_Abstract $object)
{
$detail = array(
'title' => $object->getTitle(),
'detail' => $object->getDetail(),
'nickname' => $object->getNickname(),
);
Add the new two fields you want to add.
protected function _afterSave(Mage_Core_Model_Abstract $object)
{
$detail = array(
'title' => $object->getTitle(),
'detail' => $object->getDetail(),
'nickname' => $object->getNickname(),
'email' => $object->getEmail(), // New field 1
'fname' => $object->getFname(), // New field 2
);
Thats it no more.... :) Happy coding

Grid doesn't appear in custom admin module in Magento

I am trying to create a custom module in magento admin. I have reached the point where a new link has been added to the menu and by clicking on it, I can navigate to the index action of the controller of the module. But here I cannot see the grid, only the header text and the button which has been added in the block construct appear.
I can see that since this block extends the Mage_Adminhtml_Block_Widget_Grid_Container class, it will by itself add the grid block inside this module as its child.
And the Grid.php is included which I verified by printing out something in the overriden _prepareColumns method.
What am I missing here ?
These are the contents of the Grid.php file
class Book_Brands_Block_Adminhtml_Brands_Grid extends Mage_Adminhtml_Block_Widget_Grid {
public function __construct() {
parent::__construct();
$this->setId('brandsGrid');
$this->setDefaultSort('brands_id');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(true);
}
protected function _prepareCollection() {
$collection = Mage::getModel('brands/brands')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns() {
$this->addColumn('brands_id', array(
'header' => Mage::helper('brands')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'brands_id',
));
$this->addColumn('title', array(
'header'=> Mage::helper('brands')->__('Title'),
'align' =>'left',
'index' => 'title',
));
$this->addColumn('status', array(
'header'=> Mage::helper('brands')->__('Status'),
'align' => 'left',
'width' => '80px',
'index' => 'status',
'type' => 'options',
'options' => array(
1 => 'Enabled',
2 => 'Disabled',
),
));
$this->addColumn('action', array(
'header' => Mage::helper('brands')->__('Action'),
'width' => '100',
'type' => 'action',
'getter' => 'getId',
'actions' => array(
array(
'caption' => Mage::helper('brands')->__('Edit'),
'url' => array('base'=> '*/*/edit'),
'field' => 'id'
)
),
'filter' => false,
'sortable' => false,
'index' => 'stores',
'is_system' => true,
));
return parent::_prepareColumns();
}
public function getRowUrl($row) {
return $this->getUrl('*/*/edit', array('id' => $row->getId()));
}
}
Thanks
PS. I have tried flushing the cache but no luck
From memory I think _prepareColumns() is called before _prepareCollection() so if there is an error in the collection the grid won't get rendered even though you have confirmed the columns method.
Part of parent::_prepareCollection() tries to estimate the number of pages from the collection's getSize() and getSelectCountSql() methods, I often forget to check those are producing sane results which trips me up. Make sure all logging is turned on and put the following in your .htaccess file:
php_flag display_errors on
SetEnv MAGE_IS_DEVELOPER_MODE true
Try seeing what query is being generated with these commands:
Mage::log((string)$collection->getSelect());
Mage::log((string)$collection->getSelectCountSql());
Looks like you have the grid blocks set up correctly. However, you still need to load the grid into the layout and render it. This can either be done in the adminhtml layout xml or in the controller.
In your /app/design/adminhtml/../layout/brands.xml:
<?xml version="1.0"?>
<layout>
<brands_index_index>
<reference name="content">
<block type="brands/brands_grid" name="brands_grid"></block>
</reference>
</brands_index_index>
</layout>
In your controller:
public function indexAction()
{
$this->loadLayout();
$this->_addContent(
$this->getLayout()->createBlock('brands/brands_grid','brands')
);
$this->renderLayout();
}
Please note that you have to modify the above to your particular implementation. I think the layout xml is harder to comprehend initially than the programmatic instantiation in the controller, however, in the long run, it leads to less code bloat.
Just had a quick view and the only thing I can see in your code is:
protected function _prepareCollection() {
$collection = Mage::getModel('brands/brands')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
//Try to use it like this:
protected function _prepareCollection() {
$collection = Mage::getModel('brands/brands')->getCollection();
$this->setCollection($collection);
parent::_prepareCollection();
return $this;
}

Resources