Skip to content

Commit

Permalink
Merge pull request #62 from cakephp/issue-61
Browse files Browse the repository at this point in the history
Exclude foriegn keys from validation rules.
  • Loading branch information
lorenzo committed Mar 25, 2015
2 parents bd0dc50 + 60ddc84 commit 69a1460
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/Shell/Task/ModelTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public function bake($name)
$primaryKey = $this->getPrimaryKey($model);
$displayField = $this->getDisplayField($model);
$fields = $this->getFields($model);
$validation = $this->getValidation($model);
$validation = $this->getValidation($model, $associations);
$rulesChecker = $this->getRules($model, $associations);
$behaviors = $this->getBehaviors($model);

Expand Down Expand Up @@ -444,9 +444,10 @@ public function getHiddenFields($model)
* Generate default validation rules.
*
* @param \Cake\ORM\Table $model The model to introspect.
* @param array $associations The associations list.
* @return array The validation rules.
*/
public function getValidation($model)
public function getValidation($model, $associations = [])
{
if (!empty($this->params['no-validation'])) {
return [];
Expand All @@ -459,8 +460,16 @@ public function getValidation($model)

$validate = [];
$primaryKey = (array)$schema->primaryKey();

$foreignKeys = [];
if (isset($associations['belongsTo'])) {
foreach ($associations['belongsTo'] as $assoc) {
$foreignKeys[] = $assoc['foreignKey'];
}
}
foreach ($fields as $fieldName) {
if (in_array($fieldName, $foreignKeys)) {
continue;
}
$field = $schema->column($fieldName);
$validation = $this->fieldValidation($fieldName, $field, $primaryKey);
if (!empty($validation)) {
Expand Down
23 changes: 23 additions & 0 deletions tests/TestCase/Shell/Task/ModelTaskTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,29 @@ public function testGetValidation()
$this->assertEquals($expected, $result);
}

/**
* test getting validation rules and exempting foreign keys
*
* @return void
*/
public function testGetValidationExcludeForeignKeys()
{
$model = TableRegistry::get('BakeArticles');
$associations = [
'belongsTo' => [
'BakeUsers' => ['foreignKey' => 'bake_user_id'],
]
];
$result = $this->Task->getValidation($model, $associations);
$expected = [
'title' => ['valid' => ['rule' => false, 'allowEmpty' => false]],
'body' => ['valid' => ['rule' => false, 'allowEmpty' => true]],
'published' => ['valid' => ['rule' => 'boolean', 'allowEmpty' => true]],
'id' => ['valid' => ['rule' => 'numeric', 'allowEmpty' => 'create']]
];
$this->assertEquals($expected, $result);
}

/**
* test getting validation rules with the no-rules param.
*
Expand Down

0 comments on commit 69a1460

Please sign in to comment.