validate方法始终返回false,即使数据正确且有效[Yii2]

时间:2018-11-27 11:15:11

标签: php yii2

目标: 发现模型有效后,我想创建一条记录,否则返回带有验证错误的模型表单页面。

问题: 验证总是返回false。甚至所有规则都是正确的。我试图通过添加不存在的字段来在规则中犯错,但我仍然没有任何验证错误。

场景: 表单可以通过验证,字段可以通过验证。当我在输入有效输入(每个字段都有效)后点击Submit时,在$ model-> attributes中获取的值与应有的值相同。但是,在我的控制器中验证该模型时,$ model-> validate()始终返回false。

这是我的解决方法代码:

我的查看文件(_form.php)

   <div class=''>
        <?php $form = ActiveForm::begin([
                'options' => [
                    'enctype' => 'multipart/form-data'
                ],
                'id' => 'create-company-form',
                'layout' => 'horizontal',
                'fieldConfig' => [
                    'template' => "{label}{input}{error}",
                    'labelOptions' => ['class' => 'control-label'],
                ],
        ]); ?>

            <?php echo $form->field($model, 'name')->textInput(['autofocus' => true, 'placeholder'=> \Yii::t('main', 'Name')]); ?>
            <?php echo $form->field($model, 'idcompanytype')->dropDownList(CompanyType::listCompanyTypesDropDown(), ['prompt'=> \Yii::t('main', 'Select Company Type')]); ?>
            <?php echo $form->field($model, 'datecreation')->textInput(['type'=>'text','format'=>'php:Y-m-d',  'placeholder'=> \Yii::t('main', 'Enter Date')]); ?>


            <?php echo $form->field($model, 'phone')->textInput(['placeholder'=> \Yii::t('main', 'Phone 1')]); ?>
            <?php echo $form->field($model, 'phone2')->textInput(['placeholder'=> \Yii::t('main', 'Phone 2')]); ?>

            <?php echo $form->field($model, 'email')->textInput(['type'=>'email', 'placeholder'=> \Yii::t('main', 'Email Address')]); ?>
            <?php echo $form->field($model, 'email2')->textInput(['type'=>'email', 'placeholder'=> \Yii::t('main', 'Email Address 2')]); ?>

            <?php echo $form->field($model, 'link')->textInput(['placeholder'=> \Yii::t('main', 'Link 1')]); ?>
            <?php echo $form->field($model, 'link2')->textInput(['placeholder'=> \Yii::t('main', 'Link 2')]); ?>

            <?php echo $form->field($model, 'identification')->textInput(['placeholder'=> \Yii::t('main', 'Identification')]); ?>
            <?php echo $form->field($model, 'identification2')->textInput(['placeholder'=> \Yii::t('main', 'Identification 2')]); ?>


            <?php echo $form->field($model, 'isdefault')->checkbox([
//              'template' => "<div class=\"checkbox checkbox-success\">{input} {label}</div>\n<div class=\"col-lg-8\">{error}</div></div>",
// remove last div and validation gets applied
            ]) ?>

            <?php echo $form->field($model, 'form_image')->fileInput([
                'class'=>'form_image_field',
                'data-allowed_extensions' => \Yii::$app->params['allowedImageExtensions'],
                'data-allowed_MimeTypes' => \Yii::$app->params['allowedImageMimeTypes'],
                'data-allowed_file_size' => \Yii::$app->params['allowedFileSize'],
                'data-upload_url' => Url::toRoute(['document/upload-company-logo']),
            ]); ?>
            <?php echo $form->field($model, 'image')->hiddenInput(['class'=>'form-control file_name_field'])->label(false);?>

            <div class="form-group">
                <div class='col-12 col-sm-10 offset-sm-1 col-md-8 offset-md-2 col-lg-6 offset-lg-3 col-xl-4 offset-xl-4'>
                    <?php echo Html::submitButton(\Yii::t('main', 'Save'), ['class' => 'btn btn-success waves-effect waves-light m-r-10', 'name' => 'create-button']) ?>
                    <?php echo Html::a(\Yii::t('main', 'Cancel'), ['/company'], ['class' => 'btn btn-dark waves-effect waves-light']); ?>
                </div>
            </div>

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

我的模型类(rules(),beforeValidate()方法)

    public $idcompany;
    public $name;
    public $idcompanytype;
    public $datecreation;
    public $identification;
    public $identification2;

    public $phone;
    public $phone2;

    public $email;
    public $email2;

    public $link;
    public $link2;

    public $isdefault;

    public $created;
    public $updated;
    public $image;

    public $form_image;



    /**
     * (non-PHPdoc)
     * @see \yii\base\Model::rules()
     */
    public function rules()
    {
        return [
            [['name', 'idcompanytype', 'datecreation', 'identification', 'email', 'phone', 'link'], 'required'],
            [['image', 'name', 'link', 'link2', 'identification', 'identification2', 'phone', 'phone2'], 'string', 'max' => 100],
            [['idcompany', 'idcompanytype', 'created', 'updated'], 'integer'],
            [['datecreation1'], 'date', 'format'=>'php:Y-m-d'],
            [['email', 'email2', ], 'email'],
//          [['isdefault'], 'boolean'],

            [['form_image'], 'file', 'skipOnEmpty'=>true, 'extensions' => \Yii::$app->params['allowedImageExtensions'], 'mimeTypes' => \Yii::$app->params['allowedImageMimeTypes']],
        ];
    }


    public function beforeValidate()
    {
        if(null == $this->idcompany){ // case: record does not exists
            $this->created = time();
        }

        $this->updated = time();
    }

控制器类-actionCreate()

$model = new Company();

if( $model->load(\Yii::$app->request->post())){ // postback callback
    if( $model->validate() ){
        if( Company::create($model) ){
            \Yii::$app->session->setFlash('success', \Yii::t('main', ConstantHelper::TEXT_CREATE_SUCCESS));
            return $this->redirect(['/company']);
        }
        else{
            // throw exception or whatever
        }
    }
    else{
        echo '<pre>';
        print_r($model['attributes']); //I get all attributes in attributes array but no error at all
        exit;
        return $this->render('create', ['model' => $model]);
    }
}
else{
    return $this->render('create', ['model' => $model]);
}

我不知道为什么我根本没有得到验证。 如果我缺少某些东西,请告诉我。

注意: 我正在使用\ yii \ base \ model扩展我的模型。

1 个答案:

答案 0 :(得分:0)

我不知道为什么,但是通过关闭beforeValidate()方法添加以下行似乎为我解决了这个问题。

return parent::beforeValidate();

我认为原因可能是因为我没有返回模型的更新规则来处理模型数据的验证。

还是,不知道。但这很有帮助。

相关问题