From 6aaf4cce43dd0f222a16bdcae962a1332ea5d4e2 Mon Sep 17 00:00:00 2001 From: Sam Georges Date: Wed, 28 May 2014 12:37:38 +1000 Subject: [PATCH] Form Relation widget now supports a custom name field Also detects NestedModel behavior listNested() --- modules/backend/formwidgets/Relation.php | 33 ++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/modules/backend/formwidgets/Relation.php b/modules/backend/formwidgets/Relation.php index d746a9344..341928366 100644 --- a/modules/backend/formwidgets/Relation.php +++ b/modules/backend/formwidgets/Relation.php @@ -33,6 +33,21 @@ class Relation extends FormWidgetBase */ public $renderFormField; + /** + * @var string Model column to use for the name reference + */ + public $nameColumn = 'name'; + + /** + * @var string Model column to use for the description reference + */ + public $descriptionColumn = 'description'; + + /** + * @var string Empty value to use if the relation is singluar (belongsTo) + */ + public $emptyOption; + /** * {@inheritDoc} */ @@ -41,6 +56,10 @@ class Relation extends FormWidgetBase $this->relationName = $this->formField->columnName; $this->relationType = $this->model->getRelationType($this->relationName); + $this->nameColumn = $this->getConfig('nameColumn', $this->nameColumn); + $this->descriptionColumn = $this->getConfig('descriptionColumn', $this->descriptionColumn); + $this->emptyOption = $this->getConfig('emptyOption'); + if (!$this->model->hasRelation($this->relationName)) throw new SystemException(Lang::get('backend::lang.model.missing_relation', ['class'=>get_class($this->controller), 'relation'=>$this->relationName])); } @@ -70,6 +89,7 @@ class Relation extends FormWidgetBase $field = clone $this->formField; $relationObj = $this->model->{$this->relationName}(); $relatedObj = $this->model->makeRelation($this->relationName); + $query = $relatedObj->newQuery(); if ($this->relationType == 'belongsToMany') { $field->type = 'checkboxlist'; @@ -77,12 +97,21 @@ class Relation extends FormWidgetBase } else if ($this->relationType == 'belongsTo') { $field->type = 'dropdown'; + $field->placeholder = $this->emptyOption; $foreignKey = $relationObj->getForeignKey(); $field->value = $this->model->$foreignKey; } - // @todo Should be configurable - $field->options = $relatedObj->all()->lists('name', 'id'); + // It is safe to assume that if the model and related model are of + // the exact same class, then it cannot be related to itself + if ($this->model->exists && (get_class($this->model) == get_class($relatedObj))) { + $query->where($relatedObj->getKeyName(), '<>', $this->model->id); + } + + if ($relatedObj->isClassExtendedWith('October.Rain.Database.Behaviors.NestedSetModel')) + $field->options = $query->orderByNested()->listsNested($this->nameColumn, $relatedObj->getKeyName()); + else + $field->options = $query->lists($this->nameColumn, $relatedObj->getKeyName()); return $this->renderFormField = $field; }