Yii2: CRUD

Walau sebenarnya proses CRUD bisa dilakukan secara tradisional (raw-sql), namun disarankan tetap menggunakan cara Yii agara lebih aman. Berikut contoh menggunakannya:



public function actionCrud() {
$model = new TblBuku();
$request = Yii::$app->request;
$act = $request->post('act');

if($act=='i') {
if ($model->load(Yii::$app->request->post()) && $model->save()) {
// data is valid and saved to database
//print_r(Yii::$app->request->post());
//exit;
return $this->redirect(['index', 'id' => $model->id]);
}

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

}
if($act=='u') {
$id = $request->post('id');
$model = TblBuku::findOne($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
// data is valid and saved to database
//print_r(Yii::$app->request->post());
//exit;
return $this->redirect(['index', 'id' => $model->id]);
}

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

}
if($act=='d') {
$id = $request->post('id');
$model = TblBuku::findOne($id);
if ($model->delete()) {
// data is valid and saved to database
//print_r(Yii::$app->request->post());
//exit;
return $this->redirect(['index', 'id' => $model->id]);
}

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

}

}

di form sebagai berikut:

<div class="modal fade" id="addData" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<?php $form = ActiveForm::begin([
'id' => 'buku-form',
'action' => 'index.php?r=buku%2Fcrud']); ?>

<div class="form-body">
  <div class="form-row">
    <div class="form-group col-md-6">
<?= $form->field($model, 'title')->textInput(['autofocus' => true]) ?>
    </div>
<div class="form-group col-md-6">
<?= $form->field($model, 'author')->textInput(['autofocus' => true]) ?>
        </div>
    </div>
</div>
<div class="modal-footer">
<?= Html::hiddenInput('act', 'd') ?>
<?= Html::hiddenInput('id', 4) ?>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>

hanya sekedar catatan.

Leave a comment

I’m Eddy

Dive into my world where every page is a celebration of knowledge, particularly my fascination with computer science. Join me in this journey of exploration and learning—save the day by bookmarking knowledge that spans the breadth of computer science. Enjoy the read, and may each visit offer you something valuable to take away!


Let’s connect