如何删除更新表单的错误验证


yii:how to remove error validate for update form

在我的网站,如果电子邮件是注册在我的数据库,我会添加一个错误

$this->addError('email' ,'This Email already registered');

但是在更新表单中我不想看到这个错误

有什么简单的方法可以解决我的问题?

这是我的用户模型:

<?php
/**
 * This is the model class for table "users".
class Users extends CActiveRecord
{
    //   public $captcha; 
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'users';
    }
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('username, email,password', 'required'),
            array('roles_id', 'numerical', 'integerOnly'=>true),
            array('username, password', 
                      'length',
                      'max'=>255,
                      'min'=>4
                      ),
                   array('email', 'comp_email'),
               array('username', 'comp_username'),
            array('DataCreated, LastUpdated', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, username, password, DataCreated, LastUpdated, roles_id', 'safe', 'on'=>'search'),
        );
    }
    /**
     * @return array relational rules.
     */

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
                  'email'=>'Email',
            'username' => 'Username',
            'password' => 'Password',
            'DataCreated' => 'Data Created',
            'LastUpdated' => 'Last Updated',
            'roles_id' => 'Roles',
        );
    }

    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.
        $criteria=new CDbCriteria;
        $criteria->compare('id',$this->id);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('DataCreated',$this->DataCreated,true);
        $criteria->compare('LastUpdated',$this->LastUpdated,true);
        $criteria->compare('roles_id',$this->roles_id);
        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Users the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }


          public function comp_username($attributes , $params)

                {
               $username = Yii::app()->db->createCommand()
                      ->select('username')
                      ->from('users')
                      ->queryAll();
                   $y = (count($username));
            for ($x=0;$x<$y;$x++)
            {
                $usernameE[$x] = $username[$x]['username'];
            }

          foreach ($usernameE as $u)
          {
              if($this->username == $u)
              {
                  $this->addError('username' ,'This Username already registered');
                  break;
              }
          }
      }


             public function comp_email($attributes , $params)
      {
               $email = Yii::app()->db->createCommand()
                      ->select('email')
                      ->from('users')
                      ->queryAll();
                   $y = (count($email));
            for ($x=0;$x<$y;$x++)
            {
                $emailE[$x] = $email[$x]['email'];
            }

          foreach ($emailE as $u)
          {
              if($this->email == $u)
              {
                  $this->addError('email' ,'This Email already registered');
                  break;
              }
          }
      }

      public function getUsernameEmail($id)
      {
             $emailUsername = Yii::app()->db->createCommand()
                      ->select('*')
                      ->from('users')
                     ->where('id=:id', array(':id'=>$id))
                      ->queryAll();
              return $emailUsername;

      }
}

这是我在控制器中的动作更新:

public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
        // Uncomment the following line if AJAX validation is needed
         $this->performAjaxValidation($model);
        if(isset($_POST['Users']))
        {
            $model->attributes=$_POST['Users'];
                  $id=$model->id;
                $useremail =  Users::model()->getUsernameEmail($id);
             $useremailX= $useremail[0]['username'];
            $model->username=$useremailX;
             $useremailX= $useremail[0]['email'];
            $model->email=$useremailX;
                 $model->password=  crypt($model->password,'salt');
        if($model->save())
            $this->redirect(array('view','id'=>$model->id));
    }
    $this->render('update',array(
        'model'=>$model,
    ));
}

您可以通过将特定的场景应用于您的规则来实现这一点。

关于这个主题的Yii WIKI主题是一个很好的参考。

在您的规则中,您可以指定将规则应用于哪些场景。

array('email', 'unique','message'=>'Email already exists!', 'on'=>'insert')

请注意,Yii会自动注入特定的场景,这取决于对象是如何创建的。

您可以指定您自己的自定义场景。

$model = Customer::model()->findByPK($customerID);
$model->scenario = 'purchase';

这就是验证的方法,您可以将错误消息设置为空。

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
            //First parameter is your field name of table which has email value
        array('email', 'email','message'=>"The email isn't correct"),
        array('email', 'unique','message'=>'Email already exists!'),            
    );
}
https://stackoverflow.com/a/12778419/1727357

或者您可以创建自己的验证器:

public function uniqueEmail($attribute, $params)
{
     // Set $emailExist variable true or false by using your custom query on checking in database table if email exist or not.
    // You can user $this->{$attribute} to get attribute value.
     $emailExist = true;
     if($emailExist)
     {
        //do what your want
        $this->addError('email','Email already exists');
     }
}

在规则中使用此验证方法:

array('email', 'uniqueEmail','message'=>'Email already exists!'),