diff --git a/forms/ComplexTableField.php b/forms/ComplexTableField.php index 51f3716b1..9c7c0a679 100755 --- a/forms/ComplexTableField.php +++ b/forms/ComplexTableField.php @@ -180,6 +180,24 @@ class ComplexTableField extends TableListField { } + /** + * Return the record filter for this table. + * It will automatically add a relation filter if relationAutoSetting is true, and it can determine an appropriate + * filter. + */ + function sourceFilter() { + $sourceFilter = parent::sourceFilter(); + if($this->relationAutoSetting + && $this->getParentClass() + && ($filterKey = $this->getParentIdName($this->getParentClass(), $this->sourceClass())) + && ($filterValue = $this->sourceID()) ) { + + $newFilter = "`$filterKey` = '" . Convert::raw2sql($filterValue) . "'"; + $sourceFilter = $sourceFilter ? "($sourceFilter) AND ($newFilter)" : $newFilter; + } + return $sourceFilter; + } + function isComposite() { return false; } @@ -486,6 +504,15 @@ JS; return $form; } + /** + * By default, a ComplexTableField will assume that the field name is the name of a has-many relation on the object being + * edited. It will identify the foreign key in the object being listed, and filter on that column, as well as auto-setting + * that column for newly created records. + * + * Calling $this->setRelationAutoSetting(false) will disable this functionality. + * + * @param boolean $value Should the relation auto-setting functionality be enabled? + */ function setRelationAutoSetting($value) { $this->relationAutoSetting = $value; } diff --git a/forms/TableListField.php b/forms/TableListField.php index 57125f8de..66d65af88 100755 --- a/forms/TableListField.php +++ b/forms/TableListField.php @@ -247,6 +247,13 @@ class TableListField extends FormField { Requirements::css('sapphire/css/TableListField.css'); } + /** + * Get the filter + */ + function sourceFilter() { + return $this->sourceFilter; + } + function index() { return $this->FieldHolder(); } @@ -421,7 +428,7 @@ JS $query->select[] = "{$baseClass}.ClassName AS ClassName"; $query->select[] = "{$baseClass}.ClassName AS RecordClassName"; } else { - $query = singleton($this->sourceClass)->extendedSQL($this->sourceFilter, $this->sourceSort, null, $this->sourceJoin); + $query = singleton($this->sourceClass)->extendedSQL($this->sourceFilter(), $this->sourceSort, null, $this->sourceJoin); // Add more selected fields if they are from joined table. @@ -456,7 +463,7 @@ JS $query->select[] = "{$baseClass}.ClassName AS ClassName"; $query->select[] = "{$baseClass}.ClassName AS RecordClassName"; } else { - $query = singleton($this->sourceClass)->extendedSQL($this->sourceFilter, $this->sourceSort, null, $this->sourceJoin); + $query = singleton($this->sourceClass)->extendedSQL($this->sourceFilter(), $this->sourceSort, null, $this->sourceJoin); // Add more selected fields if they are from joined table. foreach($this->FieldList() as $k=>$title){