Skip to content

A free open source IT asset/license management system

Implement model filtering for selectValue method

Marcus Moore62f8353bd74a
diff --git a/app/Models/ReportTemplate.php b/app/Models/ReportTemplate.php
index 509ccaefc1..10ac5a9f1a 100644
--- a/app/Models/ReportTemplate.php
+++ b/app/Models/ReportTemplate.php
@@ -60,8 +60,15 @@ class ReportTemplate extends Model
return null;
}
- public function selectValue(string $property)
+ public function selectValue(string $property, string $model = null)
{
+ // If a model is provided then we should ensure we only return
+ // the value if the model still exists.
+ if ($model) {
+ $foundModel = $model::find($this->options[$property]);
+
+ return $foundModel ? $foundModel->id : null;
+ }
return $this->options[$property] ?? null;
}
diff --git a/resources/views/reports/custom.blade.php b/resources/views/reports/custom.blade.php
index 343ed727a5..46891575b2 100644
--- a/resources/views/reports/custom.blade.php
+++ b/resources/views/reports/custom.blade.php
@@ -300,7 +300,7 @@
'translated_name' => trans('general.department'),
'fieldname' => 'by_dept_id',
'hide_new' => 'true',
- 'selected' => $reportTemplate->selectValue('by_dept_id')
+ 'selected' => $reportTemplate->selectValue('by_dept_id', \App\Models\Department::class)
])
@include ('partials.forms.edit.supplier-select', [
'translated_name' => trans('general.supplier'),
diff --git a/tests/Unit/ReportTemplateTest.php b/tests/Unit/ReportTemplateTest.php
index 9c1e45e065..c75433fa1e 100644
--- a/tests/Unit/ReportTemplateTest.php
+++ b/tests/Unit/ReportTemplateTest.php
@@ -79,9 +79,29 @@ class ReportTemplateTest extends TestCase
public function testSelectValueDoesNotIncludeDeletedOrNonExistentModels()
{
- $this->markTestIncomplete();
+ [$locationA, $locationB] = Location::factory()->count(2)->create();
+ $invalidId = 10000;
+
+ $templateWithValidId = ReportTemplate::factory()->create([
+ 'options' => ['single_value' => $locationA->id],
+ ]);
+
+ $templateWithDeletedId = ReportTemplate::factory()->create([
+ 'options' => ['single_value' => $locationB->id],
+ ]);
+ $locationB->delete();
+
+ $templateWithInvalidId = ReportTemplate::factory()->create([
+ 'options' => ['single_value' => $invalidId],
+ ]);
+
+ $this->assertEquals(
+ $locationA->id,
+ $templateWithValidId->selectValue('single_value', Location::class)
+ );
- // @todo: maybe it should optionally include deleted values?
+ $this->assertNull($templateWithDeletedId->selectValue('single_value', Location::class));
+ $this->assertNull($templateWithInvalidId->selectValue('single_value', Location::class));
}
public function testSelectValuesDoNotIncludeDeletedOrNonExistentModels()