Implement test for filtering out invalid models from selectValues

This commit is contained in:
Marcus Moore 2023-12-21 12:02:48 -08:00
parent 71761a48ad
commit 6fcbb108c6
No known key found for this signature in database
3 changed files with 37 additions and 7 deletions

View file

@ -65,7 +65,7 @@ class ReportTemplate extends Model
return $this->options[$property] ?? null;
}
public function selectValues(string $property)
public function selectValues(string $property, string $model = null)
{
if (!isset($this->options[$property])) {
return null;
@ -75,6 +75,12 @@ class ReportTemplate extends Model
return null;
}
// If a model is provided then we should ensure we only return
// the ids of models that exist and are not deleted.
if ($model) {
return $model::findMany($this->options[$property])->pluck('id');
}
return $this->options[$property];
}

View file

@ -287,14 +287,14 @@
'multiple' => 'true',
'fieldname' => 'by_location_id[]',
'hide_new' => 'true',
'selected' => $reportTemplate->selectValues('by_location_id')
'selected' => $reportTemplate->selectValues('by_location_id', \App\Models\Location::class)
])
@include ('partials.forms.edit.location-select', [
'translated_name' => trans('admin/hardware/form.default_location'),
'multiple' => 'true',
'fieldname' => 'by_rtd_location_id[]',
'hide_new' => 'true',
'selected' => $reportTemplate->selectValues('by_rtd_location_id')
'selected' => $reportTemplate->selectValues('by_rtd_location_id', \App\Models\Location::class)
])
@include ('partials.forms.edit.department-select', [
'translated_name' => trans('general.department'),

View file

@ -2,6 +2,7 @@
namespace Tests\Unit;
use App\Models\Location;
use App\Models\ReportTemplate;
use Tests\TestCase;
@ -85,11 +86,34 @@ class ReportTemplateTest extends TestCase
public function testSelectValuesDoNotIncludeDeletedOrNonExistentModels()
{
$this->markTestIncomplete();
[$locationA, $locationB] = Location::factory()->count(2)->create();
// report saved with select option for a company (or whatever)
// company is deleted
// ensure company's id is not returned
$savedReport = ReportTemplate::factory()->create([
'options' => [
'by_location_id' => [
$locationA->id,
$locationB->id,
10000
],
],
]);
$locationB->delete();
$this->assertContains(
$locationA->id,
$savedReport->selectValues('by_location_id', Location::class)
);
$this->assertNotContains(
$locationB->id,
$savedReport->selectValues('by_location_id', Location::class)
);
$this->assertNotContains(
10000,
$savedReport->selectValues('by_location_id', Location::class)
);
}
public function testGracefullyHandlesSingleSelectBecomingMultiSelect()