2024-04-04 12:20:03 -07:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Requests\Traits;
|
|
|
|
|
2024-04-04 15:41:10 -07:00
|
|
|
use App\Models\AssetModel;
|
2024-04-07 15:07:46 -07:00
|
|
|
use App\Models\CustomField;
|
2024-04-04 15:41:10 -07:00
|
|
|
|
2024-04-04 12:20:03 -07:00
|
|
|
trait MayContainCustomFields
|
|
|
|
{
|
2024-04-04 15:41:10 -07:00
|
|
|
// this gets called automatically on a form request
|
2024-04-04 12:20:03 -07:00
|
|
|
public function withValidator($validator)
|
|
|
|
{
|
2024-04-07 15:07:46 -07:00
|
|
|
// find the model
|
|
|
|
if ($this->method() == 'POST') {
|
|
|
|
$asset_model = AssetModel::find($this->model_id);
|
|
|
|
}
|
|
|
|
if ($this->method() == 'PATCH' || $this->method() == 'PUT') {
|
2024-07-30 20:55:15 -07:00
|
|
|
$asset_model = $this->asset->model;
|
2024-04-07 15:07:46 -07:00
|
|
|
}
|
|
|
|
// collect the custom fields in the request
|
|
|
|
$validator->after(function ($validator) use ($asset_model) {
|
2024-04-04 15:41:10 -07:00
|
|
|
$request_fields = $this->collect()->keys()->filter(function ($attributes) {
|
2024-04-04 12:20:03 -07:00
|
|
|
return str_starts_with($attributes, '_snipeit_');
|
|
|
|
});
|
2024-04-07 15:07:46 -07:00
|
|
|
// if there are custom fields, find the one's that don't exist on the model's fieldset and add an error to the validator's error bag
|
2024-10-01 15:04:18 -07:00
|
|
|
if (count($request_fields) > 0 && $validator->errors()->isEmpty()) {
|
2024-07-30 19:44:22 -07:00
|
|
|
$request_fields->diff($asset_model?->fieldset?->fields?->pluck('db_column'))
|
2024-04-04 15:41:10 -07:00
|
|
|
->each(function ($request_field_name) use ($request_fields, $validator) {
|
2024-04-07 15:07:46 -07:00
|
|
|
if (CustomField::where('db_column', $request_field_name)->exists()) {
|
2024-04-07 17:50:53 -07:00
|
|
|
$validator->errors()->add($request_field_name, trans('validation.custom.custom_field_not_found_on_model'));
|
2024-04-07 15:07:46 -07:00
|
|
|
} else {
|
2024-04-07 17:50:53 -07:00
|
|
|
$validator->errors()->add($request_field_name, trans('validation.custom.custom_field_not_found'));
|
2024-04-07 15:07:46 -07:00
|
|
|
}
|
2024-04-04 15:41:10 -07:00
|
|
|
});
|
2024-04-04 12:20:03 -07:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|