自定义验证不起作用 - Yii2-app-basic-Yii2

时间:2015-10-06 12:23:04

标签: php yii2 custom-validators yii2-basic-app

我昨天发布了一个关于单选按钮Textfield Mandatory On Radio Button的自定义验证的问题。我得到了答案。但是,这不是确切的答案。但是,它解决了我的一个问题。

实际上,我有2个单选按钮。

  • 个体
  • 事务所

当选择具有“个人”值的单选按钮时,CompanyName文本框不应是必需的。但是,当选择具有“固定”值的单选按钮时,CompanyName文本框应该是必需的。

现在发生了什么,当我选择单选按钮'Firm'并且没有填写CompanyName文本框的任何值时,数据不会插入数据库表中。精细。哪个可以。但是,错误消息未以表单形式显示。选择单选按钮固件后,应显示错误消息,因为CompanyName文本框是必需的。

我没有得到我在做错的地方。这是我的视图,控制器和型号代码。请帮助我。

register.php (VIEW)

<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
use yii\bootstrap\Modal;
use yii\helpers\Url;
?>

<?php $form = ActiveForm::begin(['id' => 'register-form']); ?>
    .
    .
    .
    <?= $form->field($model, 'AdminType')
            ->radioList(array('Individual'=>'An Individual', 'Firm'=>'Firm/Company'))
            ->label('Are You')?>
    <?= $form->field($model, 'CompanyName')->textInput()->label('Company Name')->error() ?>
    .
    .
<?php ActiveForm::end(); ?>

SiteController.php (CONTROLLER)

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use app\models\RegisterForm;

public function actionRegister()
{
    // Register Model
    $model = new RegisterForm();
    if ($model->load(Yii::$app->request->post())) 
    {
        $post = Yii::$app->request->post('RegisterForm');
        if ($model->validate())
        {

        }
        else
        {
            // HERE YOU CAN PRINT THE ERRORS OF MODEL
            echo "<pre>";
            print_r($model->getErrors());
            echo "</pre>";
        }
        return $this->refresh();
    }

}

RegisterForm.php (模特)

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use kartik\password\StrengthValidator;


class RegisterForm extends Model
{
    public $fname;
    public $lname;
    public $email;
    public $password;
    public $confirmPassword;
    public $AdminType;
    public $CompanyName;
    public $verifyCode;

    public function rules()
    {
        return [
                [['fname','lname', 'email', 'password','confirmPassword','verifyCode','AdminType'], 'required'],
                ['email', 'email'],
            ['confirmPassword', 'compare', 'compareAttribute' => 'password'], 
                ['verifyCode', 'captcha'],

        //add rule that uses the validator function
                ['AdminType','radioValidator'],
        ];
    }

    //implement the validator
    public function radioValidator($attribute)
    {
        if($this->$attribute === 'Firm')
            return $this->addError('CompanyName', 'Company Name cannot be blank');
    }
}

5 个答案:

答案 0 :(得分:1)

您应该在'enableAjaxValidation' => true中添加ActiveForm

执行此操作后,您的代码应为

<强>控制器

public function actionRegister()
{
    $model = new RegisterForm();
    if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
      \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
      return \yii\widgets\ActiveForm::validate($model);
    }

    if ($model->load(Yii::$app->request->post())) 
    {
    }
    else
    {
        // HERE YOU CAN PRINT THE ERRORS OF MODEL
        echo "<pre>";
        print_r($model->getErrors());
        echo "</pre>";
    }
    return $this->refresh();
}

查看

<?php $form = ActiveForm::begin([
           'id' => 'register-form',
           'enableAjaxValidation' => true,
]); ?>
    .
    .
    .
    <?= $form->field($model, 'AdminType')
            ->radioList(array('Individual'=>'An Individual', 'Firm'=>'Firm/Company'))
            ->label('Are You')?>
    <?= $form->field($model, 'CompanyName')->textInput()->label('Company Name')->error() ?>
    .
    .
<?php ActiveForm::end(); ?>

它可能对你有帮助。

答案 1 :(得分:1)

Atlast,我得到了答案

     //company_name
      ['company_name', 'required', 'when' => function($model){
        return ($model->user_type == 'Firm' ? true : false);
      }, 'whenClient' => "function (attribute, value) {
          return $('input[type=\"radio\"][name=\"Users[user_type]\"]:checked').val() == 'Firm';
      }"],

答案 2 :(得分:0)

如果您在没有选项的情况下致电error,则会产生错误输出

ActiveField error方法

<强> YII \部件\ ActiveField

public function error($options = [])
{
    if ($options === false) {
        $this->parts['{error}'] = '';
        return $this;
    }
    $options = array_merge($this->errorOptions, $options);
    $this->parts['{error}'] = Html::error($this->model, $this->attribute, $options);

    return $this;
}

您必须将调用error方法移至VIEW

<?= $form->field($model, 'CompanyName')->label('Company Name')->textInput() ?>

答案 3 :(得分:0)

@Nana Partykar

当您询问如何为验证码禁用ajax验证时,我尝试了这种方式。但我不确定这是否正确。

我已设置为具有此设置的表单

'enableAjaxValidation' => true,
'enableClientValidation' => false,
'validateOnSubmit' => false,

并将操作的验证更改为此(我在我的情况下删除了验证码&#39; verifyCode&#39;来自应该验证的属性。

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = 'json';
        $validateAttributes = $model->activeAttributes();
        $key = array_search('verifyCode', $validateAttributes);
        if ($key!==false) {
            array_splice($validateAttributes, $key, 1);
        }
        return \yii\widgets\ActiveForm::validate($model, $validateAttributes);
}

答案 4 :(得分:0)

实际上,您的操作方法不正确。当你调用refresh()时,你基本上重新加载页面。如果数据库中尚未更新模型,则您将看到没有任何特殊内容,并且在重新加载新模型后没有任何错误。

此代码将在您的视图中照常显示错误:

   /**
     * @return \yii\web\Response
     */
    public function actionRegister()
    {
        // Register Model
        $model = new RegisterForm();
        if ($model->load(Yii::$app->request->post()))
        {
            $post = Yii::$app->request->post('RegisterForm');
            if ($model->validate())
            {
                 // whatever
            }

//            return $this->refresh(); // do not refresh but...
        }

        // ... render the view with the current model, who's errors attribute is filled
        return $this->render('register', compact('model'));
    }

注意:此外,您不必在视图中调用errors(),ActiveFormField呈现方法会为您处理:

<?= $form->field($model, 'CompanyName')->textInput()->label('Company Name') ?>

就够了