I want to create searchModel with Yii2, my query have default limit is 7, and I have an input dropdownlist on the page to switch limit of query between 7 and 30.
How I can do this?
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($modelSearch, 'limit')->dropDownlist([
7 => '7 days',
30 => '30 days',
]); ?>
<?php ActiveForm::end(); ?>
and this is Model
class SearchModel extend \yii\base\Models
{
public $limit;
public function search($params) {
$query = Objects::find()->where(['attribute1'=>'a', 'attribute2'=>b]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['attributes' => ['attribute1', 'attribute2',]]
]);
$this->load($params);
return $dataProvider;
}
}
and this is controller
public function actionIndex()
{
$searchModel = new ModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->post());
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
I've tried to add
if(empty($params['limit'])) {
$query->limit(7);
}else {
$query->limit($params['limit']);
}
into the models - it worked but I think it's not a smart way to resolve it.
You may define SearchModel like:
<?php
namespace app\models\search;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Human;
/**
* Class HumanSearch
*
* @package app\models\search
*/
class HumanSearch extends Model
{
/**
* @var int $limit
*/
public $limit;
/**
* @return array
*/
public function rules(): array
{
return [
[['limit'], 'integer', 'min' => 7, 'max' => 30], // Limit can be between 7 and 30.
[['limit'], 'default', 'value' => 7], // Default query limit is 7 rows.
];
}
/**
* @param array $params
*
* @return ActiveDataProvider
*/
public function search(array $params): ActiveDataProvider
{
// Initialize query.
$query = Human::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// Load additional params to search model.
if (!$this->load($params) && $this->validate()) {
return $dataProvider;
}
// Set query limit.
$query->limit($this->limit);
return $dataProvider;
}
}
And then use it in actionIndex()
in Controller:
<?php
namespace app\controllers;
use Yii;
use yii\rest\Controller;
use yii\data\ActiveDataProvider;
use app\models\search\HumanSearch;
class HumanController extends Controller
{
public function actionIndex(): ActiveDataProvider
{
$params = Yii::$app->getRequest()->getQueryParams();
$search = new HumanSearch;
return $search->search($params);
}
}