| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- <?php
- namespace yiins\components;
- use yiins\helpers\StringsHelper;
- /**
- * Class AliasedBehavior
- * @package base\components
- */
- class AliasedBehavior extends \CActiveRecordBehavior
- {
- public $captionField = 'caption';
- public $aliasField = 'alias';
- public $idField = 'id';
- public function beforeValidate($event)
- {
- if (!$this->owner->getAttribute($this->aliasField)) {
- $this->createAlias();
- }
- return parent::beforeValidate($event);
- }
- private function createAlias()
- {
- $nextId = $this->owner->getAttribute($this->idField);
- if (!$nextId) {
- $nextId = 1;
- $queryRes = $this->owner
- ->getDbConnection()
- ->createCommand()
- ->select("MAX({$this->idField}) AS {$this->idField}")
- ->from($this->owner->tableName())
- ->queryColumn();
- if (count($queryRes)) {
- $nextId = $queryRes[0];
- }
- }
- $this->owner->setAttribute($this->aliasField,
- StringsHelper::URLize($this->owner->getAttribute($this->captionField) . '-' . $nextId));
- }
- }
|