Ryan Pasaribu
Ryan Pasaribu

Reputation: 51

Yii2 Search filter dropdown with different models

I just used Yii2 for my app. I'm want to create search filter form in index view with attribute from different model for filter active and not active.

I've two tables "Employee" and "Contract"..

tbl_employee
id_employee
name
dob
address
etc.

tbl_contract
id
date
status

in index I used this code

<?php echo $this->render('_search', ['model' => $searchModel]); ?>

I want to filter employee in index view who has an active contract an who's not

This _search.php

<?php $form = ActiveForm::begin([
    'action' => ['index'],
    'method' => 'get',
]); ?>

<?= $form->field($model, 'id_number')->textInput(['maxlength'=>6,'style'=>'width:225px']) ?>

<?= $form->field($model, 'name') ->textInput(['maxlength'=>30,'style'=>'width:225px']) ?>              

<?php $data = ['Active'=> 'Active', 'Inactive'=>'Inactive'];

echo '<label class="control-label">Status</label>';
echo Select2::widget([
'name' => 'Status_Contract',
'data' => $data,
'options' => [
    'placeholder' => 'Select Status Contract ...',
    ],
]);
?>

<div class="form-group">
    <?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-success']) ?>
    <?= Html::a('Reset', ['/employee/index'], ['class'=>'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>

Models\employee EmpSearch.php

$query = Employee::find()->joinWith('p_contract');

$dataProvider = new ActiveDataProvider([
        'query' => $query,

if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }
    ]);
$query->andFilterWhere([
'id' => $this->id,
]);

$query->andFilterWhere(['like', 'name', $this->name]);

This search form in my web

enter image description here

Attribute "status" located in Contract Models. the relation like this.

public function getP_contract()
{
    return $this->hasOne(Contract::className(), ['id_emp' => 'id_employee', 'id' => 'id_contract']);
}

So, How can I create search form based on contract "active" or "Inactive".. Please help me solve this problem.

Upvotes: 2

Views: 2171

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133380

seems You have already a proper relation in model for get status so you should add an attribute for your new field search status

/* your related attribute */
public $status;

and you have alredy a joinwith for p_contract so you should add the filter where for status

 // filter by status
   $query->joinWith(['p_contract' => function ($q) {
       $q->where('contratct_table_name.status LIKE "%' . $this->status. '%"');
}]);

you can take a look at this tutorial for more info http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/ (see scenario 2)

Upvotes: 1

Related Questions