2015-12-24 61 views
0

I.E.如果我更新address_line1,那麼它給出分配的手機號碼的錯誤。 雖然更新它不應該與它自己匹配。 即使我改變手機號碼,它應該檢查與其他用戶。提前Yii2樣板規則同步記錄更新檢查規則

public function rules() 
    { 
     return [ 
        [['mobile_number','address_line1','address_line2','city','state','country','pincode' ],'required'], 
        ['mobile_number','mobile_number_allocation_validate'], 

     ]; 
    } 

public function mobile_number_allocation_validate($attribute){ 
     // add custom validation 
     $result = User::find() 
     ->where('`mobile_number` = "'.$this->$attribute.'" AND 
       `status` = "A" ')->all(); 
     if(!empty($result)){ 
      $this->addError($attribute,'Mobile number is allocated to other vehicle'); 
     } 

    } 

感謝

+1

有沒有一個原因,不只是使用'唯一'驗證器? –

+0

@JoeMiller重複將在那裏,但我需要篩選活動user.as我不會從數據庫中刪除我的單行。 – Santosh

回答

0

改變你的條件爲: - 覆蓋的User ActiveRecord

/** 
* BeforeSave() check if User ActiveRecord is created with same calculator param 
* if created then return false with model error 
* 
*/ 
public function beforeSave($insert){ 
    $model = self::find()->where('`mobile_number` = "'.$this->$attribute.'" AND 
      `status` = "A" ')->all(); 

    if($model !== null && $model->id !== $this->id){ 
     $this->addError('mobile_number' , 'Mobile number is allocated to other vehicle'); 
     return false; 
    } 

    return parent::beforeSave($insert); 
} 
+0

$ this-> id哪個id會引用? (試圖獲得非對象的屬性) – Santosh

+0

想知道以上模型是用戶ActiveRecord任何其他模型類的類別..除用戶類別 –

+0

沒有單一類別只有 – Santosh

0

您應該能夠使用unique驗證這一點,beforeSave()通過簡單地增加一個filter條件像這樣

public function rules() 
    { 
     return [ 
      [['mobile_number','address_line1','address_line2','city','state','country','pincode' ],'required'], 
      ['mobile_number','unique', 'filter' => ['status' => 'A']], 
     ]; 
    }