phpcakephpcakephp-3.0

CakePHP3 how to use 2 default layout


I work on cakePHP 3 Project and I want to use another default layout for Admin.

So in Login Action if it is Admin I will redirect it to dashboard admin which should have another default layout.

  public function login()
    {
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();

    if ($user) {
            $this->Auth->setUser($user);
             if($user('role')=== 'admin')
                return $this->redirect(['controller' => 'admin', 'action' => 'dashboard']);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password, try again'));
        return $this->redirect(['action' => 'home', 'controller' => 'pages']);
    }
}

But how to specify that the controller admin will use another default layout not only specify in action by using:

   //admin controller 
   public action dashboard(){
    $this->layout='default2';
     //...
}

Solution

  • For change default layout add layout change in your AppController or AdminController beforeFilter method.

    public function beforeFilter(Event $event){
        $this->viewBuilder()->layout('admin');
    }
    

    For change individual layout

    public function login()
    {
       $this->viewBuilder()->layout('login');
    }