AliasedBehavior.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace yiins\components;
  3. use yiins\helpers\StringsHelper;
  4. /**
  5. * Class AliasedBehavior
  6. * @package base\components
  7. */
  8. class AliasedBehavior extends \CActiveRecordBehavior
  9. {
  10. public $captionField = 'caption';
  11. public $aliasField = 'alias';
  12. public $idField = 'id';
  13. public function beforeValidate($event)
  14. {
  15. if (!$this->owner->getAttribute($this->aliasField)) {
  16. $this->createAlias();
  17. }
  18. return parent::beforeValidate($event);
  19. }
  20. private function createAlias()
  21. {
  22. $nextId = $this->owner->getAttribute($this->idField);
  23. if (!$nextId) {
  24. $nextId = 1;
  25. $queryRes = $this->owner
  26. ->getDbConnection()
  27. ->createCommand()
  28. ->select("MAX({$this->idField}) AS {$this->idField}")
  29. ->from($this->owner->tableName())
  30. ->queryColumn();
  31. if (count($queryRes)) {
  32. $nextId = $queryRes[0];
  33. }
  34. }
  35. $this->owner->setAttribute($this->aliasField,
  36. StringsHelper::URLize($this->owner->getAttribute($this->captionField) . '-' . $nextId));
  37. }
  38. }