2

Can anyone suggest me how to hide both controller & action name from url in yii2? I tried by writing rules but did not work. this is my anchor tag:

 <?php echo Html::a($model->title, ['category/view/', 'type' => $model->category->urlValue,'parameter' => $model->urlValue]); ?>

MY current url is like this :

http://localhost/project/category/view/news-and-events/dosarrest-strong-performer-in-2015-forrester-wave-for-ddos-service-providers-1

But I want it like this:

http://localhost/project/news-and-events/dosarrest-strong-performer-in-2015-forrester-wave-for-ddos-service-providers-1
3
  • 1
    For that you have to create URL rule and .htaccess file. Commented Aug 5, 2015 at 5:59
  • include your url manager config with question Commented Aug 5, 2015 at 8:31
  • Write .htaccess rule for that :) Commented Aug 5, 2015 at 9:55

2 Answers 2

3

It finally worked by writing a rule in main.php file as follows :

'<type:[A-Za-z0-9-]+>/<param:[A-Za-z0-9 -_.]+>' => 'category/view',
Sign up to request clarification or add additional context in comments.

Comments

1

YOu chould create your own UrlRule. Something like:

class CustomUrlRule extends Object implements UrlRuleInterface {
    public function createUrl($manager, $route, $params)
    {
        $parts = explode('/', $r);
        if ($route === 'category/view' 
            && isset($params['type'])
            && isset($params['parameter'])
        ) {
            $url = generate some url;
            unset($params['view'], $params['parameter']);
            if (count($params)) {
                $url .= '?' . http_build_query($params);
            }

            return $url;
        }

        return false; 
    }
    public function parseRequest($manager, $request)
    {
        //parse request url and return true if it's url for category/view 
    }
}

and dont forget to add to config

config/web.php:
...
'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        [
        'class' => 'app\components\CustomUrlRule',
        ],
    ...
    ],
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.