0
votes

In yii2 , after search if there is only 1 result how to automatically get in to the detail view page.

Thank you.

2

2 Answers

1
votes

in your controller after $dataprovider:

$count=$dataProvider->getTotalCount();

if($count==1){

$dataProvider->getModels();
// get id and redirect view
//redirect to view

}else{

//redirect to gridview or listview

}
0
votes

I think this will be it in case of basic usage of yii2 ..

     $searchModel = new PostSearch();   // Search Model can be created by gii 
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $count=    $dataProvider->getTotalCount();

              if($count==1){

                    $a =   $dataProvider->getModels();
                     $id = $a[0]['id'] ;    // accessing 2nd level array elements   or $dataProvider->getModels()[0]['id'];

                     return $this->render('view', [
                         'model' => $this->findModel($id), //findModel($id) is protected function in the controller
                     ]);

              }