Search code examples
yii2yii2-advanced-appyii2-basic-app

Activerecord cant update a row


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.


Solution

  • 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]);
      }