I’m having trouble converting functionality I have in my Yii1.1 app into a Yii2. Specifically it’s around switching themes dynamically using dkeeper/yii2-mobiledetect. In version Yii1.1, I was able to add my mobile/tablet/classic views under a @app\themes\{theme name folder} like this…
myapp\
protected\
views\
wines\
index.php
themes
mobile\
css\
views\
wines\
index.php
tablet\
css\
views\
wines\
index.php
classic\
views\
wines\
index.php
In Yii1.1 @app\components\Controller.php I updated the init() method to:
public function init()
{
//read and store current user data so it's available in all controllers
if (!Yii::app()->user->isGuest)
{
$this->userData = User::model()->findByPk(Yii::app()->user->id);
}
//theme defaults to classic in config/main.php
//we set it here to either mobile or tablet as appropriate
$detector = Yii::app()->mobileDetect;
if ($detector->isTablet())
{
Yii::app()->theme = 'tablet';
}
elseif ($detector->isMobile())
{
Yii::app()->theme = 'mobile';
};
parent::init();
}
This worked just fine. The views automatically switched based on the type of browser detected by MobileDetect.
I need some guidance on how to accomplish the same in Yii2. I’m using Kartik’s version of the basic template kartik-v/yii2-app-practical-b. I’ve been able to add a new themes folder under “Source Files” and updated the theme info in config\web.php components[]view[] and it works just fine for 1 theme, I’m just not sure where/how to change it based on mobiledetect.
The MobileDetect install has me update the @app\index.php like this. My first thought is to use YII::$app->set() to update the components just before application->run(). Is there a better way to do this?
$config = require(__DIR__ . '/config/web.php');
$application = new yii\web\Application($config);
Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST,function($event){
Yii::$app->params['detect'] = [
'isMobile' => Yii::$app->mobiledetect->isMobile(),
'isTablet' => Yii::$app->mobiledetect->isTablet(),
];
});
$application->run();
Thanks,
Jim