Grid serializer retuns foreach error upon search - magento

Hello I've trying to create a grid serializer. Upon clicking the tab in Admin it's displaying correctly.
But when in grid I change the select field from Yes to Any to find all the records. It gives the Foreach error(Invalid argument supplied for foreach).
Layout:
<manager_adminhtml_manager_category>
<block type="core/text_list" name="root" output="toHtml">
<block type="manager/adminhtml_manager_edit_tab_category" name="categories.grid"/>
<block type="adminhtml/widget_grid_serializer" name="grid_serializer">
<reference name="grid_serializer">
<action method="initSerializerBlock">
<grid_block_name>categories.grid</grid_block_name>
<data_callback>getSelectedCategories</data_callback>
<hidden_input_name>links[category]</hidden_input_name>
<reload_param_name>category</reload_param_name>
</action>
<action method="addColumnInputName">
<input_name>position</input_name>
</action>
</reference>
</block>
</block>
</manager_adminhtml_manager_category>
<manager_adminhtml_manager_categorygrid>
<block type="core/text_list" name="root" output="toHtml">
<block type="manager/adminhtml_manager_edit_tab_category" name="categories.grid"/>
</block>
</manager_adminhtml_manager_categorygrid>
controller
class Excellence_Manager_Adminhtml_ManagerController extends Mage_Adminhtml_Controller_action
{
public function categoryAction(){
$this->loadLayout();
$this->getLayout()->getBlock('categories.grid')->setCategory($this->getRequest()->getPost('category',null));
$this->renderLayout();
}
public function categorygridAction(){
$this->loadLayout();
$this->getLayout()->getBlock('categories.grid')
->setCategory($this->getRequest()->getPost('category', null));
$this->renderLayout();
}
block
<?php
class Excellence_Manager_Block_Adminhtml_Manager_Edit_Tab_Category extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('categoryGrid');
$this->setUseAjax(true); // Using ajax grid is important
$this->setDefaultSort('entity_id'); // default sort from the _prepareColoum below
$this->setDefaultFilter(array('in_producted'=>1)); // By default we have added a filter for the rows, that in_products value to be 1
$this->setSaveParametersInSession(false);
}
protected function _prepareCollection()
{
$collection = Mage::getResourceModel('catalog/category_collection');
$tm_id = $this->getRequest()->getParam('id');
if(!isset($tm_id)) {
$tm_id = 0;
}
Mage::getResourceModel('manager/cat')->addGridPosition($collection,$tm_id);
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _addColumnFilterToCollection($column)
{
// Set custom filter for in product flag
if ($column->getId() == 'in_producted') {
$ids = $this->_getSelectedCategories();
if (empty($ids)) {
$ids = 0;
}
if ($column->getFilter()->getValue()) {
$this->getCollection()->addFieldToFilter('entity_id', array('in'=>$ids));
} else {
if($ids) {
$this->getCollection()->addFieldToFilter('entity_id', array('nin'=>$ids));
}
}
} else {
parent::_addColumnFilterToCollection($column);
}
return $this;
}
protected function _prepareColumns()
{
$this->addColumn('in_producted', array(
'header_css_class' => 'a-center',
'type' => 'checkbox',
'name' => 'customer',
'values' => $this->_getSelectedCategories(),
'align' => 'center',
'index' => 'entity_id'
));
$this->addColumn('entity_id', array(
'header' => Mage::helper('customer')->__('ID'),
'width' => '50px',
'index' => 'entity_id',
'type' => 'number',
));
$this->addColumn('name', array(
'header' => Mage::helper('customer')->__('Name'),
'index' => 'name'
));
$this->addColumn('is_active', array(
'header' => Mage::helper('customer')->__('Status'),
'width' => '150',
'index' => 'is_active'
));
return parent::_prepareColumns();
}
protected function _getSelectedCategories() // Used in grid to return selected customers values.
{
$categories = array_keys($this->getSelectedCategories());
return $categories;
}
public function getGridUrl()
{
return $this->_getData('grid_url') ? $this->_getData('grid_url') : $this->getUrl('*/*/categorygrid', array('_current'=>true));
}
public function getSelectedCategories()
{
// Categories Data
$tm_id = $this->getRequest()->getParam('id');
if(!isset($tm_id)) {
$tm_id = 0;
}
$collection = Mage::getModel('manager/cat')->getCollection();
$collection->addFieldToFilter('manager_id',$tm_id);
$catIds = array();
foreach($collection as $obj){
$catIds[$obj->getCategoryId()] = array('position'=>$obj->getPosition());
}
return $catIds;
}
}

Have you checked that the $collection isn't empty/has data? Could you var_dump($collection); before your foreach loop and post the output?
Try this by replacing:
$collection = Mage::getModel('manager/cat')->getCollection();
$collection->addFieldToFilter('manager_id',$tm_id);
with
$collection = Mage::getModel('manager/cat')->getCollection()->addFieldToSelect('*')->addFieldToFilter('manager_id',$tm_id);
If that doesn't work try adding $collection->load(); before your foreach loop.

Related

Magento invoice grid filter_condition_callback not working

I added a custom column to invoice grid using an observer.
The problem is that I can't sort or filter by the new column.
I added a filter condition callback but the function is not called.
Here is my Observer.php
class DB_CustomGrid_Model_Adminhtml_Observer
{
public function onBlockHtmlBefore(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
$payment_methods = array();
$readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
$query = 'SELECT method FROM '.Mage::getSingleton('core/resource')->getTableName('sales/order_payment').' GROUP BY method';
$methods = $readConnection->fetchAll($query);
foreach($methods as $payment) {
if($payment["method"] !== 'free') {
$payment_methods[$payment["method"]] = Mage::getStoreConfig('payment/'.$payment["method"].'/title');
}
}
switch ($block->getType()) {
case 'adminhtml/sales_invoice_grid':
$block->addColumnAfter('state', array(
'header' => Mage::helper('sales')->__('Payment Method'),
'index' => 'method',
'type' => 'options',
'width' => '70px',
'options' => $payment_methods,
'filter' => false,
'filter_condition_callback' => array($this, '_myCustomFilter'),
), 'method');
break;
}
}
public function beforeCollectionLoad(Varien_Event_Observer $observer)
{
$collection = $observer->getOrderInvoiceGridCollection();
$collection->join(array('payment'=>'sales/order_payment'),'main_table.order_id=parent_id',array('method'));
}
protected function _myCustomFilter($collection, $column)
{
exit;
if (!$value = $column->getFilter()->getValue()) {
return $collection;
}
$collection->getCollection()->getSelect()->where("sales_order_payment.method like ?", "%$value%");
return $collection;
}
}
I added an exit; to check if the function is called or not.
Try this:
Add a new protected function to your observer class:
protected function _callProtectedMethod($object, $methodName) {
$reflection = new ReflectionClass($object);
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invoke($object);
}
Then call $block->sortColumnsByOrder() and the new function $this->_callProtectedMethod($block, '_prepareCollection') directly after $block->addColumnAfter();

save and delete buttons are missing from magento adminpanel form and also position of form is left?

i have been following this to create an admin grid view. Grid works fine but when i try to load form to edit or delete or save my entries there is no save and delete button in my form container see here https://www.dropbox.com/s/odk79gsvufpj9j9/Screenshot%20from%202015-08-28%2014%3A37%3A08.png?dl=0
here is my Edit.php
class Best_Test_Block_Adminhtml_Test_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::_construct();
$this->_objectId = 'id';
$this->_blockGroup = 'test';
$this->_controller = 'adminhtml_test';
$this->_updatebutton('save', 'label', 'save user');
$this->_updatebutton('delete', 'label', 'delete user');
}
public function getHeaderText()
{
if (Mage::registry('test_data')&&Mage::registry('test_data')->getId()) {
return 'Edit user '.$this->htmlEscape(Mage::regisrty('test_data')->getTitle()).'<br/>';
}else{
return 'Add a user';
}
}
}
here is my indexController.php in Adminhtml
class Best_Test_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()->_setActiveMenu('test/set_time')->_addBreadcrumb('test Manager', 'test Manager');
return $this;
}
public function indexAction()
{
$this->_initAction();
$this->renderLayout();
}
public function editAction()
{
$testId = $this->getRequest()->getParam('id');
$testModel = Mage::getModel('test/test')->load($testId);
if ($testModel->getId() || $testId == 0) {
Mage::register('test_data', $testModel);
$this->loadLayout();
$this->_setActiveMenu('test/set_time');
$this->_addBreadcrumb('test Manager', 'test Manager');
$this->_addBreadcrumb('Test Description', 'Test Description');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('test/adminhtml_test_edit'))->_addLeft($this->getLayout()->createBlock('test/adminhtml_test_edit_tabs'));
$this->renderLayout();
}else{
Mage::getSingleton('adminhtml/session')->addError('Test does not exist!');
$this->_redirect('*/*/');
}
}
public function newAction()
{
$this->_forward('edit');
}
public function saveAction()
{
if ($this->getRequest()->getPost()) {
try{
$postData = $this->getRequest()->getPost();
$testModel = Mage::getModel('test/test');
if ($this->getRequest()->getParam('id') <= 0) {
$testModel->setCreatedTime(Mage::getSingleton('core/date')->gmtDate());
$testModel->addData($postData)->setUpdateTime(Mage::getSingleton('core/date')->gmtDate())->setId($this->getRequest()->getParam('id'))->save();
Mage::getSingleton('adminhtml/session')->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')->settestData(false);
$this->_redirect('*/*/');
return;
}
} catch (Exception $e){
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->settestData($this->getRequest()->getPost());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return ;
}
}
$this->_redirect('*/*/');
}
public function deleteAction()
{
if ($this->getRequest()->getParam('id') > 0) {
try{
$testModel = Mage::getModel('test/test');
$testModel->setId($this->getRequest()->getParam('id'))->delete();
Mage::getSingleton('adminhtml/session')->addSuccess('Successfully deleted');
$this->_redirect('*/*/');
} catch (Exception $e){
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
}
here is Form.php in Adminhtml/Test/Edit
class Best_Test_Block_Adminhtml_Test_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(
array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
)
);
$form->setUseContainer(true);
$form->setForm($form);
return parent::_prepareForm();
}
}
here is Tabs.php in Adminhtml/Test/Edit
class Best_Test_Block_Adminhtml_Test_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId('test_tabs');
$this->setDestElementId('edit_form');
$this->setTitle('Information of User');
}
protected function _beforeToHtml()
{
$this->addTab('form_section', array(
'label' => 'User information',
'title' => 'User information',
'content' => $this->getLayout()->createBlock('test/adminhtml_test_edit_tab_form')->toHtml()
));
return parent::_beforeToHtml()
; }
}
here is Form.php in Adminhtml/Test/Edit/Tab
class Best_Test_Block_Adminhtml_Test_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareform()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('test_form', array('legend'=>'ref information'));
$fieldset->addField('name', 'text', array(
'label' => 'name',
'class' => 'required-entry',
'required' => 'true',
'name' => 'name',
));
$fieldset->addField('email', 'text', array(
'label' => 'email',
'class' => 'required-entry',
'required' => 'true',
'name' => 'email',
));
$fieldset->addField('password', 'password', array(
'label' => 'password',
'class' => 'required-entry',
'required' => 'true',
'name' => 'password',
));
if (Mage::registry('test_data')) {
$form->setValues(Mage::registry('test_data')->getData());
}
return parent::_prepareform();
}
}
And here is my test.xml in app/design/adminhtml/default/default/layout
<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
<test_adminhtml_index_index>
<reference name="content">
<block type="test/adminhtml_grid" name="test" />
</reference>
</test_adminhtml_index_index>
</layout>
why is save and delete missing from my form container?
Sorry if question is not well phrased, i am a noob magento user.

can't Filter or search product in grid with custom renderer

I have a problem with filter in my module in admin grid.
I also used 'order_item_id' field in my custom table and fetching product name based on '(sales/order_item)' using renderer.
I also using " 'filter_condition_callback' => array($this, '_productFilter') " but it cant' work
My problem is: can't Filter for columns with custom renderer not working.
When i search product name in column,it returns zero records.
What i wrong in My Code ?
public function _prepareColumns()
{
$this->addColumn('entity_id', array(
'header' => Mage::helper('adminhtml')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'entity_id',
));
$this->addColumn('order_item_id', array(
'header' => Mage::helper('adminhtml')->__('Product Name'),
'align' =>'right',
'index' => 'order_item_id',
'renderer' => 'Test_Module1_Block_Adminhtml_Renderer_Product',
'filter_condition_callback' => array($this, '_productFilter'),
));
return parent::_prepareColumns();
}
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$this->getCollection()->getSelect()->where(
"order_item_id like ?
"
, "%$value%");
return $this;
}
my renderer is
class Test_Module1_Block_Adminhtml_Renderer_Product extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
$order = Mage::getModel('sales/order_item')->load($row->getData('order_item_id'));
return $order->getName();
}
}
It is because of you have rendered id and you are searching with product name. So you need to change your productfilter function and put code for search the id in table according to product name.
You need to change your function :
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$orderitem = Mage::getModel('sales/order_item')->getCollection();
$orderitem->addFieldToFilter('name',array('like'=>'%'.$value.'%'));
$ids =array();
foreach($orderitem as $item){
$ids[] = $item->getId();
}
$this->getCollection()->addFieldToFilter("id",array("in",$ids));
return $this;
}
I have done some changes on saumik code and its work for me.
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$orderitem = Mage::getModel('sales/order_item')->getCollection();
$orderitem->addFieldToFilter('name',array('like'=>'%'.$value.'%'));
$ids =array();
foreach($orderitem as $item){
$ids[] = $item->getOrderId(); // sales_flat_order_item.order_id = sales_flat_order.entity_id
}
$this->getCollection()->addFieldToFilter("entity_id",array("in",$ids));
return $this;
}

After adding a column to Magento Sales order grid sorting and searching is not working

I have added a column for the shipping method to the sales order grid. But now sorting and searching is not working for any of the column.I have 65 orders being listed at a time even if I select 20 from view drop-down.
I have created a custom module for this and I am getting correct values under shipping information column.
Following is my code in Grid.php file.
<?php
class Mynamespace_Ordergrid_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid
{
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->join('sales_flat_order', 'main_table.entity_id = sales_flat_order.entity_id',array('shipping_description'));
$this->setCollection($collection);
}
protected function _prepareColumns() {
$this->addColumn('shipping_description', array(
'header' => Mage::helper('sales')->__('Shipping Method'),
'index' => 'shipping_description',
'filter_index'=>'sales_flat_order.shipping_description',
));
return parent::_prepareColumns();
}
public function getGridUrl()
{
return $this->getUrl('*/*/grid', array('_current'=>true));
}
}
?>
Please help
muk,try below
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$collection->getSelect()->join(array('myorder'=>'sales_flat_order'),'main_table.entity_id=myorder.entity_id',array('myorder.shipping_method as myorder_shipping_method'));
$this->setCollection($collection);
return parent::_prepareCollection();
}
Columns view of
$this->addColumn('myorder_shipping_method', array(
'header' => Mage::helper('sales')->__('Status'),
'index' => 'myorder_shipping_method',
'type' => 'options',
'width' => '70px',
'options' => $this->toOptionArray(),
));
add new function
public function toOptionArray($isMultiSelect = false)
{
$methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
$options = array();
foreach($methods as $_code => $_method)
{
if(!$_title = Mage::getStoreConfig("carriers/$_code/title"))
$_title = $_code;
$options[$_code.'_'.$_code] = $_title . " ($_code)";
}
return $options;
}

Magento Admin Grid is Empty

I am trying to create a custom module.When i click a module menu,empty grid is displaying.Log is not showing any errors
Grid.php
class Training_Banners_Block_Adminhtml_Banners_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('bannersGrid');
$this->setDefaultDir('ASC');
$this->setDefaultSort('banner_id');
$this->setSaveParamatersInSession(true);
}
protected function _prepareCollection()
{
$collection=Mage::getModel('banners/manage')->getCollection();
$this->setCollection($collection);
Mage::log(var_dump($collection));
return $collection;
}
protected function _prepareColumns()
{
$this->addColumn('banner_id', array(
'header' => Mage::helper('banners')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'banner_id'
));
$this->addColumn('name', array(
'header' => Mage::helper('banners')->__('Name'),
'align' =>'left',
'index' => 'name'
));
return parent::_prepareColumns();
}
}
banners.xml
<?xml version="1.0"?>
<layout version="0.1.0">
<adminhtml_banners_index>
<reference name="content">
<block type="banners/adminhtml_banners" name="training.banners" />
</reference>
</adminhtml_banners_index>
</layout>
Controller
<?php
class Training_Banners_Adminhtml_BanneradminController extends Mage_Adminhtml_Controller_Action
{
public function _initAction()
{
$this->loadLayout()->_setActiveMenu('banners/banners')
->_addBreadcrumb(Mage::helper('adminhtml')->__('Banners Manager'), Mage::helper('adminhtml')->__('Banners Manager'));
return $this;
}
public function indexAction()
{
$this->_initAction();
$this->loadLayout();
$this->_addContent($this->getLayout()->createBlock('banners/adminhtml_banners'));
$this->renderLayout();
}
}
First Please clear your cache and then logout and login.
Also please check the config.xml file ,whether the block and other declarations are same..

Resources