-
Notifications
You must be signed in to change notification settings - Fork 1
/
SortableBehavior.php
63 lines (53 loc) · 1.83 KB
/
SortableBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
class SortableBehavior extends CActiveRecordBehavior
{
public function swapPosition($fromId, $toId)
{
$owner = $this->getOwner();
$from = $owner->model()->findByPk($fromId);
$to = $owner->model()->findByPk($toId);
$to->scenario = $from->scenario = 'movePosition';
//swap
list($from->priority, $to->priority) = array($to->priority, $from->priority);
$transaction=Yii::app()->db->beginTransaction();
try {
if ($from->save() && $to->save())
$transaction->commit();
else
throw new CException('movePosition error');
} catch(Exception $e) {
$transaction->rollBack();
}
}
public function setPositions($ids, $table, $criteria=null)
{
$criteria = $criteria ? $criteria : new CDbCriteria();
$owner = $this->getOwner();
$pk = $owner->primaryKey();
//last id have 0 priority => revers => first id have 0 priority => flip => every id have their priority
$priorities = array_flip(array_reverse($ids));
$data = array('priority' => Sql::arrToCase($pk, $priorities));
$c = Yii::app()->db->commandBuilder
->createUpdateCommand($table, $data, $criteria);
Y::dump($c->execute());
}
/**
* @return CActiveRecord Season
*/
public function mostPriority()
{
$owner = $this->getOwner();
$alias = $owner->getTableAlias();
$owner->getDbCriteria()->mergeWith(array(
'limit' => 1,
'order' => $alias.'.priority DESC'
));
return $owner;
}
public function setDefaultPriority()
{
$owner = $this->getOwner();
$model = $owner->model()->mostPriority()->find();
$owner->priority = $model->priority + 1;
}
}