Yii2 how to use ActiveForm not to create a new element, but to update?

The form:

<?$form = ActiveForm::begin($config);?> <?= $form->field($model, 'save_images_post')->checkbox()?> <?= $form->field($model, 'folder_save_images_post')->textInput()?> <?= $form->field($model, 'save_backups')->checkbox()?> <?= $form->field($model, 'folder_save_backups')->textInput()?> <?= $form->field($model, 'path_backups')->textInput()?> <?= $form->field($model, 'token_yandex_disk')->textInput()?> <?= $form->field($model, 'id_yandex_disk')->textInput()?> <?= $form->field($model, 'password_yandex_disk')->textInput()?> <?= $form->field($model, 'access_to_more_yandex_disk_link')->checkbox()?> <?= Html::submitButton(Yii::t('app', $status), 'btn btn-success')?> <?php ActiveForm::end();?> 

I have an update depending on whether there is an item or not. If there is something updated. This all happens on the index page.

Here is the controller -

 class DefaultController extends Controller { public function actionIndex() { $model = new ApiYandexDiskSettings; $status = 'update'; if($model->load(Yii::$app->request->post()) && $model->validate()){ $model->save(false); } $firstEl = ApiYandexDiskSettings::find()->one(); if(empty($firstEl)){ $status = 'create'; }else{ $status = 'update'; } return $this->render('index', array('status' => $status, 'model' => $firstEl)); } } 

I try to update using update () but it returns false

 if(Yii::$app->request->get('status','update')){ $model->update(); }else{ $model->save(false); } 

    1 answer 1

    It's all about the implementation of ApiYandexDiskSettings, if it's just ActiveRecord:

    Judging by the code, you have only one entry in the database for this object. you can do this

     $model = ApiYandexDiskSettings::find()->one(); if (!$model) { $model = new ApiYandexDiskSettings(); } $model->load(Yii::$app->request->post()) && $model->save(); return $this->render('index', array('status' => $model->isNewRecord, 'model' => $model));