0

I want update just one column of table I'm getting this error when updating a table rows:

Call to a member function load() on null

This is my action:

public function actionAddNote(){

        $id = \Yii::$app->request->post('id');

        $model = MainRequest::findOne($id);

        if ($model->load(\Yii::$app->request->post())  && $model->validate())
        {
            if($model->update()){
                echo "1";
            }else {
                print_r($model->getErrors());
            }
        }

        return $this->renderAjax('add-extra-note',['model' => $model]);
    }

My model:

class MainRequest extends ActiveRecord {

    public static function tableName()
    {
        return "main_request";
    }


    public function behaviors()
    {
        return [
            DevNotificationBehavior::className(),
        ];
    }

    public function rules() {

        return [
            [
                ['who_req',
                'req_description',
                'req_date',
                'extra_note'

            ], 'safe']
         ];

    }

The form will render properly and I can see my text but when I submit this the error occur:

<div>

    <?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'extra_note')->textInput(); ?>
<div class="form-group">
    <?= Html::submitButton('save', ['class' => 'btn green']) ?>
</div>

<?php ActiveForm::end(); ?>

</div>

Can anybody tell what is problem ? Thank you.

Zissouu
  • 924
  • 2
  • 10
  • 17
moh
  • 433
  • 10
  • 33

2 Answers2

0

You should load the model and the use the model loaded for accessing attribute and you should manage ythe initial situation where you d0n't have a model to update but need a model for invoke the update render form eg:

public function actionAddNote(){

      $myModel = \Yii::$app->request->post();

      $model = MainRequest::findOne($myModel->id);

      if (isset($model)){
        if ($model->load(\Yii::$app->request->post())  && $model->validate())
        {
            if($model->update()){
                echo "1";
            }else {
                print_r($model->getErrors());
            }
        }

      } else {
        $model = new MainRequest();
      }

      return $this->renderAjax('add-extra-note',['model' => $model]);
  }
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

Use Simple save function or updateAttributes of Yii2:

public function actionAddNote(){

    $id = \Yii::$app->request->post('id');

    $model = MainRequest::findOne($id);

    if ($model->load(\Yii::$app->request->post())  && $model->validate())
    {
        if($model->**save**()){
            echo "1";
        }else {
            print_r($model->getErrors());
        }
    }

    return $this->renderAjax('add-extra-note',['model' => $model]);
}
Pratik Karmakar
  • 247
  • 1
  • 8