Hi all,
Just sharing an approach that can be used in a custom module to check whether a service field value is unique or already in use (e.g. to enforce unique domain names).
public function validateService($package, array $vars=null, $edit=false) {
if ($package)
$module_row_id = $package->module_row;
else
$module_row_id = isset($vars['module_row']) ? $vars['module_row'] : null;
$row = $this->getModuleRow($module_row_id);
//get the service id using a known and guaranteed unique field. this is needed to perform a unique validation of service fields without having the same service that may already have the field to cause validation to fail (e.g. when activating a pending service).
$service_id = $this->getServiceIDUsingUniqueServiceField('myUniqueServiceUID', $params['myUniqueServiceUID']);
$rules = array(
'domain' => array(
'unique' => array(
'final' => true,
'rule' => array(array($this, "checkUniqueDomain"), $service_id),
'negate' => true,
'message' => Language::_("ModuleName.!error.domain_valid.unique", true)
)
)
);
$this->Input->setRules($rules);
return $this->Input->validates($params);
}
// check any service field value exists
private function checkServiceFieldValueExists($key, $value, $service_id = null) {
Loader::loadComponents($this, array("Record"));
$exists = false;
if (is_null($service_id)) {
$service_id = -1;
}
$this->Record->select()
->from("service_fields")
->where("service_fields.key", "=", $key)
->where("service_fields.value", "=", $value)
->where("service_fields.service_id", "!=", $service_id);
if($this->Record->numResults() > 0) {
$exists = true;
}
$this->Record->reset();
return $exists;
}
// check domain is unique
public function checkUniqueDomain($value, $service_id = null) {
return $this->checkServiceFieldValueExists('domain', $value, $service_id);
}