Skip to content

Instantly share code, notes, and snippets.

@svandragt
Created November 15, 2016 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svandragt/e937ae033b78d35117f908abd6711273 to your computer and use it in GitHub Desktop.
Save svandragt/e937ae033b78d35117f908abd6711273 to your computer and use it in GitHub Desktop.
AjaxUniqueTextField Example
<?php
class MyDataObject extends DataObject
{
public function getCMSFields()
{
$fields = parent::getCMSFields();
// Place a unique value constraint MyDataObjects table, MyCode column
$myAjax = new MyAjaxUniqueTextField('MyCode', 'My Code', 'MyCode', 'MyDataObject', "", null, null, null, $this->ID);
$fields->replaceField('MyCode', $myAjax);
return $fields;
}
}
<?php
class MyAjaxUniqueTextField extends AjaxUniqueTextField
{
public function __construct($name, $title, $restrictedField, $restrictedTable, $value = "", $maxLength = null, $validationURL = null, $restrictedRegex = null, $recordID = null)
{
// assign record
$this->recordID = $recordID;
parent::__construct($name, $title, $restrictedField, $restrictedTable, $value, $maxLength,
$validationURL, $restrictedRegex);
}
public function validate($validator)
{
// validate against db records
$result = DB::query(sprintf(
"SELECT COUNT(*) FROM \"%s\" WHERE \"%s\" = '%s' AND \"ID\" != '
%s' ",
$this->restrictedTable,
$this->restrictedField,
Convert::raw2sql($this->value),
$this->recordID
))->value();
if ($result && ($result > 0)) {
$validator->validationError($this->name,
_t('Form.VALIDATIONNOTUNIQUE', "The value entered is not unique"));
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment