【问题标题】:Yii2 Search filter dropdown with different modelsYii2 不同型号的搜索过滤器下拉菜单
【发布时间】:2017-07-05 04:38:54
【问题描述】:

我刚刚将 Yii2 用于我的应用程序。我想在索引视图中创建搜索过滤器表单,其属性来自不同模型的过滤器活动和非活动。

我有两个表“Employee”和“Contract”..

tbl_employee
id_employee
名称
出生日期
地址
等等

tbl_contract
身份证
日期
状态

在索引中我使用了这段代码

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

我想在索引视图中筛选具有有效合同和没有有效合同的员工

这个_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(); ?>

模型\员工 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]);

我的网络中的这个搜索表单

位于合同模型中的属性“状态”。这样的关系。

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

那么,如何根据合同“活动”或“非活动”创建搜索表单.. 请帮我解决这个问题。

【问题讨论】:

    标签: php datagridview yii2 yii2-advanced-app search-form


    【解决方案1】:

    似乎您已经在模型中建立了获取状态的适当关系,因此您应该为新字段搜索状态添加一个属性

    /* your related attribute */
    public $status;
    

    你已经为 p_contract 加入了一个joinwith,所以你应该添加过滤器 where for status

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

    您可以查看本教程以获取更多信息http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/(参见场景 2)

    【讨论】:

    • 感谢您的回答@sacisEdge .. 我试过了,但所有列的“状态”值都变成了“未设置”.. 怎么会这样?有什么我想念的吗?
    • 在 index.php 中我只是添加: [ 'attribute' => 'status', 'value' => function($data) { return $data->p_contract->status; }, ],
    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多