Hi guys i am trying to search data using $searchModel in a view file and having problem displaying and searching related table.
Here is my SearchModel
where clubname
is related data from organiser
table and i am trying to search it in Event
form.
public function rules()
{
return [
[['title', 'description', 'location', 'clubname'], 'safe'],
];
}
public function search($params)
{
$query = Event::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
$query->joinWith(['organiser']);
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;
}
$query->andFilterWhere([
'id' => $this->id,
'interest_id' => $this->interest_id,
]);
$query->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['like', 'description', $this->description])
->andFilterWhere(['like', 'location', $this->location]);
$query->andFilterWhere(['like', 'organiser.clubname', $this->organiser_id]);
return $dataProvider;
}
Here is my $search
page and list below it
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<div class="row">
<?= $form->field($searchModel, 'title',[
'template' => ' <div class="col-lg-2 col-md-2 col-sm-2 col-xs-3">{label}</div><div class="col-lg-4 col-md-4 col-sm-6 col-xs-8">{input}</div>'
])->textInput(['maxlength' => true]) ?>
<?= $form->field($searchModel, 'clubname',[
'template' => ' <div class="col-lg-2 col-md-2 col-sm-2 col-xs-3">{label}</div><div class="col-lg-4 col-md-4 col-sm-6 col-xs-8">{input}</div>'
])->textInput(['maxlength' => true]) ?>
</div>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary btn-xs']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default btn-xs']) ?>
</div>
<?php ActiveForm::end(); ?>
There is no problem in search for title
but i want user to also be able to search using clubname
which is field in Organiser
table and they have relation with id
.
You need to add RelationName.property
in searchModel
:
public function rules()
{
return [
[['title', 'description', 'location', 'organiser.clubname'], 'safe'],
];
}
Then add attributes()
function :
public function attributes()
{
return array_merge(parent::attributes(),
[
'organiser.clubname',
]
);
}
And Finally add query to search data:
$query->andWhere(['Attribute_name' => $params['attribute']]);