Browse files

Merge branch 'master' of https://github.com/thyseus/gii-template-coll…

…ection into merge-with-thyseus

Reworked fallback method (merge with master)
Conflicts:
	fullCrud/templates/default/controller.php
  • Loading branch information...
2 parents e9ea32c + 9bb5675 commit d9597505e0449330dedfbc62e937aa9a949dd38c @schmunk42 committed Oct 6, 2011
View
25 components/GActiveRecord.php
@@ -1,25 +0,0 @@
-<?php
-
-abstract class GActiveRecord extends CActiveRecord {
- public function behaviors()
- {
- return array_merge(parent::behaviors(), array(
- 'CSaveRelationsBehavior' => array(
- 'class' => 'ext.gtc.components.CSaveRelationsBehavior'
- ),
- 'TimestampBehavior' => array(
- 'class' => 'ext.gtc.components.TimestampBehavior'
- )
- )
- );
- }
-
- public function __toString() {
- return $this->id;
- }
-
- public function getRecordTitle(){
- $nameColumn = GHelper::guessNameColumn($this->tableSchema->columns);
- return $this->$nameColumn;
- }
-}
View
40 components/identificationColumnValidator.php
@@ -0,0 +1,40 @@
+<?php
+/**
+ * IdentificationColumnValidator class file.
+ *
+ * @author Herbert Maschke <thyseus@gmail.com>
+ * This file is part of the gii-template-collection
+ */
+
+/**
+ * IdentificationColumnValidator is automatically applied by FullModel
+ * to any column that 'identifies' the Model in a human-readable way. There
+ * are certain rules that need to be applied, since the column can appear
+ * in the URL. There should not be a / inside it and there should not be a .
+ * (dot) as last character.
+ *
+ * Child classes must implement the {@link validateAttribute} method.
+ *
+ */
+class IdentificationColumnValidator extends CValidator
+{
+ protected function validateAttribute($object,$attribute) {
+ if(isset($object->$attribute)) {
+ if($object->$attribute) {
+ if(substr($object->$attribute, 0, -1) == '.')
+ $object->addError($attribute, Yii::t('app',
+ 'Please do not use a . (dot) as the last character for this column'));
+
+ if(strpos($object->$attribute, '/') !== false)
+ $object->addError($attribute, Yii::t('app',
+ 'Please do not use a / (slash) for this column'));
+ }
+ }
+ }
+
+ public function clientValidateAttribute($object,$attribute)
+ {
+ }
+
+}
+
View
3 fullCrud/FullCrudCode.php
@@ -34,7 +34,8 @@ public function validateModel($attribute,$params)
{
// check your import paths, if you get an error here
// PHP error can't be catched as an exception
- $class=Yii::import($this->model, true);
+ if($this->model)
+ Yii::import($this->model, true);
parent::validateModel($attribute,$params);
}
View
6 fullCrud/templates/default/controller.php
@@ -82,7 +82,7 @@ public function actionCreate()
$this->redirect(array('view','id'=>$model->id));
}
} catch (Exception $e) {
- throw new CHttpException(500,$e->getMessage());
+ $model->addError('<?php echo $this->identificationColumn;?>', $e->getMessage());
}
} elseif(isset($_GET['<?php echo $this->modelClass; ?>'])) {
$model->attributes = $_GET['<?php echo $this->modelClass; ?>'];
@@ -122,7 +122,7 @@ public function actionUpdate($id)
$this->redirect(array('view','id'=>$model->id));
}
} catch (Exception $e) {
- throw new CHttpException(500,$e->getMessage());
+ $model->addError('<?php echo $this->identificationColumn;?>', $e->getMessage());
}
}
@@ -176,7 +176,7 @@ public function loadModel($id)
{
$model=<?php echo $this->modelClass; ?>::model()->findByPk($id);
if($model===null)
- throw new CHttpException(404,Yii::t('app','The requested page does not exist.'));
+ throw new CHttpException(404,Yii::t('app', 'The requested page does not exist.'));
return $model;
}
View
5 fullCrud/views/crud.php
@@ -54,8 +54,9 @@
instead of <code>index.php?r=post/view&id=5</code>.
Ready to use url rules for Yii's CUrlManager will be generated and shown
after the generation.
- Please make sure that the column is marked as <em> Unique </em> in the
- model Rules section when using this function.
+ Please make sure that identificationColumnValidator is applied to the
+ column. If the model has been generated by FullModel, this is already done
+ automatically.
</div>
<?php echo $form->error($model,'identificationColumn'); ?>
</div>
View
2 fullCrud/views/index.php
@@ -41,7 +41,7 @@
'model' => $model,
'form' => $form));
-if(isset($_POST['preview']))
+if(isset($_POST['preview']) && !$model->hasErrors())
$this->renderPartial('url_hint', array(
'model' => $model,
'form' => $form));
View
118 fullModel/FullModelCode.php
@@ -3,20 +3,26 @@
Yii::import('ext.gtc.components.*');
class FullModelCode extends ModelCode {
- public $baseClass = 'GActiveRecord';
+ public $tables;
+ public $baseClass = 'CActiveRecord';
+ public $identificationColumn = null;
public function init() {
parent::init();
if (!@class_exists("CSaveRelationsBehavior")) {
throw new CException("Fatal Error: Class 'CSaveRelationsBehavior' could not be found in your application! Add 'ext.gtc.components.*' to your import paths.");
}
- if (!@class_exists("GActiveRecord")) {
- throw new CException("Fatal Error: Class 'GActiveRecord' could not be found in your application! Add 'ext.gtc.components.*' to your import paths.");
- }
}
+ public function rules()
+ {
+ return array_merge(parent::rules(), array(
+ array('identificationColumn', 'safe'),
+ ));
+ }
+
public function prepare() {
parent::prepare();
@@ -30,22 +36,32 @@ public function prepare() {
$tableName = $this->tableName;
}
if ($tableName[strlen($tableName) - 1] === '*') {
- $tables = Yii::app()->db->schema->getTables($schema);
+ $this->tables = Yii::app()->db->schema->getTables($schema);
if ($this->tablePrefix != '') {
- foreach ($tables as $i => $table) {
+ foreach ($this->tables as $i => $table) {
if (strpos($table->name, $this->tablePrefix) !== 0)
- unset($tables[$i]);
+ unset($this->tables[$i]);
}
}
}
else
- $tables=array($this->getTableSchema($this->tableName));
+ $this->tables=array($this->getTableSchema($this->tableName));
$this->relations = $this->generateRelations();
- foreach ($tables as $table) {
+ foreach ($this->tables as $table) {
$tableName = $this->removePrefix($table->name);
$className = $this->generateClassName($table->name);
+
+ if(!$this->identificationColumn)
+ $this->identificationColumn = $this->guessIdentificationColumn(
+ $table->columns);
+
+ if(!array_key_exists(
+ $this->identificationColumn, $table->columns))
+ $this->addError('identificationColumn', 'The specified column can not be found in the models attributes. <br /> Please specify a valid attribute. If unsure, leave the field empty.');
+
+
$params = array(
'tableName' => $schema === '' ? $tableName : $schema . '.' . $tableName,
'modelClass' => $className,
@@ -55,11 +71,11 @@ public function prepare() {
'relations' => isset($this->relations[$className]) ? $this->relations[$className] : array(),
);
- if($this->template != 'singlefile')
- $this->files[] = new CCodeFile(
- Yii::getPathOfAlias($this->modelPath) . '/' . 'Base' . $className . '.php',
- $this->render($templatePath . '/basemodel.php', $params)
- );
+ if($this->template != 'singlefile')
+ $this->files[] = new CCodeFile(
+ Yii::getPathOfAlias($this->modelPath) . '/' . 'Base' . $className . '.php',
+ $this->render($templatePath . '/basemodel.php', $params)
+ );
}
}
@@ -73,6 +89,54 @@ public function requiredTemplates() {
);
}
+ public function getBehaviors($columns) {
+ $behaviors = 'return array(';
+ if(count($this->relations) > 0)
+ $behaviors .= "'CSaveRelationsBehavior', array(
+ 'class' => 'CSaveRelationsBehavior'),";
+
+ foreach($columns as $name => $column) {
+ if(in_array($column->name, array(
+ 'create_time',
+ 'createtime',
+ 'created_at',
+ 'createdat',
+ 'changed',
+ 'changed_at',
+ 'updatetime',
+ 'update_time',
+ 'timestamp'))) {
+ $behaviors .= sprintf("\n\t\t'CTimestampBehavior' => array(
+ 'class' => 'zii.behaviors.CTimestampBehavior',
+ 'createAttribute' => %s,
+ 'updateAttribute' => %s,
+ \t),\n", $this->getCreatetimeAttribute($columns),
+ $this->getUpdatetimeAttribute($columns));
+ break; // once a column is found, we are done
+ }
+ }
+ foreach($columns as $name => $column) {
+ if(in_array($column->name, array(
+ 'user_id',
+ 'userid',
+ 'ownerid',
+ 'owner_id',
+ 'created_by',
+ 'createdby'))) {
+ $behaviors .= sprintf("\n\t\t'OwnerBehavior' => array(
+ 'class' => 'OwnerBehavior',
+ 'ownerColumn' => '%s',
+ \t),\n", $column->name);
+ break; // once a column is found, we are done
+
+ }
+ }
+
+
+ $behaviors .= "\n);\n";
+ return $behaviors;
+ }
+
public function generateRules($table)
{
$rules=array();
@@ -95,10 +159,16 @@ public function generateRules($table)
$integers[]=$column->name;
else if($column->type==='double')
$numerical[]=$column->name;
- else if($column->type==='string' && $column->size>0)
+ else if($column->type==='string' && $column->size>0) {
$length[$column->size][]=$column->name;
+ if($column->name == $this->identificationColumn ) {
+ $rules[] = "array('{$column->name}', 'unique')";
+ $rules[] = "array('{$column->name}', 'identificationColumnValidator')";
+ }
+ }
else if(!$column->isPrimaryKey && !$r)
$safe[]=$column->name;
+
}
if($required!==array())
$rules[]="array('".implode(', ',$required)."', 'required')";
@@ -116,6 +186,7 @@ public function generateRules($table)
if($safe!==array())
$rules[]="array('".implode(', ',$safe)."', 'safe')";
+
return $rules;
}
@@ -137,6 +208,23 @@ function getUpdatetimeAttribute($columns) {
return 'null';
}
+ public function guessIdentificationColumn($columns) {
+ $found = false;
+ foreach($columns as $name => $column) {
+ if(!$found
+ && $column->type != 'datetime'
+ && $column->type==='string'
+ && !$column->isPrimaryKey) {
+ return $column->name;
+ $found = true;
+ }
+ }
+
+ // if the columns contains no column of type 'string', return the
+ // first column (usually the primary key)
+ if(!$found)
+ return reset($columns)->name;
+ }
}
View
66 fullModel/templates/singlefile/model.php
@@ -125,51 +125,8 @@ public function search()
public function behaviors()
{
- <?php
- $behaviors = 'return array(';
- foreach($columns as $name => $column) {
- if(in_array($column->name, array(
- 'create_time',
- 'createtime',
- 'created_at',
- 'createdat',
- 'changed',
- 'changed_at',
- 'updatetime',
- 'update_time',
- 'timestamp'))) {
- $behaviors .= sprintf("\n\t\t'CTimestampBehavior' => array(
- 'class' => 'zii.behaviors.CTimestampBehavior',
- 'createAttribute' => %s,
- 'updateAttribute' => %s,
- \t),\n", $this->getCreatetimeAttribute($columns),
- $this->getUpdatetimeAttribute($columns));
- break; // once a column is found, we are done
- }
- }
- foreach($columns as $name => $column) {
- if(in_array($column->name, array(
- 'user_id',
- 'userid',
- 'ownerid',
- 'owner_id',
- 'created_by',
- 'createdby'))) {
- $behaviors .= sprintf("\n\t\t'OwnerBehavior' => array(
- 'class' => 'OwnerBehavior',
- 'ownerColumn' => '%s',
- \t),\n", $column->name);
- break; // once a column is found, we are done
-
- }
- }
-
-
- $behaviors .= "\n);\n";
- echo $behaviors;
- ?>
- }
-
+ <?php echo $this->getBehaviors($columns); ?>
+ }
public function beforeValidate()
{
@@ -192,26 +149,9 @@ public function afterSave()
}
public function __toString() {
- return (string) $this-><?php
- $found = false;
- foreach($columns as $name => $column) {
- if(!$found
- && $column->type != 'datetime'
- && $column->type==='string'
- && !$column->isPrimaryKey) {
- echo $column->name;
- $found = true;
- }
+ return (string) $this-><?php echo $this->identificationColumn; ?>;
}
- // if the columns contains no column of type 'string', return the
- // first column (usually the primary key)
- if(!$found)
- echo reset($columns)->name;
- ?>;
-
- }
-
}
View
18 fullModel/views/index.php
@@ -111,6 +111,22 @@
</div>
<?php echo $form->error($model,'modelClass'); ?>
</div>
+ <div class="row">
+ <?php echo $form->labelEx($model,'identificationColumn'); ?>
+ <?php echo $form->textField($model,'identificationColumn', array('size'=>65)); ?>
+ <div class="tooltip">
+ If you specify a column here, the generated Model will use the column
+ as a human-readable identifier. Specify the 'title' or 'name' attribute of
+ the model here. Leave it empty to let the column be guessed automatically.
+ Set it to 'id' or to the PK of the model to bypass this feature. <hr />
+ If unsure, leave it empty <hr />
+ The 'identificationColumnValidator' will automatically applied to the column
+ because certain conditions need to be met for the column. Check the Validator
+ for details.
+ </div>
+ <?php echo $form->error($model,'identificationColumn'); ?>
+ </div>
+
<div class="row sticky">
<?php echo $form->labelEx($model,'baseClass'); ?>
<?php echo $form->textField($model,'baseClass',array('size'=>65)); ?>
@@ -130,4 +146,6 @@
<?php echo $form->error($model,'modelPath'); ?>
</div>
+
+
<?php $this->endWidget(); ?>

0 comments on commit d959750

Please sign in to comment.