简体   繁体   中英

Saving Form Data Into Database Table YII2

So I'm trying to get information through a Yii2 form and save it into the database, though it won't work. I'm getting the success flash message, but no changes are made into the database.

Controller file:

<?php

namespace frontend\modules\portfolio\controllers;

use Yii;
use yii\web\Controller;
use frontend\modules\portfolio\models\LandingPage;
use common\models\HelloMessage;

class HelloController extends Controller {

    public function actionIndex() {

        $form_model = new HelloMessage();
        $request    = Yii::$app->request; 

        if ($form_model->load(Yii::$app->request->post())) {
            $form_model->name = $request->post('name');
            $form_model->email = $request->post('email');
            $form_model->message = $request->post('message');

            $form_model->save();
            Yii::$app->getSession()->setFlash('success', 'Your message has been successfully recorded.');
        }

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

}

And this would be the View file:

        <div class="box">
            <?= Yii::$app->session->getFlash('success'); ?>

            <?php $form = ActiveForm::begin(); ?>

            <?= $form->field($form_model, 'name')->textInput(['maxlength' => true]) ?>

            <?= $form->field($form_model, 'email')->textInput(['maxlength' => true]) ?>

            <?= $form->field($form_model, 'message')->textarea(['maxlength' => true]) ?>

            <div class="form-group">
                <?= Html::submitButton('Submit', ['name' => 'contact-button']); ?>
            </div>

            <?php ActiveForm::end(); ?>
        </div>

change your index action like that

    $form_model = new HelloMessage();
    $postData   = Yii::$app->request->post(); 

    if ($form_model->load($postData)) {
        if (!$form_model->save()) 
            print_r($form_model->getErrors()); // this would be helpful to find problem.
        else 
            Yii::$app->getSession()->setFlash('success', 'Your message has been successfully recorded.');
    }

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

Most likely your model fails validation. You can turn if off using $form_model->save(false) , but it is better to know why it is not validating. Do this:

if (!$form_model->validate()) {
  return $this->render('index', [
            'form_model' => $form_model
        ]);
}

Ok, so I've found the solution: $model->save(false) - without any validation. Will try to sort out the validation rules in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM