Skip to content

Instantly share code, notes, and snippets.

@romaninsh
Created October 26, 2016 13:33
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 romaninsh/5b6f9dc55e2210f726d26a01148232a5 to your computer and use it in GitHub Desktop.
Save romaninsh/5b6f9dc55e2210f726d26a01148232a5 to your computer and use it in GitHub Desktop.
Define Unique Fields in Domain Model with Agile Data
<?php
namespace smbo;
class Controller_UniqueFields {
use \atk4\core\InitializerTrait {
init as _init;
}
use \atk4\core\TrackableTrait;
use \atk4\core\AppScopeTrait;
protected $fields = null;
function init() {
$this->_init();
// by default make 'name' unique
if (!$this->fields) {
$this->fields = [$this->owner->title_field];
}
$this->owner->addHook('beforeSave', $this);
}
function beforeSave($m)
{
foreach ($this->fields as $field) {
if ($m->dirty[$field]) {
$mm = clone $m;
$mm->tryLoadBy($field, $m[$field]);
if ($mm->loaded()) {
throw new \atk4\core\Exception(['Duplicate record exists', 'field'=>$field, 'value'=>$m[$field]]);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment