Magento – getLayout()->getBlock(”) returns false in contoller file

controllerscustom blockmagento-1.9

I want to show product grid serialization in admin in my collections module. But I am getting error of

Fatal error: Call to a member function setCollectionsProducts() on a
non-object

by printing $this->getLayout()->getBlock object I am getting Boolean false value. What is error in my below code.

CollectionsController.php

class Gdata_Collections_Adminhtml_CollectionsController extends Mage_Adminhtml_Controller_Action{

protected function _initAction()
{
    // load layout, set active menu and breadcrumbs
    $this->loadLayout()
        ->_setActiveMenu('custom/manage')
        ->_addBreadcrumb(
              Mage::helper('gdata_collections')->__('Collections'),
              Mage::helper('gdata_collections')->__('Collections')
          )
        ->_addBreadcrumb(
              Mage::helper('gdata_collections')->__('Manage Collections'),
              Mage::helper('gdata_collections')->__('Manage Collections')
          )
    ;
    return $this;
}

/**
 * Index action
 */
public function indexAction()
{       
    $this->_title($this->__('Collections'))
         ->_title($this->__('Manage Collections'));     
    $this->_initAction();
    $this->renderLayout();
}

public function newAction()
{
    // the same form is used to create and edit
    $this->_forward('edit');
}

public function editAction()
{
    $this->_title($this->__('Collections'))
         ->_title($this->__('Manage Collections'));
   
    $model = Mage::getModel('gdata_collections/collections');
  
    $id = $this->getRequest()->getParam('id');
    if ($id) {
        $model->load($id);

        if (!$model->getId()) {
            $this->_getSession()->addError(
                Mage::helper('gdata_collections')->__('Collections item does not exist.')
            );
            return $this->_redirect('*/*/');
        }
       
        $this->_title($model->getTitle());
        $breadCrumb = Mage::helper('gdata_collections')->__('Edit Item');
    } else {
        $this->_title(Mage::helper('gdata_collections')->__('Collections Item'));
        $breadCrumb = Mage::helper('gdata_collections')->__('Collections Item');
    }       
   
    $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
    if (!empty($data)) {
        $model->addData($data);
    }       
   

    Mage::register('collections_item', $model); 

    
    $this->_initAction()->_addBreadcrumb($breadCrumb, $breadCrumb);

    $this->renderLayout();
}

public function saveAction()
{
    $redirectPath   = '*/*';
    $redirectParams = array();

   
    $data = $this->getRequest()->getPost();
    if ($data) {           
       
        $model = Mage::getModel('gdata_collections/collections');

      
        $Id = $this->getRequest()->getParam('id');
        if ($Id) {
            $model->load($Id);
        }            
        
        $model->addData($data);

        try {
            $hasError = false;
          
            $products = $this->getRequest()->getPost('products', -1);
            if ($products != -1) {
            
                $model->setProductsData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($products));
                
            }
            
            $model->save();

            
            $this->_getSession()->addSuccess(
                Mage::helper('gdata_collections')->__('The collections item has been saved.')
            );

        
            if ($this->getRequest()->getParam('back')) {
                $redirectPath   = '*/*/edit';
                $redirectParams = array('id' => $model->getId());
            }
        } catch (Mage_Core_Exception $e) {
            $hasError = true;
            $this->_getSession()->addError($e->getMessage());
        } catch (Exception $e) {
            $hasError = true;
            $this->_getSession()->addException($e,
                Mage::helper('gdata_collections')->__('An error occurred while saving the news item.')
            );
        }

        if ($hasError) {
            $this->_getSession()->setFormData($data);
            $redirectPath   = '*/*/edit';
            $redirectParams = array('id' => $this->getRequest()->getParam('id'));
        }
    }

    $this->_redirect($redirectPath, $redirectParams);
}

public function deleteAction()
{
 
    $itemId = $this->getRequest()->getParam('id');
    if ($itemId) {
        try {
            // init model and delete
         
            $model = Mage::getModel('gdata_collections/collections');
            $model->load($itemId);
            if (!$model->getId()) {
                Mage::throwException(Mage::helper('gdata_collections')->__('Unable to find a news item.'));
            }
            $model->delete();

            // display success message
            $this->_getSession()->addSuccess(
                Mage::helper('gdata_collections')->__('The collections item has been deleted.')
            );
        } catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        } catch (Exception $e) {
            $this->_getSession()->addException($e,
                Mage::helper('gdata_collections')->__('An error occurred while deleting the collections item.')
            );
        }
    }

    // go to grid
    $this->_redirect('*/*/');
}

/**
 * Check the permission to run it
 *
 * @return boolean
 */
protected function _isAllowed()
{       
    switch ($this->getRequest()->getActionName()) {
        case 'new':
        case 'save':
            return Mage::getSingleton('admin/session')->isAllowed('custom/manage/save');
            break;
        case 'delete':
            return Mage::getSingleton('admin/session')->isAllowed('custom/manage/delete');
            break;
        default:
            return Mage::getSingleton('admin/session')->isAllowed('custom/manage');
            break;
    }
} 

/**
 * Grid ajax action
 */
public function gridAction()
{
    $this->loadLayout();
    $this->renderLayout();
}

public function productsAction(){
    $this->_initAction();
    $this->loadLayout();                
    $this->getLayout()->getBlock('collections.edit.tab.product')->setCollectionsProducts($this->getRequest()->getPost('collections_products', null));
    
    $this->renderLayout();
    
}

public function productsGridAction(){           

    $this->loadLayout();
    
    $this->getLayout()->getBlock('collections.edit.tab.product')->setCollectionsProducts($this->getRequest()->getPost('collections_products', null));
    
    $this->renderLayout();
    
}}  

gdata_collections.xml

<adminhtml_collections_grid>
    <block type="gdata_collections/adminhtml_collections_grid" name="root"/>
</adminhtml_collections_grid>

<adminhtml_collections_new>
    <update handle="adminhtml_collections_edit" />
</adminhtml_collections_new>

<adminhtml_collections_edit>
    <update handle="editor"/>
    <reference name="content">
        <block type="gdata_collections/adminhtml_collections_edit" name="collections_edit" />
    </reference>
    <reference name="left">
        <block type="gdata_collections/adminhtml_collections_edit_tabs" name="collections_collections_tabs">
            <block type="gdata_collections/adminhtml_collections_edit_tab_main" name="collections_edit_tab_main" />
            <block type="gdata_collections/adminhtml_collections_edit_tab_content" name="collections_edit_tab_content" />               
            <action method="addTab"><name>main_section</name><block>collections_edit_tab_main</block></action>
            <action method="addTab"><name>content_section</name><block>collections_edit_tab_content</block></action>
                 
        </block>
    </reference>    
</adminhtml_collections_edit>
    

<adminhtml_collections_products>
    <block type="core/text_list" name="root" output="toHtml">
        <block type="gdata_collections/adminhtml_collections_edit_tab_product" name="collections.edit.tab.product"/>
        <block type="adminhtml/widget_grid_serializer" name="product_grid_serializer">
            <reference name="product_grid_serializer">
                <action method="initSerializerBlock">
                    <grid_block_name>collections.edit.tab.product</grid_block_name>
                    <data_callback>getSelectedProducts</data_callback>
                    <hidden_input_name>products</hidden_input_name>
                    <reload_param_name>collections_products</reload_param_name>
                </action>
                <action method="addColumnInputName">
                    <input_name>position</input_name>
                </action>
            </reference>
        </block>
    </block>
</adminhtml_collections_products>

<adminhtml_collections_productsgrid>
    <block type="core/text_list" name="root" output="toHtml">
        <block type="gdata_collections/adminhtml_collections_edit_tab_product" name="collections.edit.tab.product"/>
    </block>
</adminhtml_collections_productsgrid>

config.xml

<config>
<modules>
    <Gdata_Collections>
        <version>1.0.0.0.1</version>
    </Gdata_Collections>
</modules>
<global>
    <models>
        <gdata_collections>
            <class>Gdata_Collections_Model</class>
            <resourceModel>collections_resource</resourceModel>
        </gdata_collections>
        <collections_resource>
            <class>Gdata_Collections_Model_Resource</class>
            <entities>
                <collections>
                    <table>gdata_collections</table>                        
                </collections>
                <collections_product>
                <table>gdata_product</table>
                </collections_product>
            </entities>
        </collections_resource>
    </models>   
    <helpers>
        <gdata_collections>
            <class>Gdata_Collections_Helper</class>
        </gdata_collections>
    </helpers>
    <blocks>
        <gdata_collections>
            <class>Gdata_Collections_Block</class>
        </gdata_collections>
    </blocks>
     <resources>
        <gdata_collections_setup>
            <setup>
                <module>Gdata_Collections</module>
                <class>Mage_Core_Model_Resource_Setup</class>
            </setup>
        </gdata_collections_setup>
    </resources>        
</global>
<frontend>
    <routers>
        <gdata_collections>
            <use>standard</use>
            <args>
                <module>Gdata_Collections</module>
                <frontName>collections</frontName>
            </args>
        </gdata_collections>
    </routers>
    <layout>
        <updates>
            <gdata_collections>
                <file>gdata_collections.xml</file>
            </gdata_collections>
        </updates>
    </layout>
</frontend>
<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <Gdata_Collections before="Mage_Adminhtml">Gdata_Collections_Adminhtml</Gdata_Collections>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>
<adminhtml>
    <layout>
        <updates>
            <gdata_collections>
                <file>gdata_collections.xml</file>
            </gdata_collections>
        </updates>
    </layout>
</adminhtml>

Product.php /*** block file*****/

 class Gdata_Collections_Block_Adminhtml_Collections_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->getCollections()->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->getCollections()->getId()){
        $constraint = '{{table}}.collections_id='.$this->getCollections->getId();
    }
    else{
        $constraint = '{{table}}.entity_id=0';
    }
    
    $collection->joinField('position',
        'gdata_collections/collections_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->getCollectionsProducts();
    
    if (!is_array($products)) {
     
        $products = array_keys($this->getSelectedProducts());
    }       
    
    return $products;       
}

public function getSelectedProducts() {
    
    $selected = Mage::registry('collections_item')->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->getCollections()->getId()
   
    ));
    
}   

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;
}

public function getCollections(){
  
    return Mage::helper('gdata_collections')->getColItemInstance();
    
}}

Best Answer

Here getBlock('collections.edit.tab.product') returns null and that is why setCollectionsProducts() is not working. From your layout udpate xml file, collections.edit.tab.product block stands for the block class Gdata_Collections_Block_Adminhtml_Collections_Edit_Tab_Product. I can see that you defined that block file correctly.

So checkout the folder path for that file, it should be app/code/<codePool>/Gdata/Collections/Block/Adminhtml/Collections/Edit/Tab/Product.php.

Also make sure, your layout update xml file resides in admin theme section. That means it's location should be at app\design\adminhtml\default\default\layout\gdata_collections.xml

Also look for any log errors for more details.

clear the cache and try again.

Related Topic