1
votes

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>\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>

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
do you have any scenarios defined for the model? and please share us all of your model class. - Mohammad
I might be wrong but I think that there is no such method errors() in model, I think you can get errors accessing property $model->errors or calling method getErrors() on it - ArtOsi
as @ArtOsi said, there is no errors() method in the model class, unless you defined it manually ! yiiframework.com/doc/api/2.0/yii-base-model - Mohammad
And also you checking in if statement if model is loaded $model->load(\Yii::$app->request->post() so if it returns "false" then you just render your view file again and don't get any errors I believe - ArtOsi
What is your request data (\Yii::$app->request->post())? Can you please update post - Damian Dziaduch

1 Answers

0
votes

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.