2

I am new to magento and have just starting creating custom modules. I have one which adds pagination to a custom collection.

Everything works for this. My declared <frontName>custom-collection</frontName> in config.xml means that the pagaination and collection show on http://www.website.com/custom-collection

But i also now have to add 2 other pages with slightly different collections (different filtered by etc...) to have pagination.

Is it possible to reuse this same module for however many pages i want or do i need to replicate this module for every page that wants a collection with pagination?

My module setup is:

Custom
    Collection
        Block
            Collection.php
            Toolbar.php
        controllers
            IndexController.php
        etc
            config.xml
        Helper
            Data.php

Files are:

config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Custom_Collection>
            <version>0.1.0</version>
        </Custom_Collection>
    </modules>
    <frontend>
        <routers>
            <collection>
                <use>standard</use>
                <args>
                    <module>Custom_Collection</module>
                    <frontName>custom-collection</frontName>
                </args>
            </collection>
        </routers>
        <layout>
            <updates>
                <collection>
                    <file>collection.xml</file>
                </collection>
            </updates>
        </layout>
    </frontend>
    <global>
        <models>
            <collection>
                <class>Custom_Collection_Model</class>
                <resourceModel>collection_mysql4</resourceModel>
            </collection>
            <collection_mysql4>
                <class>Custom_Collection_Model_Mysql4</class>
                <entities>
                    <collection>
                        <table>collection</table>
                    </collection>
                </entities>
            </collection_mysql4>
        </models>
        <resources>
            <collection_setup>
                <setup>
                    <module>Custom_Collection</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </collection_setup>
            <collection_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </collection_write>
            <collection_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </collection_read>
        </resources>
        <blocks>
            <collection>
                <class>Custom_Collection_Block</class>
            </collection>
        </blocks>
        <helpers>
            <collection>
                <class>Custom_Collection_Helper</class>
            </collection>
        </helpers>
    </global>
</config>

IndexController.php

    class Custom_Collection_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        $this->loadLayout();  

        $head = Mage::app()->getLayout()->getBlock('head'); 
        $head->addItem('skin_js', 'js/grid.min.js');
        $head->setTitle('Custom Collection');
        $head->setDescription('.....');

        $this->renderLayout();
    }
}

Collection.php

<?php
class Custom_Collection_Block_Collection extends Mage_Core_Block_Template
{

    public function __construct()
    {
        parent::__construct();

        $collection = Mage::getModel('catalog/category')->getCollection();
        // filters...

        $this->setCollection($collection);

    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        $parent_id = Mage::app()->getStore()->getRootCategoryId();
        if($this->getRequest()->getParam('category_id',false)){
            $parent_id = $this->getRequest()->getParam('category_id');
        }
        $category = Mage::getModel('catalog/category')->load($parent_id);

        if ($headBlock = $this->getLayout()->getBlock('head')) {
            if ($title = $category->getMetaTitle()) {
                $headBlock->setTitle($title);
            }
            if ($description = $category->getMetaDescription()) {
                $headBlock->setDescription($description);
            }
            if ($keywords = $category->getMetaKeywords()) {
                $headBlock->setKeywords($keywords);
            }
        }
        $this->setTitle($category->getName());

        $pager = $this->getLayout()->createBlock('page/html_pager', 'collection.pager')->setCollection($this->getCollection());
        $pager->setAvailableLimit(array(9=>9, 12=>12, 18=>18, 36=>36, 'all'=>'all'));
        $this->setChild('pager', $pager);

        $toolbar = $this->getToolbarBlock();

        // called prepare sortable parameters
        $collection = $this->getCollection();

        // use sortable parameters
        if ($orders = $this->getAvailableOrders()) {
            $toolbar->setAvailableOrders($orders);
        }
        if ($sort = $this->getSortBy()) {
            $toolbar->setDefaultOrder($sort);
        }
        if ($dir = $this->getDefaultDirection()) {
            $toolbar->setDefaultDirection($dir);
        }
        $toolbar->setCollection($collection);

        $this->setChild('toolbar', $toolbar);
        $this->getCollection()->load();
        return $this;
    }
    public function getDefaultDirection(){
        return 'asc';
    }
    public function getAvailableOrders(){
        return array(
            'name'=> 'Name',
            'created_at'=>'Newest',
            'toprated'=>'Most Popular'
        );
    }
    public function getSortBy(){
        return 'name';
    }
    public function getToolbarBlock()
    {
        $block = $this->getLayout()->createBlock('collection/toolbar', microtime());
        return $block;
    }
    public function getMode()
    {
        return $this->getChild('toolbar')->getCurrentMode();
    }

    public function getToolbarHtml()
    {
        return $this->getChildHtml('toolbar');
    }

    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }
}

Toolbar.php

    class Custom_Collection_Block_Toolbar extends Mage_Catalog_Block_Product_List_Toolbar{
    public function getPagerHtml()
    {
        $pagerBlock = $this->getLayout()->createBlock('page/html_pager');

        if ($pagerBlock instanceof Varien_Object) {

            /* @var $pagerBlock Mage_Page_Block_Html_Pager */
            $pagerBlock->setAvailableLimit($this->getAvailableLimit());

            $pagerBlock->setUseContainer(true)
            ->setShowPerPage(true)
            ->setShowAmounts(true)
            ->setLimitVarName($this->getLimitVarName())
            ->setPageVarName($this->getPageVarName())
            ->setLimit($this->getLimit())
            ->setCollection($this->getCollection());
            return $pagerBlock->toHtml();
        }
        return '';
    }
}
  • what is the router/urs for rest of two – Amit Bera Feb 26 '15 at 17:18
  • Sorry do you mean the urls (as in this is ../custom-collection/ ? It's 'product-collection' and 'unique-collection' – odd_duck Feb 26 '15 at 17:29
0

Best way to so this by custom url system

my simple logic is

`custom-collection` internally goes to `modulename/controller/methodname/id/1/`
`product-collection` internally goes to `modulename/controller/methodname/id/2/`
`unique-collection` internally goes to `modulename/controller/methodname/id/3/`

Please add below code inside the config.xml inside the <global> tag for trigger an observer on controller_front_init_routers

<events>
    <controller_front_init_routers>
        <observers>
            <vendor_module>
                <class>Custom_Collection_Controller_Router</class>
                <method>initControllerRouters</method>
            </vendor_module>
        </observers>
    </controller_front_init_routers>
</events>

Then create the file app/code/YourcodePool/Custom/Collection/Controller/Router.php for custom route checking

<?php
class Custom_Collection_Controller_Router extends Mage_Core_Controller_Varien_Router_Abstract {
    public function initControllerRouters($observer)
    {
        $front = $observer->getEvent()->getFront();
        $front->addRouter('custom_collection', $this);
        return $this;
    }    
    public function match(Zend_Controller_Request_Http $request)
    {
        if (!Mage::isInstalled()) {
            Mage::app()->getFrontController()->getResponse()
                ->setRedirect(Mage::getUrl('install'))
                ->sendResponse();
            exit;
        }
        $urlKey = trim($request->getPathInfo(), '/');
        //split the urlKey by slash
        $parts = explode('/', $urlKey);
        //check if there are at least 3 parts (special, id and the actual id)
        //if there are less than 3 it means it's not the url you are looking for
        if (count($parts) < 3) {
            return false;
        }
        //check if every part matches what it should
        if ($parts[0] == 'custom-collection') {
            //get the id
            $id = '1';
            //TODO: add here additional check to see if $id is valid (if an entity with your id exists)
            //tell the request to map to your controller
            $request->setModuleName('module_front_key_here')
                    ->setControllerName('controller_name_here')
                    ->setActionName('action_name_here')
                    ->setParam('id', $id);
            $request->setAlias(
                Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
                $urlKey
            );
            return true;
        }elseif($parts[0] == 'product-collection'){
              $id = '2';
             $request->setModuleName('module_front_key_here')
                    ->setControllerName('controller_name_here')
                    ->setActionName('action_name_here')
                    ->setParam('id', $id);
            $request->setAlias(
                Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
                $urlKey
            );
            return true;

        }elseif($parts[0] == '3'){
              $id = 'collection3';
             $request->setModuleName('module_front_key_here')
                    ->setControllerName('controller_name_here')
                    ->setActionName('action_name_here')
                    ->setParam('id', $id);
            $request->setAlias(
                Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
                $urlKey
            );
            return true;


        }
        return false;
    }
}

then on id param change the collection at Custom_Collection_Block_Collection

  public function __construct()
    {
        parent::__construct();
    if($this->getRequest()->getParam('id')=1):
       $collection
    elseif($this->getRequest()->getParam('id')=2):
         $collection
    elseif($this->getRequest()->getParam('id')=3):
       $collection
    else:
    endif;
    ...
    // filters...

....
        $this->setCollection($collection);

    }
  • Thanks for the indepth answer and explanation , great work! – odd_duck Mar 18 '15 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.