Implement model filtering for selectValue method

This commit is contained in:
Marcus Moore 2023-12-21 13:03:43 -08:00
parent 1dd9273f70
commit 62f8353bd7
No known key found for this signature in database
3 changed files with 31 additions and 4 deletions

View file

@ -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;
}

View file

@ -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'),

View file

@ -79,9 +79,29 @@ class ReportTemplateTest extends TestCase
public function testSelectValueDoesNotIncludeDeletedOrNonExistentModels()
{
$this->markTestIncomplete();
[$locationA, $locationB] = Location::factory()->count(2)->create();
$invalidId = 10000;
// @todo: maybe it should optionally include deleted values?
$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)
);
$this->assertNull($templateWithDeletedId->selectValue('single_value', Location::class));
$this->assertNull($templateWithInvalidId->selectValue('single_value', Location::class));
}
public function testSelectValuesDoNotIncludeDeletedOrNonExistentModels()