Elgg  Version 6.3
FieldsService.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Forms;
4 
8 use Elgg\Traits\Loggable;
9 
16 
17  use Loggable;
18 
19  protected array $fields = [];
20 
28  public function __construct(protected EventsService $events, protected Translator $translator, protected EntityTable $entityTable) {
29  }
30 
39  public function get(string $type, string $subtype): array {
40  if (isset($this->fields[$type][$subtype])) {
41  return $this->fields[$type][$subtype];
42  }
43 
44  $entity_class = $this->entityTable->getEntityClass($type, $subtype);
45  $defaults = !empty($entity_class) ? $entity_class::getDefaultFields() : [];
46  $priority = 100;
47  foreach ($defaults as &$default_field) {
48  if (!isset($default_field['priority'])) {
49  $default_field['priority'] = $priority;
50  $priority += 100;
51  }
52  }
53 
54  $result = (array) $this->events->triggerResults('fields', "{$type}:{$subtype}", [
55  'type' => $type,
56  'subtype' => $subtype,
57  ], $defaults);
58 
59  $fields = [];
60  // validate fields and generate labels
61  foreach ($result as $field) {
62  if (empty($field['name']) || empty($field['#type'])) {
63  $this->getLogger()->warning("Field config for '{$type}:{$subtype}' is missing 'name' or '#type' in field: " . print_r($field, true));
64  continue;
65  }
66 
67  if (!isset($field['#label'])) {
68  $label_key = "fields:{$type}:{$subtype}:{$field['name']}";
69  if ($this->translator->languageKeyExists($label_key)) {
70  $field['#label'] = $this->translator->translate($label_key);
71  }
72  }
73 
74  if (!isset($field['#help'])) {
75  $label_key = "fields:{$type}:{$subtype}:{$field['name']}:help";
76  if ($this->translator->languageKeyExists($label_key)) {
77  $field['#help'] = $this->translator->translate($label_key);
78  }
79  }
80 
81  if (!isset($field['priority'])) {
82  $field['priority'] = $priority;
83  $priority += 100;
84  }
85 
86  $fields[] = $field;
87  }
88 
89  // sort fields by priority
90  usort($fields, function ($a, $b) {
91  return (int) $a['priority'] - (int) $b['priority'];
92  });
93 
94  foreach ($fields as &$field) {
95  // remove priority as we do not want it leaking to field vars
96  unset($field['priority']);
97  }
98 
99  $this->fields[$type][$subtype] = $fields;
100 
101  return $fields;
102  }
103 }
$subtype
Definition: delete.php:22
$type
Definition: delete.php:21
Entity table database service.
Definition: EntityTable.php:24
Events service.
Service for getting field definitions for type/subtype combinations.
__construct(protected EventsService $events, protected Translator $translator, protected EntityTable $entityTable)
Constructor.
if(elgg_extract('input_type', $vars)) if(elgg_extract('required', $vars)) if(elgg_extract('disabled', $vars)) $field
Definition: field.php:42
$defaults
Generic entity header upload helper.
Definition: header.php:6
$priority