-
Notifications
You must be signed in to change notification settings - Fork 554
/
TwillFormComponent.php
69 lines (56 loc) · 2.05 KB
/
TwillFormComponent.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
<?php
namespace A17\Twill\View\Components\Fields;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\View as ViewFacade;
use Illuminate\View\Component;
/**
* The constructor of our components does grow quite large, but the benefit of this is that it is clear what is
* in, needs to be in, and it provides autocomplete on modern code editors.
*/
abstract class TwillFormComponent extends Component
{
public ?Model $item;
public array $form_fields;
public ?string $formModuleName;
public ?string $routePrefix;
public function __construct(
public string $name,
public string $label,
public ?string $note = '',
public bool $inModal = false,
public bool $readOnly = false,
public bool $renderForBlocks = false,
public bool $renderForModal = false,
public bool $disabled = false,
public bool $required = false,
public bool $translated = false,
public mixed $default = null
) {
// This can be null. In that case the field might be used outside of a form and we have no shared $form.
$form = ViewFacade::shared("form");
$this->item = $form['item'] ?? null;
$this->form_fields = $form['form_fields'] ?? [];
$this->formModuleName = $form['moduleName'] ?? null;
$this->routePrefix = $form['routePrefix'] ?? null;
$shared = ViewFacade::shared('TwillUntilConsumed', []);
foreach ($shared as $key => $value) {
$this->{$key} = $value;
}
}
public function formFieldName(bool $asAttributes = false, ?string $customName = null): string
{
$name = $customName ?? $this->name;
if ($this->renderForBlocks) {
if ($asAttributes) {
return "name: fieldName('$name')";
}
return ":name=\"fieldName('$name')\"";
}
if ($asAttributes) {
return "name: '$name'";
}
return "name=\"$name\"";
}
abstract public function render(): View;
}