Last active
April 9, 2018 13:00
-
-
Save andrewandante/04337042642d99adb6496b967ca17801 to your computer and use it in GitHub Desktop.
Validate a unique DB Field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function validate() | |
{ | |
$result = parent::validate(); | |
$this->ensureUnique('Title', $result); | |
return $result; | |
} | |
/** | |
* @param string $fieldName | |
* @param \ValidationResult $validationResult | |
* | |
* @return \ValidationResult | |
*/ | |
protected function ensureUnique($fieldName, &$validationResult) | |
{ | |
if ($this->isChanged($fieldName)) { | |
$exists = myClass::get()->filter($fieldName, $this->getField($fieldName))->first(); | |
if ($exists) { | |
$validationResult->error($fieldName.' must be unique among '. myClass::class); | |
} | |
} | |
return $validationResult; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment