O
O
Oleg Belyay2017-10-12 20:38:05
Yii
Oleg Belyay, 2017-10-12 20:38:05

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

Yii2 how to use ActiveForm not to create a new element, but to update it?
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() ?>
    <div class="form-group">
        <div class="col-sm-offset-3 col-sm-9">
            <?= Html::submitButton(Yii::t('app', $status), 'btn btn-success') ?>
        </div>
    </div>
<?php ActiveForm::end(); ?>

I have an update going depending on whether there is an element or not. If there is, it is updated. It all happens on the index page.
Here is the controller -
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
    	$model = new ApiYandexDiskSettings;

    	$status = 'update';

    	if($model->load(Yii::$app->request->post()) && $model->validate()){
    		$model->save(false);
      }
      $firstEl = ApiYandexDiskSettings::find()->one();
      var_dump($firstEl);
      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);
    	}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lumore, 2017-10-12
@Lumore

In the controller, accept as an update:

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['/model/index']);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question