Gernerate custom urls within Magento
Asked Answered
N

3

10

I am currently looking at trying to generate custom urls/routing using magento, currently I have set a default route in config.xml within the local module.

<frontend>
 <routers>
         <portfolios>
             <use>standard</use>
             <args>
                 <module>Custom_Portfolios</module>
                 <frontName>portfolios</frontName>
             </args>
         </portfolios>
     </routers>
     <default>
         <router>portfolios</router>
     </default>
 </frontend>

This currently works with the url path of /portfolios/index/action/custom-string which is the magento default route. What I am trying to achieve is to have /portfolios/custom-string.html I have attempted to use a mod_rewrite rule with no success, I have found some references in relation to utilising a custom suffix of .html which I have added to the same config.xml file.

<default><portfolios><seo><portfolios_url_suffix>.html</portfolios_url_suffix></seo></portfolios></default>

I have looked at the alan storm docs in relation to routing and found it relevent to the default routing paths only or the information is a little out-dated.

Do you know the best method to control the routing within magento with possibly an easy to follow and relevent tutorial? if so please share :D many

Naturalize answered 11/11, 2010 at 12:48 Comment(0)
G
8

The way to do this is with an URL rewrite. In fact, the suffix config you found is probably used by Mage_Catalog to create it's sets of rewrites. I'm approaching this particular feature for the first time so this snippet should be taken with a pinch of salt...

// Creating a rewrite
/* @var $rewrite Mage_Core_Model_Url_Rewrite */
$rewrite = Mage::getModel('core/url_rewrite');
$rewrite->setStoreId($store_id)
        ->setIdPath('portfolios/'.$url_key)
        ->setRequestPath('portfolios/'.$url_key.'.html')
        ->setTargetPath('portfolios/index/action/id/'.$url_key)
        ->setIsSystem(true)
        ->save();

A new rewrite is needed for each possible path.

Edit; I've added a setIdPath because it might be necessary.

Gaggle answered 11/11, 2010 at 13:55 Comment(8)
I will investigate this further, would you know the best way to reference it from a route within the xml otherwise i will get a 404 error message come up?Naturalize
Sorry I don't understand the question.Gaggle
when i hit portfolios/blah.html it currently gets forwarded to a 404 error page, i presume this is cause the routing doesnt exist and as such its causing an issue, do you know of where i would need to reference this code as a method within the xml file or would i only need to run this code once?Naturalize
You should only need to run this once per URL. After that you can confirm it exists by looking in Catalog > URL Rewrite Management. Check it's target path is exactly what you want. I added an id because I don't know how you handle parameters, an id would be the typical use.Gaggle
After my brain got into gear i worked out how to impliment this system, many thanks for your solution.Naturalize
I was looking for this answer throwout anywhere.Finally you gave this excellent solution.Thanks lot clockHousebroken
hi, i also in sitiuation to do this same task now. please could you tell me, where to add this code na? in controller file? @GaggleEyeopening
@Eyeopening you need to save one of these rewrite objects for each URL that your data needs. Typically this means creating the rewrite when an object is saved. This is how products work, when a Mage_Catalog_Model_Product is saved it updates it's relevant rewrite too.Gaggle
H
15

Code below is untested, but should work

If you don't want to define custom rewrite for each protfolio item, just follow these steps:

  1. Write your custom router class extended from Mage_Core_Controller_Varien_Router_Standard and implement match method:

    public function match(Zend_Controller_Request_Http $request)
    {
        $path = explode('/', trim($request->getPathInfo(), '/'));
        // If path doesn't match your module requirements
        if (count($path) > 2 && $path[0] != 'portfolios') {
            return false; 
        }
        // Define initial values for controller initialization
        $module = $path[0];
        $realModule = 'Custom_Portfolios';
        $controller = 'index';
        $action = 'action';
        $controllerClassName = $this->_validateControllerClassName(
            $realModule, 
            $controller
        );            
        // If controller was not found
        if (!$controllerClassName) {
            return false; 
        }            
        // Instantiate controller class
        $controllerInstance = Mage::getControllerInstance(
            $controllerClassName, 
            $request, 
            $this->getFront()->getResponse()
        );
        // If action is not found
        if (!$controllerInstance->hasAction($action)) { 
            return false; // 
        }            
        // Set request data
        $request->setModuleName($module);
        $request->setControllerName($controller);
        $request->setActionName($action);
        $request->setControllerModule($realModule);            
        // Set your custom request parameter
        $request->setParam('url_path', $path[1]);
        // dispatch action
        $request->setDispatched(true);
        $controllerInstance->dispatch($action);
        // Indicate that our route was dispatched
        return true;
    }
    
  2. Define your custom router in config.xml:

    <stores>
        <default>
            <web>
                <routers>                               
                    <your_custom>
                        <area>frontend</area>
                        <class>Custom_Portfolios_Controller_Router_Custom</class>
                    </your_custom>
                </routers>
            </web>
        </default>
    </stores>
    
  3. Enjoy your custom routing in Magento :)

Hollington answered 11/11, 2010 at 19:41 Comment(2)
I found the solution above worked for my needs and as such didnt use this one. Thank you for taking your time to answer this question.Naturalize
And don't forget to set route name for request - it is being used for layout handle: $request->setRouteName('someRouteName')Netsuke
G
8

The way to do this is with an URL rewrite. In fact, the suffix config you found is probably used by Mage_Catalog to create it's sets of rewrites. I'm approaching this particular feature for the first time so this snippet should be taken with a pinch of salt...

// Creating a rewrite
/* @var $rewrite Mage_Core_Model_Url_Rewrite */
$rewrite = Mage::getModel('core/url_rewrite');
$rewrite->setStoreId($store_id)
        ->setIdPath('portfolios/'.$url_key)
        ->setRequestPath('portfolios/'.$url_key.'.html')
        ->setTargetPath('portfolios/index/action/id/'.$url_key)
        ->setIsSystem(true)
        ->save();

A new rewrite is needed for each possible path.

Edit; I've added a setIdPath because it might be necessary.

Gaggle answered 11/11, 2010 at 13:55 Comment(8)
I will investigate this further, would you know the best way to reference it from a route within the xml otherwise i will get a 404 error message come up?Naturalize
Sorry I don't understand the question.Gaggle
when i hit portfolios/blah.html it currently gets forwarded to a 404 error page, i presume this is cause the routing doesnt exist and as such its causing an issue, do you know of where i would need to reference this code as a method within the xml file or would i only need to run this code once?Naturalize
You should only need to run this once per URL. After that you can confirm it exists by looking in Catalog > URL Rewrite Management. Check it's target path is exactly what you want. I added an id because I don't know how you handle parameters, an id would be the typical use.Gaggle
After my brain got into gear i worked out how to impliment this system, many thanks for your solution.Naturalize
I was looking for this answer throwout anywhere.Finally you gave this excellent solution.Thanks lot clockHousebroken
hi, i also in sitiuation to do this same task now. please could you tell me, where to add this code na? in controller file? @GaggleEyeopening
@Eyeopening you need to save one of these rewrite objects for each URL that your data needs. Typically this means creating the rewrite when an object is saved. This is how products work, when a Mage_Catalog_Model_Product is saved it updates it's relevant rewrite too.Gaggle
P
0

The easiest method (when you do not need to auto-generate many urls) is to use built-in Url Rewrites module. Go to admin backend -> Catalog -> Url Rewrite management and setup any url rewrite you like.

Pourpoint answered 11/11, 2010 at 14:39 Comment(1)
Hi, i believe that this will only actually work when the url is known without pre-creating thousands of rules manually. thank you for your imput though.Naturalize

© 2022 - 2024 — McMap. All rights reserved.