Answer the question
In order to leave comments, you need to log in
How to organize a search on a related field?
I'm doing a search on a related field. accordingly, in order to find a category in subcategories, you must enter id_category in the field, and not the name of the category. How to fix it?
model
class SubcategorySearch extends Subcategory
{
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id'], 'integer'],
[['name', 'category_id'], 'safe'],
[['name'], 'string', 'max' => 100],
];
}
/**
* {@inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Subcategory::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
//$query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->orFilterWhere([
'id' => $this->id,
//'category_id' => $this->category_id,
])->orFilterWhere(['like', 'name', $this->name])->orFilterWhere(['like', 'category_id', $this->category_id]);
return $dataProvider;
}
}
<?php $form = ActiveForm::begin([
'action' => ['index-subcategory'],
'method' => 'get'
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'category_id') ?>
<?= $form->field($model, 'name') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-outline-secondary']) ?>
</div>
<?php ActiveForm::end(); ?>
public function actionIndexSubcategory()
{
$searchModel = new SubcategorySearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
return $this->render('index-subcategory', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question