douguwo2275 2018-11-27 11:15
浏览 414
已采纳

即使数据正确有效,validate方法也总是返回false [Yii2]

Target: I want to create a record after I find out that model is valid otherwise get back to model form page with validation errors.

Problem: validation always returns false. Even all rules are proper. I have tried to make mistake in my rules by adding fields that are not existing still I get no validation errors at all.

Scenario: Form gets validated fine, fields are validated as they should be. When I hit submit after entering valid input (every field is valid), the values get in $model->attributes get just as they should be. But when it comes to validating that model in my controller, $model->validate() always return false.

Here is my code for workaround:

My View File (_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>
<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>

My Model Class (rules(), beforeValidate() methods):

    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();
    }

Controller Class - 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]);
}

I have no idea why I get no validation at all. Please let me know If I'm missing something.

Note: I am extending my model with \yii\base\model.

  • 写回答

1条回答 默认 最新

  • du27271 2019-01-01 05:33
    关注

    I have no idea why but adding the following line by the closing of beforeValidate() method seems to have fixed this issue for me.

    return parent::beforeValidate();
    

    I think the reason might be because I was not returning updated rules for model to process for validations of model data.

    Still, no idea. but it helped.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题