Yii2模型验证,但表单不将数据存储在数据库中


yii2 model validating but form not storing data in database

当我用$model->validate()验证我的表单时,验证工作完美,但是当所有数据都填写在表单中时,它仍然没有将数据保存到数据库,甚至没有重定向。告诉我解决方案。

下面是我的代码

actionCreate()控制器代码:

public function actionCreate()
{
    $model = new ClientUsers();
    if($model->load(Yii::$app->request->post())) {
        // && $model->validate()
        //get file instance
        $imageName = $model->first_name . '_' . Yii::$app->security->generateRandomString();
        if ($model->file = UploadedFile::getInstance($model, 'file'))
        {
            $model->profile_pic = '../../user_uploads/' . $imageName . '.' . $model->file->extension;
            $model->file->saveAs('../../user_uploads/' . $imageName . '.' . $model->file->extension);
        }
        $model->created_date = date('d-m-y h:m:s');
        $model->updated_date = date('d-m-y h:m:s');
        $model->updated_by = Yii::$app->user->identity->username;
        $model->password_hash = $model->setPassword($model->password_hash);
        $model->auth_key = $model->generateAuthKey();
        //$model->validate();
        $model->save();
        return $this->redirect(['view', 'id' => $model->id]);

    }   
    else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

模型的代码:

<?php
namespace backend'models;
use Yii;
use yii'base'Model;
/**
 * This is the model class for table "client_users".
 *
 * @property integer $id
 * @property string $first_name
 * @property string $last_name
 * @property string $email
 * @property string $mobile
 * @property integer $gender
 * @property string $profile_pic
 * @property string $address
 * @property integer $city
 * @property integer $state
 * @property integer $country
 * @property integer $pincode
 * @property string $status
 * @property string $created_date
 * @property string $updated_by
 * @property string $updated_date
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 */
class ClientUsers extends 'yii'db'ActiveRecord
{
    /**
     * @inheritdoc
     */
    public $file;
    public static function tableName()
    {
        return 'client_users';
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['first_name', 'last_name', 'email', 'mobile', 'gender',/* 'profile_pic', */'address', 'city', 'state', 'country', 'pincode', 'created_date',/* 'updated_by', 'updated_date',*/ 'username', 'auth_key', 'password_hash',/* 'password_reset_token'*/], 'required'],
            [['gender', 'city', 'state', 'country', 'pincode'], 'integer'],
            [['gender', 'city', 'state', 'country', 'pincode'], 'required'],
            [['first_name', 'last_name', 'email',  'created_date', 'updated_by', 'updated_date'], 'string', 'max' => 50],
            [['mobile'], 'string', 'max' => 20],
            [['address','profile_pic'], 'string', 'max' => 300],
            [['status'], 'string', 'max' => 10],
            [['status'],'required'],
            [['email'],'email'],
            [['username', 'password_hash', 'password_reset_token'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['file'],'safe'],
            [['file'],'file', 'skipOnEmpty' => true],
            ['email', 'unique', 'targetClass' => ''common'models'User', 'message' => 'This email address has already been taken.'],
            ['username', 'unique', 'targetClass' => ''common'models'User', 'message' => 'This username has already been taken.'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'email' => 'Email',
            'mobile' => 'Mobile',
            'gender' => 'Gender',
            'profile_pic' => 'Profile Pic',
            'address' => 'Address',
            'city' => 'City',
            'state' => 'State',
            'country' => 'Country',
            'pincode' => 'Pincode',
            'status' => 'Status',
            'created_date' => 'Created Date',
            'updated_by' => 'Updated By',
            'updated_date' => 'Updated Date',
            'username' => 'Username',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password',
            'password_reset_token' => 'Password Reset Token',
            'file' => 'Profile Picture',
        ];
    }
    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
        return "$this->password_hash";
    }
    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
        return "$this->auth_key";
    }
}

视图的代码:

use yii'helpers'Html;
use yii'widgets'ActiveForm;
use yii'helpers'arrayHelper;
use backend'models'CityMaster;
use backend'models'StateMaster;
use backend'models'CountryMaster;
/* @var $this yii'web'View */
/* @var $model backend'models'ClientUsers */
/* @var $form yii'widgets'ActiveForm */
?>
<div class="client-users-form">
    <div class="row">
    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
    <div class="col-sm-6">
    <?= $form->field($model, 'first_name')->textInput(['maxlength' => true]) ?>
    </div>
    <div class="col-sm-6">
    <?= $form->field($model, 'last_name')->textInput(['maxlength' => true]) ?>
    </div>
    </div>
    <div class="row">
    <div class="col-sm-6">
    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
    </div>
    <div class="col-sm-6">
    <?= $form->field($model, 'mobile')->textInput(['maxlength' => true]) ?>
    </div>
    </div>
    <div class="row">
    <div class="col-sm-6">
    <?= $form->field($model, 'gender')->radioList(array('1'=>'Male','0'=>'Female')); ?>
    </div>
    <div class="col-sm-6">
    <?=
   $form->field($model, 'file')->fileInput(); 
    ?>
    </div>
    </div>
    <div class="row">
    <div class="col-sm-6">
    <?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?>
    </div>
    <div class="col-sm-6">
    <?= $form->field($model, 'country')->dropDownList(
            arrayHelper::map(countrymaster::find()->all(),'id','country_name'),[
            'prompt'=>'Select Country',
            'onchange'=>'
                    $.post("index.php?r=state/lists&id='.'"+$(this).val(), function(data){
                        $("select#clientusers-state").html(data);
                        });'
            ]
    )->label('Country'); ?>
    </div>
    </div>
     <div class="row">
    <div class="col-sm-6">
    <?= $form->field($model, 'state')->dropDownList(
            arrayHelper::map(statemaster::find()->all(),'id','state_name'),['prompt'=>'Select State Name']
    )->label('State'); ?>
    </div>
    <div class="col-sm-6">
    <?php
    //$form->field($model, 'city')->textInput() 
    ?>
    <?= $form->field($model, 'city')->dropDownList(
            arrayHelper::map(citymaster::find()->all(),'id','name'),[
            'prompt'=>'Select City',
            ]
    )->label('City'); ?>
    </div>
    </div>
    <div class="row">
    <div class="col-sm-6">
    <?= $form->field($model, 'pincode')->textInput() ?>
    </div>
    <div class="col-sm-6">
   <?= $form->field($model, 'status')->dropDownList(array('10'=>'Active','0'=>'Inactive')); ?>
   </div>
   </div>
   <div class="row">
    <div class="col-sm-6">  
    <?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
</div>
    <div class="col-sm-6">

    <?= $form->field($model, 'password_hash')->passwordInput(['maxlength' => true]) ?>
</div>
</div>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>
    <?php ActiveForm::end(); ?>
</div>

您可以简单地检查模型是否已保存。如果是,则只重定向,否则打印错误。请执行以下操作,检查是否存在验证错误:

if($model->save())
{
     // redirect to view
}
else
{
    // check whether there are any errors
    echo '<pre>'; print_r($model->getErrors());
}

在你的代码中你没有检查模型验证

 if($model->validate()) {
     // your code for validate true
 }

然而,validate()没有显示您的错误。它只检查验证规则并回答真或假。

对于测试,您可以尝试:

$model->save(false);

这样,不检查验证就保存模型。如果以这种方式保存模型,这意味着您有一些验证规则不正确或一些数据不尊重它们。