yii2 规则部分的数据验证

data validate in rule section in yii2

我在 Yii2 中创建了 CRUD。我使用了 class 扩展模型,我认为我做的很好,但是当我试图验证我的数据时,我得到了属性不能是空白的错误。当我不使用验证我的应用程序将数据正确保存到数据表时。这是我在控制器中创建和更新的操作:

public function actionCreate()
    {
        $model = new UrUserForm();

        $model->scenario = 'create';
        var_dump($model->validate(), $model->getErrors());
        exit();
        if ($model->load(Yii::$app->request->post())&& $model->saveUser()) {
           Yii::$app->session->setFlash('success', 'Użytkownik został dodany');
            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,

            ]);
        }
    }

    public function actionUpdate($id)
    {
        $model = UrUserForm::findOne($id);
        if (!$model) {
            Yii::$app->session->setFlash('error', 'Niestety wystąpił błąd. Przosze skontaktować się z administratorem');
            return $this->redirect(['index']);
        }
        $model->scenario = 'update';
        if ($model->load(Yii::$app->request->post()) && $model->updateUser()) {
            Yii::$app->session->setFlash('success', 'Dane zostały zapisane');
            return $this->redirect(['index']);
        } else {
            return $this->render('update', [
                'model' => $model,

            ]);
        }
    }

我在上面的创建操作中写了 var_dump(),以检查数据是否正确,当我填写所有输入时,我收到此消息:

bool(false) array(7) { ["Login"]=> array(1) { [0]=> string(22) "Login cannot be blank." } ["Sex"]=> array(1) { [0]=> string(23) "PĹeÄ cannot be blank." } ["Name"]=> array(1) { [0]=> string(22) "ImiÄ cannot be blank." } ["Surname"]=> array(1) { [0]=> string(25) "Nazwisko cannot be blank." } ["BirthDate"]=> array(1) { [0]=> string(31) "Data urodzenia cannot be blank." } ["Email"]=> array(1) { [0]=> string(22) "Email cannot be blank." } ["Password"]=> array(1) { [0]=> string(23) "HasĹo cannot be blank." } }

当我删除 var_dump 时,它会正确保存,但我知道我应该验证此数据。 有我的 UrUserForm:

<?php

namespace backend\modules\users\models;

use common\models\User;
use backend\modules\users\models\UrUser;
use yii\base\Model;
use Yii;
use yii\helpers\Url;


class UrUserForm extends Model {

    public $Login;
    public $Email;
    public $Password;
    public $Sex;
    public $Country;
    public $Language;
    public $Category;
    public $AccoutType;
    public $Name;
    public $Surname;
    public $BirthDate;
    public $RulesAccept;
    public $user;

    public function rules() {
        return [
            [['Country', 'Language', 'Category'], 'safe'],
            ['Login', 'filter', 'filter' => 'trim'],
            [['Login', 'Sex', 'Name', 'Surname', 'BirthDate'], 'required'],
            ['Login', 'unique', 'targetClass' => '\common\models\User', 'message' => Yii::t('app', 'Pdany login jest już używany')],
            ['Login', 'string', 'min' => 2, 'max' => 255],
            ['Email', 'filter', 'filter' => 'trim'],
            ['Email', 'required'],
            ['Email', 'email'],
            ['Email', 'string', 'max' => 255],
            ['Email', 'unique', 'targetClass' => '\common\models\User', 'message' => Yii::t('app', 'Podany e-mail jest już używany')],
            ['Password', 'string', 'min' => 6],
            ['Password', 'required','on' => 'create'],
        ];
    }

    public function saveUser() {

        $user = new UrUser();
        $user->Login = $this->Login;
        $user->Email = $this->Email;
        $user->RulesAccept = 1;
        $user->Rel_Sex = $this->Sex;
        $user->Name = $this->Name;
        $user->BirthDate = $this->BirthDate;
        $user->Surname = $this->Surname;
        $user->setPassword($this->Password);
        $user->generateAuthKey();
        $user->Rel_Country = $this->Country;
        $user->Rel_UserCategory = $this->Category;
        $user->Rel_Language = $this->Language;
        $user->status = 10;
        $this->user = $user;
        $user->created_at=time();
        if ($this->validate() && $user->validate()) {
            $user->save();
            return $user;
        }
        return false;
    }

    public function updateUser() {
        $this->user->load($this->toArray(), '');
        $this->user->Rel_Country=$this->Country;
        $this->user->Rel_Language=$this->Language;
        $this->user->Rel_UserCategory=$this->Category;
        $this->user->Rel_Sex=$this->Sex;
        $this->user->updated_at=time();
        if (!empty($this->Password)) {
            $this->user->setPassword($this->Password);
        }

        return $this->user->save();
    }




    public static function findOne($id) {
        $user = UrUser::find()->where(['Id' => $id])->one();
        $model = new UrUserForm();
        $model->load($user->toArray(), '');
        $model->Country=$user->Rel_Country;
        $model->Language=$user->Rel_Language;
        $model->Category=$user->Rel_UserCategory;
        $model->scenario = 'update';
        $model->Sex=$user->Rel_Sex;
        $model->user = $user;
        return $model;
    }

}

这是表格:

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\models\SmCountry;
use common\models\SmSex;
use common\models\SmLanguage;
use common\models\SmUserCategory;
use yii\helpers\ArrayHelper;
use kartik\date\DatePicker;

/* @var $this yii\web\View */
/* @var $model backend\modules\users\models\UrUser */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="ur-user-form">

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

    <?= $form->field($model, 'Sex')->radioList(array('1' => Yii::t('app', 'Mężczyzna'), 2 => Yii::t('app', 'Kobieta'))); ?>

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

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

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

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

    <?= $form->field($model, 'BirthDate')->widget(DatePicker::classname(), ([
        'pluginOptions' => [
            'language' => 'pl',
            'format' => 'yyyy-mm-dd',
            'todayHighlight' => true,
            'autoclose' => true,
        ]
    ])) ?>

    <label class="control-label"> <?= Yii::t('app', 'Hasło')?> </label>
    <?= $form->field($model, 'Password')->passwordInput(['placeholder' => Yii::t('app', 'Utwórz hasło'), 'value' => ''])->label('') ?>

    <label class="control-label"> <?= Yii::t('app', 'Państwo')?> </label><br>
    <?= Html::activeDropDownList($model, 'Country', ArrayHelper::map(SmCountry::find()->all(), 'Id', 'Name'), ['prompt' => 'Wybierz państwo'])?>

    <br><label class="control-label"> <?= Yii::t('app', 'Język')?> </label><br>
    <?= Html::activeDropDownList($model, 'Language', ArrayHelper::map(SmLanguage::find()->all(), 'Id', 'Name'), ['prompt' => 'Wybierz język'])?>

    <br><label class="control-label"> <?= Yii::t('app', 'Kategoria')?> </label><br>
    <?= Html::activeDropDownList($model, 'Category', ArrayHelper::map(smUserCategory::find()->all(), 'Id', 'Name'), ['prompt' => 'Wybierz kategorię'])?>


    <div class="form-group">
    <?= Html::submitButton(Yii::t('app', 'Dodaj'), ['class'=> 'btn btn-success']) ?>
    </div>

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

</

div>

我不知道为什么我想验证我的数据时出现此错误任何人都可以帮助我吗?

属性为空,因为您在将它们加载到模型实例之前进行了转储。

先尝试 $model->load(Yii::$app->request->post())。然后你可以正确使用方法 $model->validate()$model->save().