Created
October 26, 2016 13:33
-
-
Save romaninsh/5b6f9dc55e2210f726d26a01148232a5 to your computer and use it in GitHub Desktop.
Define Unique Fields in Domain Model with Agile Data
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
<?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