gridviewactiverecordyii2yii2-advanced-appcactivedataprovider

yii2 create history contract from old id


I'm trying to display a contract history following old id. If an employee create new contract so he is can see the last contract in view history contract. I have tried it but only can display one last contract. if the employee have 2 last contract, in view only one appears.

this my contract controller

    public function actionView($id)
{
    $model = $this ->findModel($id);
    $employee = $model->employee;
    $params = [":old" => $employee->old_id];
    $result = Yii::$app->db->createCommand('select * from employee where id=:old or old_id=:old', $params)->queryOne();

    $contractQuery = Contract::find()->where(['id_contract' => $result]);

    $dataProvider = new ActiveDataProvider([
        'query' => $contractQuery ,
        'pagination' => [
            'pageSize' => 20,
        ],
    ]);

    return $this->render('view', [
        'model' => $model,
        'teNumDataProvider' => $teNumDataProvider,
    ]);
}

contract.php models

public function getEmployee()
{
return $this->hasOne(Employee::className(), ['id' => 'id_employee']);
}

view.php

<div class="contract-index">
<h4>History Contract</h4>

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'id',
        'id_employee',
        'startdate:date',
        'enddate:date',
        'employee_status',
        'status',

        [
            'class' => 'yii\grid\ActionColumn',
            'visible' => FALSE,
        ],
    ],
]); ?>


Solution

  • You should get the column name from the $result (eg: $result->contract_id);

    $result = Yii::$app->db->createCommand('select * from employee 
                           where id=:old or old_id=:old', $params)->queryOne();
    
    $contractQuery = Contract::find()->where(['id_contract' => $result->contract_id]);
    

    and the action if your build a var named $dataProvider you should use in render the same varname

    return $this->render('view', [
        'model' => $model,
        'dataProvider' => $dataProvider,
    ]);
    

    and last you in this way in your gridview the $dataProvider contain the values you buil wuth the query in action

     <?= GridView::widget([
       'dataProvider' => $dataProvider,
       ...