1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Ui;
6:
7: use Atk4\Data\Model;
8:
9: /**
10: * Display a card section within a Card View.
11: */
12: class CardSection extends View
13: {
14: /** @var Card */
15: public $card;
16:
17: /** @var string */
18: public $glue = ': ';
19:
20: /** @var array<int, string> */
21: public $tableClass = ['fixed', 'small'];
22:
23: #[\Override]
24: protected function init(): void
25: {
26: parent::init();
27:
28: $this->addClass('content');
29: }
30:
31: /**
32: * Add Description to card section.
33: *
34: * @param string|View $description
35: *
36: * @return View
37: */
38: public function addDescription($description)
39: {
40: $view = null;
41:
42: if (is_string($description)) {
43: $view = View::addTo($this, [$description, 'class' => ['description']]);
44: } else {
45: $view = $this->add($description)->addClass('description');
46: }
47:
48: return $view;
49: }
50:
51: /**
52: * Add Model fields to a card section.
53: */
54: public function addFields(Model $model, array $fields, bool $useLabel = false, bool $useTable = false): void
55: {
56: $model->assertIsLoaded();
57:
58: if ($useTable) {
59: $this->addTableSection($model, $fields);
60: } else {
61: $this->addSectionFields($model, $fields, $useLabel);
62: }
63: }
64:
65: /**
66: * Add fields label and value to section.
67: */
68: private function addSectionFields(Model $model, array $fields, bool $useLabel = false): void
69: {
70: foreach ($fields as $field) {
71: if ($model->titleField === $field) {
72: continue;
73: }
74:
75: $value = $this->getApp()->uiPersistence->typecastSaveField($model->getField($field), $model->get($field));
76: if ($useLabel) {
77: $label = $model->getField($field)->getCaption();
78: $value = $label . $this->glue . $value;
79: }
80:
81: if ($value) {
82: $this->addDescription($value);
83: }
84: }
85: }
86:
87: /**
88: * Add field into section using a CardTable View.
89: */
90: private function addTableSection(Model $model, array $fields): void
91: {
92: $cardTable = CardTable::addTo($this, ['class' => $this->tableClass]);
93: $cardTable->setModel($model, $fields);
94: }
95: }
96: