-
Notifications
You must be signed in to change notification settings - Fork 27
/
TimeField.php
77 lines (68 loc) · 2.05 KB
/
TimeField.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
namespace Laraning\NovaTimeField;
use Carbon\Carbon;
use DateTime;
use Laravel\Nova\Fields\Field;
use Laravel\Nova\Http\Requests\NovaRequest;
class TimeField extends Field
{
/**
* The field's component.
*
* @var string
*/
public $component = 'nova-time-field';
/**
* Create a new field.
*
* @param string $name
* @param string|null $attribute
* @param mixed|null $resolveCallback
*
* @return void
*/
public function __construct($name, $attribute = null, $resolveCallback = null)
{
parent::__construct($name, $attribute, $resolveCallback ?? function ($value) {
return Carbon::createFromFormat('H:i', $value)->format('H:i');
});
}
/**
* Indicate that the date field is nullable.
*
* @return $this
*/
public function nullable($nullable = true, $value = null)
{
return $this->withMeta(['nullable' => true]);
}
public function withTwelveHourTime()
{
return $this->withMeta(['twelveHourTime' => true]);
}
/**
* Hydrate the given attribute on the model based on the incoming request.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param string $requestAttribute
* @param object $model
* @param string $attribute
*
* @return void
*/
protected function fillAttributeFromRequest(
NovaRequest $request,
$requestAttribute,
$model,
$attribute
) {
if ($request->exists($requestAttribute) && $request[$requestAttribute]) {
$sentData = $request[$requestAttribute];
if (DateTime::createFromFormat('H:i', $sentData) === false) {
throw new Exception('The field must contain a valid time.');
}
$newDate = Carbon::createFromFormat('H:i', $request[$requestAttribute])->format('H:i');
$model->{$attribute} = $newDate;
}
}
}