发新话题
打印

symfony自定义验证数据库某个字段数据唯一性

symfony自定义验证数据库某个字段数据唯一性

验证数据库的某个字段是否已经存在了相同的数据

首先,在lib目录建立一个 sfCustomUniqueValidator.php
复制内容到剪贴板
代码:
<?php
  /**
* sfCustomUniqueValidator checks if a record exist in the database with all the mentionned fields.
*
* ex: Check if a companie with company_name exist in country_id
*   class:            sfCustomUniqueValidator
*   param:
*     class:          Companies    //the class on which the search is performed
*     nb_fields:      2            //the number of fields on which the comparison is done
*     field_1:        company_name //First field of the comparison
*     field_2:        country_id   //Other country for the comparison
*
* @package    lib
* @author     Joachim Martin
* @date       15/06/2007
*/
  
class sfCustomUniqueValidator extends sfValidator {
  
   /**
   * Executes this validator.
   *
   * @param mixed A file or parameter value/array
   * @param error An error message reference
   *
   * @return bool true, if this validator executes successfully, otherwise false
   */
  
    public function execute(&$value, &$error) {
  
        $className  = $this->getParameter('class').'Peer';
  
        //Get fields number
        $nb_fields = $this->getParameter('nb_fields');
  
        //Define new criteria      
        $c = new Criteria();
  
        //Loop on the fields
        for($i = 1; $i <= $nb_fields ; $i++) {
            //Retrieve field_$i
            $check_param = $this->getParameterHolder()->get("field_$i");
            $check_value = $this->getContext()->getRequest()->getParameter($check_param);
  
            //If check value defined        
            if ($check_value != '') {   
                //Adding field to the criteria
                $columnName = call_user_func(array($className, 'translateFieldName'), $check_param, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
                $c->add($columnName, $check_value);
            }
        }
  
        $object = call_user_func(array($className, 'doSelectOne'), $c);
  
        if ($object)
        {
          $tableMap = call_user_func(array($className, 'getTableMap'));
          foreach ($tableMap->getColumns() as $column)
          {
            if (!$column->isPrimaryKey())
            {
              continue;
            }
  
            $method = 'get'.$column->getPhpName();
            $primaryKey = call_user_func(array($className, 'translateFieldName'), $column->getPhpName(), BasePeer::TYPE_PHPNAME, BasePeer::TYPE_FIELDNAME);
            if ($object->$method() != $this->getContext()->getRequest()->getParameter($primaryKey))
            {
              $error = $this->getParameter('custom_unique_error');
  
              return false;
            }
          }
        }
  
        return true;
    }  
  
    public function initialize ($context, $parameters = null) {
        // initialize parent
        parent::initialize($context);
  
        //Set default parameters value
        $this->setParameter('custom_unique_error','The value is not unique');
  
        $this->getParameterHolder()->add($parameters);
  
        // check parameters
        if (!$this->getParameter('class'))
        {
          throw new sfValidatorException('The "class" parameter is mandatory for the sfCustomUniqueValidator validator.');
        }
  
        if (!$this->getParameter('nb_fields'))
        {
          throw new sfValidatorException('The "nb_fields" parameter is mandatory for the sfCustomUniqueValidator validator.');
        }
  
        return true;
    }
}
调用方法:
下面的代码检测companie表中是否已经有相同的记录
复制内容到剪贴板
代码:
sfCustomUniqueValidator:
class: Companies
nb_fields: 3
field_1: company_name
field_2: activity_id
field_3: country_id
custom_unique_error: This company already exist for this country

class: 用来测试的model
nb_fields: 有几个字段要检测
field_x: 要检测的字段
custom_unique_error: 错误信息
努力为phpres做贡献
时刻准备着,当机会来临时你就成功了
打好基础,增加社会经验
资深技术工程师是我的梦想
承接各种团体网站外包服务和各种it技术培训
准备申请AJAX版大,希望大家支持~~

TOP

发新话题