数据在yii2的规则部分验证

时间:2016-02-11 19:33:31

标签: php validation yii2 rules

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

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,

            ]);
        }
    }

我在create action中写了var_dump(),检查数据是否是,当我填写所有输入时,我有这样的信息:

  

bool(false)array(7){[“Login”] => array(1){[0] => string(22)“登录   不能为空。“} [”性别“] =>数组(1){[0] =>字符串(23)”PĹeÄ   不能为空。“} [”名称“] =>数组(1){[0] =>字符串(22)”ImiÄ   不能为空。“} [”Surname“] => array(1){[0] => string(25)   “Nazwisko不能空白。” } [“BirthDate”] => array(1){[0] =>   string(31)“数据urodzenia不能为空。” } [“电子邮件”] => array(1){   [0] => string(22)“电子邮件不能为空。” } [“密码”] => array(1){   [0] => string(23)“HasĹo不能为空。” }}

当我删除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&GT;

我不知道为什么我有这个错误,当我想验证我的数据时,任何人都可以帮助我?

1 个答案:

答案 0 :(得分:1)

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

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