Esempio n. 1
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param mixed $id the ID of the model to be loaded
  * @param string $modelClass the model class name
  * @return GxActiveRecord the loaded model
  */
 public function loadModel($id, $modelClass)
 {
     $model = GxActiveRecord::model($modelClass)->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
     }
     return $model;
 }
Esempio n. 2
0
 public function loadModel($key, $modelClass)
 {
     if (is_array($key)) {
         return parent::loadModel($key, $modelClass);
     }
     $staticModel = GxActiveRecord::model($modelClass);
     $model = $staticModel->findByPk($key);
     if (!$model) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
Esempio n. 3
0
 public static function model($className = __CLASS__)
 {
     return parent::model($className);
 }
Esempio n. 4
0
 public function loadModel($key, $modelClass)
 {
     // Get the static model.
     $staticModel = GxActiveRecord::model($modelClass);
     if (is_array($key)) {
         // The key is an array.
         // Check if there are column names indexing the values in the array.
         reset($key);
         if (key($key) === 0) {
             // There are no attribute names.
             // Check if there are multiple PK values. If there's only one, start again using only the value.
             if (count($key) === 1) {
                 return $this->loadModel($key[0], $modelClass);
             }
             // Now we will use the composite PK.
             // Check if the table has composite PK.
             $tablePk = $staticModel->getTableSchema()->primaryKey;
             if (!is_array($tablePk)) {
                 throw new CHttpException(400, Yii::t('giix', 'Your request is invalid.'));
             }
             // Check if there are the correct number of keys.
             if (count($key) !== count($tablePk)) {
                 throw new CHttpException(400, Yii::t('giix', 'Your request is invalid.'));
             }
             // Get an array of PK values indexed by the column names.
             $pk = $staticModel->fillPkColumnNames($key);
             // Then load the model.
             $model = $staticModel->findByPk($pk);
         } else {
             // There are attribute names.
             // Then we load the model now.
             $model = $staticModel->findByAttributes($key);
         }
     } else {
         // The key is not an array.
         // Check if the table has composite PK.
         $tablePk = $staticModel->getTableSchema()->primaryKey;
         if (is_array($tablePk)) {
             // The table has a composite PK.
             // The key must be a string to have a PK separator.
             if (!is_string($key)) {
                 throw new CHttpException(400, Yii::t('giix', 'Your request is invalid.'));
             }
             // There must be a PK separator in the key.
             if (stripos($key, GxActiveRecord::$pkSeparator) === false) {
                 throw new CHttpException(400, Yii::t('giix', 'Your request is invalid.'));
             }
             // Generate an array, splitting by the separator.
             $keyValues = explode(GxActiveRecord::$pkSeparator, $key);
             // Start again using the array.
             return $this->loadModel($keyValues, $modelClass);
         } else {
             // The table has a single PK.
             // Then we load the model now.
             $model = $staticModel->findByPk($key);
         }
     }
     // Check if we have a model.
     if ($model === null) {
         throw new CHttpException(404, Yii::t('giix', 'The requested page does not exist.'));
     }
     return $model;
 }
 protected function dataTables($aColumns, $modelClass, $customQuery = NULL)
 {
     $staticModel = GxActiveRecord::model($modelClass);
     $sIndexColumn = $staticModel->getTableSchema()->primaryKey;
     $namaTabel = $staticModel->tableName();
     /*
      * Paging
      */
     $sLimit = "";
     if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
         $sLimit = "LIMIT " . $_GET['iDisplayStart'] . ", " . $_GET['iDisplayLength'];
     }
     /*
      * Ordering
      */
     $sOrder = "";
     if (isset($_GET['iSortCol_0'])) {
         $sOrder = "ORDER BY  ";
         for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
             if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                 $sOrder .= "`" . $aColumns[intval($_GET['iSortCol_' . $i])] . "` " . $_GET['sSortDir_' . $i] . ", ";
             }
         }
         $sOrder = substr_replace($sOrder, "", -2);
         if ($sOrder == "ORDER BY") {
             $sOrder = "";
         }
     }
     /*
      * Filtering
      * NOTE this does not match the built-in DataTables filtering which does it
      * word by word on any field. It's possible to do here, but concerned about efficiency
      * on very large tables, and MySQL's regex functionality is very limited
      */
     $sWhere = "";
     if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
         $sWhere = "WHERE (";
         for ($i = 0; $i < count($aColumns); $i++) {
             $sWhere .= "`" . $aColumns[$i] . "` LIKE '%" . $_GET['sSearch'] . "%' OR ";
         }
         $sWhere = substr_replace($sWhere, "", -3);
         $sWhere .= ')';
     }
     /* Individual column filtering */
     for ($i = 0; $i < count($aColumns); $i++) {
         if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
             if ($sWhere == "") {
                 $sWhere = "WHERE ";
             } else {
                 $sWhere .= " AND ";
             }
             $sWhere .= "`" . $aColumns[$i] . "` LIKE '%" . $_GET['sSearch_' . $i] . "%' ";
         }
     }
     if ($customQuery != NULL) {
         if (strlen(trim($sWhere)) == 0) {
             $sWhere = "WHERE " . $customQuery;
         } else {
             $sWhere .= " AND " . $customQuery;
         }
     }
     /*
      * SQL queries
      * Get data to display
      */
     $sQuery = "\n\t\t   SELECT `" . str_replace(" , ", " ", implode("`, `", $aColumns)) . "`\n\t\t   FROM   {$namaTabel}\n\t\t   {$sWhere}\n\t\t   {$sOrder}\n\t\t   {$sLimit}\n\t\t   ";
     //echo $sQuery;
     $rResult = Yii::app()->db->createCommand($sQuery)->queryAll();
     /* Data set length after filtering */
     $sQuery = "SELECT COUNT(*) AS FR\n\t\t   FROM   {$namaTabel}\n\t\t   {$sWhere}\n\t\t   {$sOrder}";
     $rResultFilterTotal = Yii::app()->db->createCommand($sQuery)->queryAll();
     foreach ($rResultFilterTotal as $v) {
         $aResultFilterTotal = $v;
     }
     $iFilteredTotal = $aResultFilterTotal["FR"];
     /* Total data set length */
     $sQuery = "\n\t\t   SELECT COUNT(`" . $sIndexColumn . "`) as total\n\t\t   FROM   {$namaTabel}";
     if ($customQuery != NULL) {
         $sQuery .= " WHERE " . $customQuery;
     }
     $rResultTotal = Yii::app()->db->createCommand($sQuery)->queryAll();
     $i = 0;
     $iTotal = 0;
     foreach ($rResultTotal as $v) {
         $iTotal = $v["total"];
     }
     return array("result" => $rResult, "total" => $iTotal, "filtertotal" => $iFilteredTotal);
 }
Esempio n. 6
0
<?php 
echo '<?php';
?>
 $this->widget('bootstrap.widgets.TbDetailView', array(
	'data' => $model,
	'attributes' => array(
<?php 
foreach ($this->tableSchema->columns as $column) {
    echo $this->generateDetailViewAttribute($this->modelClass, $column) . ",\n";
}
?>
	),
)); ?>

<?php 
foreach (GxActiveRecord::model($this->modelClass)->relations() as $relationName => $relation) {
    if ($relation[0] == GxActiveRecord::HAS_MANY || $relation[0] == GxActiveRecord::MANY_MANY) {
        ?>
<h2><?php 
        echo '<?php';
        ?>
 echo GxHtml::encode($model->getRelationLabel('<?php 
        echo $relationName;
        ?>
')); ?></h2>
<?php 
        echo "<?php\n";
        ?>
	echo GxHtml::openTag('ul');
	foreach($model-><?php 
        echo $relationName;
Esempio n. 7
0
	/**
	 * Returns all the relations of the specified model.
	 * @param string $modelClass The model class name.
	 * @return array The relations. Each array item is
	 * a relation as an array, having 3 items:
	 * 0: the relation name,
	 * 1: the relation type,
	 * 2: the foreign key,
	 * 3: the related active record class name.
	 * Or an empty array if no relations were found.
	 */
	public function getRelations($modelClass) {
		$relations = GxActiveRecord::model($modelClass)->relations();
		$result = array();
		foreach ($relations as $relationName => $relation) {
			$result[] = array(
				$relationName, // the relation name
				$relation[0], // the relation type
				$relation[2], // the foreign key
				$relation[1] // the related active record class name
			);
		}
		return $result;
	}
Esempio n. 8
0
 /**
  * Saves the MANY_MANY relations of this record.
  * Internally used by {@link saveWithRelated} and {@link saveMultiple}.
  * See {@link saveWithRelated} and {@link saveMultiple} for details.
  * @param array $relatedData The relation data in the format returned by {@link GxController::getRelatedData}.
  * @param boolean $runValidation Whether to perform validation before saving the record.
  * @param boolean $batch Whether to try to do the deletes and inserts in batch.
  * While batches may be faster, using active record instances provides better control, validation, event support etc.
  * Batch is only supported for deletes.
  * @return boolean Whether the saving succeeds.
  * @see saveWithRelated
  * @see saveMultiple
  * @throws CException If this record is new.
  * @throws CException If this active record has composite PK.
  * @uses pivotModels
  */
 protected function saveRelated($relatedData, $runValidation = true, $batch = true)
 {
     if (empty($relatedData)) {
         return true;
     }
     // This active record can't be new for the method to work correctly.
     if ($this->getIsNewRecord()) {
         throw new CException(Yii::t('giix.messages', 'Cannot save the related records to the database because the main record is new.'));
     }
     // Save each related data.
     foreach ($relatedData as $relationName => $relationData) {
         // The pivot model class name.
         $pivotClassNames = $this->pivotModels();
         $pivotClassName = $pivotClassNames[$relationName];
         $pivotModelStatic = GxActiveRecord::model($pivotClassName);
         // Get the foreign key names for the models.
         $activeRelation = $this->getActiveRelation($relationName);
         $relatedClassName = $activeRelation->className;
         if (preg_match('/(.+)\\((.+),\\s*(.+)\\)/', $activeRelation->foreignKey, $matches)) {
             // By convention, the first fk is for this model, the second is for the related model.
             $thisFkName = $matches[2];
             $relatedFkName = $matches[3];
         }
         // Get the primary key value of the main model.
         $thisPkValue = $this->getPrimaryKey();
         if (is_array($thisPkValue)) {
             throw new CException(Yii::t('giix.messages', 'Composite primary keys are not supported.'));
         }
         // Get the current related models of this relation and map the current related primary keys.
         $currentRelation = $pivotModelStatic->findAll(new CDbCriteria(array('select' => $relatedFkName, 'condition' => "{$thisFkName} = :thisfkvalue", 'params' => array(':thisfkvalue' => $thisPkValue))));
         $currentMap = array();
         foreach ($currentRelation as $currentRelModel) {
             $currentMap[] = $currentRelModel->{$relatedFkName};
         }
         // Compare the current map to the new data and identify what is to be kept, deleted or inserted.
         $newMap = $relationData;
         $deleteMap = array();
         $insertMap = array();
         if ($newMap !== null) {
             // Identify the relations to be deleted.
             foreach ($currentMap as $currentItem) {
                 if (!in_array($currentItem, $newMap)) {
                     $deleteMap[] = $currentItem;
                 }
             }
             // Identify the relations to be inserted.
             foreach ($newMap as $newItem) {
                 if (!in_array($newItem, $currentMap)) {
                     $insertMap[] = $newItem;
                 }
             }
         } else {
             // If the new data is empty, everything must be deleted.
             $deleteMap = $currentMap;
         }
         // If nothing changed, we simply continue the loop.
         if (empty($deleteMap) && empty($insertMap)) {
             continue;
         }
         // Now act inserting and deleting the related data: first prepare the data.
         // Inject the foreign key names of both models and the primary key value of the main model in the maps.
         foreach ($deleteMap as &$deleteMapPkValue) {
             $deleteMapPkValue = array_merge(array($relatedFkName => $deleteMapPkValue), array($thisFkName => $thisPkValue));
         }
         unset($deleteMapPkValue);
         // Clear reference;
         foreach ($insertMap as &$insertMapPkValue) {
             $insertMapPkValue = array_merge(array($relatedFkName => $insertMapPkValue), array($thisFkName => $thisPkValue));
         }
         unset($insertMapPkValue);
         // Clear reference;
         // Now act inserting and deleting the related data: then execute the changes.
         // Delete the data.
         if (!empty($deleteMap)) {
             if ($batch) {
                 // Delete in batch mode.
                 if ($pivotModelStatic->deleteByPk($deleteMap) !== count($deleteMap)) {
                     return false;
                 }
             } else {
                 // Delete one active record at a time.
                 foreach ($deleteMap as $value) {
                     $pivotModel = GxActiveRecord::model($pivotClassName)->findByPk($value);
                     if (!$pivotModel->delete()) {
                         return false;
                     }
                 }
             }
         }
         // Insert the new data.
         foreach ($insertMap as $value) {
             $pivotModel = new $pivotClassName();
             $pivotModel->setAttributes($value);
             if (!$pivotModel->save($runValidation)) {
                 return false;
             }
         }
     }
     // This is the end of the loop "save each related data".
     return true;
 }
 /**
  * Returns all the relations of the specified model.
  * @param string $modelClass The model class name.
  * @return array The relations. Each array item is
  * a relation as an array, having 3 items:
  * 0: the relation name,
  * 1: the relation type,
  * 2: the foreign key,
  * 3: the related active record class name.
  * Or an empty array if no relations were found.
  */
 public function getRelations($modelClass)
 {
     $relations = GxActiveRecord::model($modelClass)->relations();
     $result = array();
     foreach ($relations as $relationName => $relation) {
         $result[] = array($relationName, $relation[0], $relation[2], $relation[1]);
     }
     return $result;
 }
Esempio n. 10
0
 /**
  * Saves the current record and its relations.
  * @param array $relatedData The relation data in the format returned by {@link GxController::getRelatedData}.
  * @param boolean $runValidation Whether to perform validation before saving the record.
  * If the validation fails, the record will not be saved to database. This applies to all (including related) models.
  * This does not apply when in batch mode. This does not apply for deletes. If you want to validate deletes, disable
  * batch mode and use the {@link CActiveRecord::onBeforeDelete} event.
  * @param array $attributes List of attributes that need to be saved. Defaults to null,
  * meaning all attributes that are loaded from DB will be saved. This applies only to the main model.
  * @param array $options Additional options. Valid options are:
  * <ul>
  * <li>'withTransaction', boolean: Whether to use a transaction.
  * Note: if there are no changes in the relations, no transaction will be used.</li>
  * <li>'batch', boolean: Whether to try to do the deletes and inserts in batch.
  * While batches may be faster, using active record instances provides better control, validation, event support etc.
  * Batch is only supported for deletes.</li>
  * </ul>
  * @return boolean Whether the saving succeeds.
  */
 public function saveWithRelated($relatedData, $runValidation = true, $attributes = null, $options = array())
 {
     // The default options.
     $defaultOptions = array('withTransaction' => true, 'batch' => true);
     // Merge the specified options with the default options.
     $options = array_merge($defaultOptions, $options);
     // Pass the options to variables.
     $withTransaction = $options['withTransaction'];
     $batch = $options['batch'];
     if (empty($relatedData)) {
         // There is no related data. We simply save the main model.
         return parent::save($runValidation, $attributes);
     } else {
         // Save each related data.
         foreach ($relatedData as $relationName => $relationData) {
             // Get the current related models of this relation and map the current related primary keys.
             $currentRelation = $this->{$relationName};
             $currentMap = array();
             foreach ($currentRelation as $currentRelModel) {
                 $currentMap[] = $currentRelModel->primaryKey;
             }
             // Compare the current map to the new data and identify what is to be kept, deleted or inserted.
             $newMap = $relationData;
             $deleteMap = array();
             $insertMap = array();
             if (!is_null($newMap)) {
                 // Identify the relations to be deleted.
                 foreach ($currentMap as $currentItem) {
                     if (!in_array($currentItem, $newMap)) {
                         $deleteMap[] = $currentItem;
                     }
                 }
                 // Identify the relations to be inserted.
                 foreach ($newMap as $newItem) {
                     if (!in_array($newItem, $currentMap)) {
                         $insertMap[] = $newItem;
                     }
                 }
             } else {
                 // If the new data is empty, everything must be deleted.
                 $deleteMap = $currentMap;
             }
             // If nothing changed, we simply save the main model.
             if (empty($deleteMap) && empty($insertMap)) {
                 return parent::save($runValidation, $attributes);
             }
             // Now act inserting and deleting the related data: first prepare the data.
             // Get the foreign key names for the models.
             $activeRelation = $this->getActiveRelation($relationName);
             $relatedClassName = $activeRelation->className;
             if (preg_match('/(.+)\\((.+),\\s*(.+)\\)/', $activeRelation->foreignKey, $matches)) {
                 // By convention, the first fk is for this model, the second is for the related model.
                 //$pivotTableName = $matches[1];
                 $thisFkName = $matches[2];
                 $relatedFkName = $matches[3];
             }
             // The pivot model class name.
             $pivotClassNames = $this->pivotModels();
             $pivotClassName = $pivotClassNames[$relationName];
             $pivotModelStatic = GxActiveRecord::model($pivotClassName);
             // Get the primary key value of the main model.
             $thisPkValue = $this->primaryKey;
             if (is_array($thisPkValue)) {
                 throw new Exception(Yii::t('giix', 'Composite primary keys are not supported.'), 500);
             }
             // Inject the foreign key names of both models and the primary key value of the main model in the maps.
             foreach ($deleteMap as &$pkValue) {
                 $pkValue = array_merge(array($relatedFkName => $pkValue), array($thisFkName => $thisPkValue));
             }
             unset($pkValue);
             // Clear reference;
             foreach ($insertMap as &$pkValue) {
                 $pkValue = array_merge(array($relatedFkName => $pkValue), array($thisFkName => $thisPkValue));
             }
             unset($pkValue);
             // Clear reference;
             // Start the transaction if required.
             if ($withTransaction && is_null($this->dbConnection->currentTransaction)) {
                 $transacted = true;
                 $transaction = $this->dbConnection->beginTransaction();
             } else {
                 $transacted = false;
             }
             try {
                 // Save the main model.
                 if (!parent::save($runValidation, $attributes)) {
                     if ($transacted) {
                         $transaction->rollback();
                     }
                     return false;
                 }
                 // Now act inserting and deleting the related data: then execute the changes.
                 // Delete the data.
                 if (!empty($deleteMap)) {
                     if ($batch) {
                         // Delete in batch mode.
                         if ($pivotModelStatic->deleteByPk($deleteMap) !== count($deleteMap)) {
                             if ($transacted) {
                                 $transaction->rollback();
                             }
                             return false;
                         }
                     } else {
                         // Delete one active record at a time.
                         foreach ($deleteMap as $value) {
                             $pivotModel = GxActiveRecord::model($pivotClassName)->findByPk($value);
                             if (!$pivotModel->delete()) {
                                 if ($transacted) {
                                     $transaction->rollback();
                                 }
                                 return false;
                             }
                         }
                     }
                 }
                 // Insert the new data.
                 foreach ($insertMap as $value) {
                     $pivotModel = new $pivotClassName();
                     $pivotModel->attributes = $value;
                     if (!$pivotModel->save($runValidation)) {
                         if ($transacted) {
                             $transaction->rollback();
                         }
                         return false;
                     }
                 }
                 // If transacted, commit the transaction.
                 if ($transacted) {
                     $transaction->commit();
                 }
             } catch (Exception $ex) {
                 // If there is an exception, roll back the transaction, if transacted. If not transacted, rethrow the exception.
                 if ($transacted) {
                     $transaction->rollback();
                     return false;
                 } else {
                     throw $ex;
                 }
             }
         }
         return true;
     }
 }
Esempio n. 11
0
          <div id="gridview-wrapper" class="left">
<?php 
echo '<?php';
?>
 $this->widget('zii.widgets.grid.CGridView', array(
	'id' => '<?php 
echo $this->class2var($relatedModelClass);
?>
-grid',
	'dataProvider' => $prod_dataProvider,
	'filter' => $model,
	'columns' => array(
<?php 
$count = 0;
foreach (GxActiveRecord::model($relatedModelClass)->tableSchema->columns as $column) {
    if (++$count == 7) {
        echo "\t\t/*\n";
    }
    echo "\t\t" . $this->generateGridViewColumn($this->modelClass, $column) . ",\n";
}
if ($count >= 7) {
    echo "\t\t*/\n";
}
?>
                                                                  array(
                                                                           'class' => 'CDataColumn',
                                                                           'type' => 'image',
                                                                           'value' => '($data-><?php 
echo $this->class2var($relatedModelClass);
?>