HCE Project DC service web UI  0.2
Hierarchical Cluster Engine DC service web UI
 All Classes Namespaces Files Functions Variables Pages
TbSortableAction.php
Go to the documentation of this file.
1 <?php
16 class TbSortableAction extends CAction
17 {
21  public $modelName;
22 
27  public function run()
28  {
29  if (!$this->isValidRequest())
30  throw new CHttpException(400, Yii::t('yii', 'Your request is invalid.'));
31 
32  $sortableAttribute = Yii::app()->request->getQuery('sortableAttribute');
33 
35  $model = new $this->modelName;
36  if (!$model->hasAttribute($sortableAttribute)) {
37  throw new CHttpException(400, Yii::t(
38  'yii',
39  '{attribute} "{value}" is invalid.',
40  array('{attribute}' => 'sortableAttribute', '{value}' => $sortableAttribute)
41  ));
42  }
43 
44  $sortOrderData = $_POST['sortOrder'];
45 
46  $this->update($model, $sortableAttribute, $sortOrderData);
47  }
48 
49  private function isValidRequest()
50  {
51  return Yii::app()->request->isPostRequest
52  && Yii::app()->request->isAjaxRequest
53  && isset($_POST['sortOrder']);
54  }
55 
63  private function update($model, $sortableAttribute, $sortOrderData)
64  {
65  $pk = $model->tableSchema->primaryKey;
66  $pk_array = array();
67  if(is_array($pk)) { // composite key
68  $string_ids = array_keys($sortOrderData);
69 
70  $array_ids = array();
71  foreach ($string_ids as $string_id)
72  $array_ids[] = explode(',', $string_id);
73 
74  foreach ($array_ids as $array_id)
75  $pk_array[] = array_combine($pk, $array_id);
76  } else { // normal key
77  $pk_array = array_keys($sortOrderData);
78  }
79 
80  $models = $model->model()->findAllByPk($pk_array);
81  $transaction = Yii::app()->db->beginTransaction();
82  try {
83  foreach ($models as $model) {
84  $_key = is_array($pk) ? implode(',', array_values($model->primaryKey)) : $model->primaryKey;
85  $model->{$sortableAttribute} = $sortOrderData[$_key];
86  $model->save();
87  }
88  $transaction->commit();
89  }
90  catch(Exception $e) { // an exception is raised if a query fails
91  $transaction->rollback();
92  }
93  }
94 }