AliasedBehavior.php 1.2 KB

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