Yii, createUrl not working as expected
-
20-06-2021 - |
Question
I'm doing the following in a view:
<li><a href='<? Yii::app()->controller->createUrl('sources'); ?>'>sources</a></li>
However 'sources' is not appended to the path, instead the code just returns the path to the current controller.
Could anyone suggest why this might me? The code is in a module.
My url rules are as follows:
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
Solution
You should try 2 things
To get an absolute URL and not relative to the current controller or action add a leading 'slash' like:
Yii::app()->createUrl('/sources/view');
You should also make sure you are not doing something stupid like forgetting to use echo :) that happens to me sometimes...
<li><a href='<? echo Yii::app()->controller->createUrl('sources'); ?>'>sources</a></li>
OTHER TIPS
First of all , why are you even trying to access controller from the view? It's pointless and it goes against all the patterns.
Besides, you can create URLs with Yii::app()->createUrl()
. Also, you might benefit from reading the documentation on how to utilize this function.
The value 'sources'
does not fit any of the routing patterns .. try maybe following:
Yii::app()->createUrl('sources/view');
Yii::app()->createUrl('sources/foobar');
.
You forgot the echo:
<a href="<?php
echo Yii::app()->createUrl("[/][CONTROLLER][/]ACTION", array("view"=>"VIEW"));
?>">Link name</a>