Form Relation widget now supports a custom name field
Also detects NestedModel behavior listNested()
This commit is contained in:
parent
b47e3587f4
commit
6aaf4cce43
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue