how to switch route or URL for mobile browser?

Hi everyone,

I want to have different views for desktop browser and mobile devices. So far I have the different views including model and controllers and calling the URLs directly is fine.

My Problem is : how can I best switch or redirect to mobile view when I detect that the user is calling the URL from a mobile device? My first assumption is that to go into the beforeAction method of the Controller class and get the current controller and switch to the mobile controller. But I don’t know how do I best do this and without losing the loaded values? Should I change in the \Yii::$app->controller->className() ? More importantly I want to keep all the get parameters. This means for example redirect from the URL http://domain/page1/view?id=22&type=news to http://domain/m-page1/view?id=22&type=news where m-page1 is the mobile view for the page1.

Calling both URLs directly in the browser is fine. My problem is just How to best switch from one to another without losing the get parameters values

Thanks

You can use redirect() method.

For example:





public function beforeAction($action)

{

    if (!parent::beforeAction($action)) {

        return false;

    }


    // set $isMobile


    if ($isMobile) {


        list($controller, $action) = explode('/', $this->route);

        

        // set $mobileController and $mobileAction depends on $controller and $action


        $params = Yii::$app->request->queryParams;

        $params[0] = '/' . $mobileController . '/' . $mobileAction;


        $this->redirect($params, 302)->send();

        return false; // don't run action

    }


    return true; // run action

}