You are viewing revision #2 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.
We all need SEO friendly URLs for our projects. its not always good to call route with params so we can generalise it for all models using a common function.
Following the general convention of model and control sharing common name, we can use this code to get seo friendly URL.
public function getControllerID() {
$modelClass = get_class ( $this );
$pos = strrpos ( $modelClass, '\\' );
$class = substr ( $modelClass, $pos + 1 );
return Inflector::camel2id ( $class );
}
public function getUrl($action = 'view', $id = null) {
$params = [
$this->getControllerID () . '/' . $action
];
if ($id != null)
$params ['id'] = $id;
else
$params ['id'] = $this->id;
// add the title parameter to the URL
$params ['title'] = ( string ) $this;
// absolute url
return Yii::$app->getUrlManager ()->createAbsoluteUrl ( $params, true );
}
In code code where ever you need to url to a model , you just call $model->url or $model->getUrl('view').
You may have to additionally update urlManager in config with rules for pretty url.
'<controller:[A-Za-z-]+>/<id:\d+>/<title>' => '<controller>/view',
'<controller:[A-Za-z-]+>/<id:\d+>' => '<controller>/view',
'<controller:post>/<id:\d+>/<title>' => 'blog/view',
'<controller:[A-Za-z-]+>/<action:[A-Za-z-]+>/<id:\d+>/<title>' => '<controller>/<action>',
'<controller:[A-Za-z-]+>/<action:[A-Za-z-]+>/<id:\d+>' => '<controller>/<action>',
you will get url like this.
I used to put this code:
`
public function getUrl()
{
$query = array( $this->getFilter()->getRequestVar()=>$this->getValue(),
Mage::getBlockSingleton('page/html_pager')->getPageVarName() => null // exclude current page from urls);
return Mage::getUrl('//*', array('_current'=>true, '_use_rewrite'=>true, '_query'=>$query));
}
`
In file config.xml of your custom module, rewrite class Mage_Catalog_Model_Layer_Filter_Item:
<models> .... <catalog> <layer_filter_item>Namespace_Module_Model_Catalog_Layer_Filter_Item</layer_filter_item> <catalog> .... </models>
If you liked my method sometimes I post articles in my blog and write my papers for academic publications
How to extend regex to handle non latin(cyrillic) characters?
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.