Tags

, , ,

Yii adalah framework yang menganut konsep MVC. Artinya bisnis logic dipisahkan dari user interface. Umumnya bisnis logic diletakkan di controler dan model. Untuk proses yang sederhana seperti login(hanya ada authenticate) atau halaman contact(hanya ada proses send email), kita bisa mengabaikan adanya model. Proses cukup ditangani di controller.
Berikut contoh membuat halaman contact

// di controller
public function actionContact()
{
    $model = new DynamicModel([
        'name', 'email', 'subject', 'body', 'verifyCode'
    ]);
    $model->addRule(['name', 'email', 'subject', 'body'], 'required')
        ->addRule(['email'], 'email')
        ->addRule(['verifyCode'], 'boolean');

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
        } else {
            Yii::$app->session->setFlash('error', 'There was an error sending email.');
        }

        return $this->refresh();
    }
    return $this->render('contact', ['model' => $model]);
}

lalu di viewnya kita tulis

<div class="row">
    <div class="col-lg-5">
        <?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
            <?= $form->field($model, 'name') ?>
            <?= $form->field($model, 'email') ?>
            <?= $form->field($model, 'subject') ?>
            <?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
            <?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
                'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
            ]) ?>
            <div class="form-group">
                <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
            </div>
        <?php ActiveForm::end(); ?>
    </div>
</div>
Advertisements