cakephp isUnique for 2 fields?

后端 未结 6 1618
醉梦人生
醉梦人生 2020-12-05 16:36

I have a registration form in which users can fill in two email address (email1 & email2). Marketing\'s requirement is that they need to be unique (unique as in if we ha

6条回答
  •  一向
    一向 (楼主)
    2020-12-05 17:39

    I posted a solution to this on the CakePHP Google Group:

    http://groups.google.com/group/cake-php/browse_frm/thread/b3a1e4ae3eeb6091/e168f54bac27c163?lnk=gst&q=checkUnique#e168f54bac27c163

    Add the following to your AppModel:

            /** 
             * checks is the field value is unqiue in the table 
             * note: we are overriding the default cakephp isUnique test as the 
    original appears to be broken 
             * 
             * @param string $data Unused ($this->data is used instead) 
             * @param mnixed $fields field name (or array of field names) to 
    validate 
             * @return boolean true if combination of fields is unique 
             */ 
            function checkUnique($data, $fields) { 
                    if (!is_array($fields)) { 
                            $fields = array($fields); 
                    } 
                    foreach($fields as $key) { 
                            $tmp[$key] = $this->data[$this->name][$key]; 
                    } 
                    if (isset($this->data[$this->name][$this->primaryKey])) { 
                            $tmp[$this->primaryKey] = "<>".$this->data[$this->name][$this- 
    >primaryKey]; 
    
                    } 
                    return $this->isUnique($tmp, false); 
            } 
    } 
    

    and is used in your model validate:

            var $validate = array( 
                    "name"=>array( 
                            "unique"=>array( 
                                    "rule"=>array("checkUnique", array("name", "institution_id")), 
                                    "message"=>"A contact with that name already exists for that 
    institution" 
                            ) 
                    ) 
           ); 
    

提交回复
热议问题