Serendesk Posted November 12, 2015 Report Posted November 12, 2015 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); } jobplease, Michael and serge 3 Quote
aneip Posted September 22, 2016 Report Posted September 22, 2016 Can details out on how to do this.. I want to check for unique username. I means, where do I put the code? What need to change if my service option field is username? Quote
Blesta Addons Posted September 22, 2016 Report Posted September 22, 2016 this is a shorten code for that purpose .using the built-in fucntion searchServiceFields() public function checkUniqueDomain($domain, $module_id) { Loader::loadModels($this, array("Services")); $services = $this->Services->searchServiceFields($module_id, "domain", $domain); if (empty($services)) return false; return $services[0]; } then call this function from the rules : $rules = array( 'domain' => array( 'unique' => array( 'final' => true, 'rule' => array(array($this, "checkUniqueDomain"), $module_id), 'negate' => true, 'message' => Language::_("ModuleName.!error.domain_valid.unique", true) ) ) ); Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.