How to create pretty url in yii for module

462 views Asked by At

I have searched a lot and tried a lot to do this , but no luck . I have referred this LINK. But it didn't solve my problem . I have a user module installed in yii (yii 2) . and i have user profile url like

http://192.168.1.31/Eb/user/profile?uguid=ac0c4558-77fc-4896-9b30-f77afe4d81cd


but i want this to like

http://192.168.1.31/Eb/user/profile/ac0c4558-77fc-4896-9b30-f77afe4d81cd


I mean without guid query string parameter . I am trying in url manager like this

'urlManager'=>array(
                'urlFormat'=>'path',
                'showScriptName'=>false,
                'rules'=>array(
           '<controller:\w+>/<action:\w+>/<guid:\d+>'=>'<controller>/<action>',
            '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            ),

How it is possible ??

2

There are 2 answers

0
Taron Saribekyan On

In Yii UrlManager keys of rules parameter (attribute) must be regex pattern. If I understand true your url have a structure CONTROLLER/ACTION (in my case Eb is subfolder), so your rules must be:

'urlManager'=>array(
   'urlFormat'=>'path',
   'showScriptName'=>false,
   'rules'=>array(
        '<controller:\w+>/<action:\w+>/<uguid:\w+>' => '<controller>/<action>',
        '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
    ),
)

Be careful, that your uguid parameter not number so you must use w+ instead of d+

So you can create urls using createUrl:

Yii::app()->createUrl('user/profile', array('uguid' => 'USER_ID'))

Result must give which you want.

0
Apoorv Joshi On

Your current url can also be accessed using

http://192.168.1.31/Eb/user/profile/uguid/ac0c4558-77fc-4896-9b30-f77afe4d81cd

You can remove your controller name by adding the following line in urlmanager rules:

'/Eb/user/profile/<id:([0-9a-zA-Z_\-]+)' => 'Eb/user/profile/uguid/<id>'

That should do the trick :)