Skip to content

Commit

Permalink
Support editing arrays for language variables
Browse files Browse the repository at this point in the history
  • Loading branch information
afbora committed Jan 23, 2025
1 parent e5188b0 commit 1384147
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 11 deletions.
49 changes: 40 additions & 9 deletions config/areas/languages/dialogs.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,25 +239,56 @@
}

$fields = $translationDialogFields;
$fields['key']['disabled'] = true;
$fields['value']['autofocus'] = true;
$fields['key']['disabled'] = true;

$value = ['key' => $variable->key()];

// if language variable is array,
// set text fields as per array size
// otherwise it will show only one textarea
if (is_array($variable->value()) === true) {
unset($fields['value']);

foreach ($variable->value() as $index => $val) {
$fields['value_' . $index] = [
'autofocus' => $index === 0,
'counter' => false,
'label' => I18n::translate('language.variable.value') . ' ' . ($index + 1),
'type' => 'text',
];
$value['value_' . $index] = $val;
}
} else {
$fields['value']['autofocus'] = true;
$value['value'] = $variable->value();
}

return [
'component' => 'k-form-dialog',
'props' => [
'fields' => $fields,
'size' => 'large',
'value' => [
'key' => $variable->key(),
'value' => $variable->value()
]
'value' => $value
],
];
},
'submit' => function (string $languageCode, string $translationKey) {
Find::language($languageCode)->variable($translationKey, true)->update(
App::instance()->request()->get('value', '')
);
$kirby = App::instance();
$variable = Find::language($languageCode)->variable($translationKey, true);

// if the language variable is array
// it reads the text field values as many as the number of arrays
if (is_array($variable->value()) === true) {
$value = array_map(
fn ($val, $index) => $kirby->request()->get('value_' . $index, ''),
$variable->value(),
array_keys($variable->value())
);
} else {
$value = $kirby->request()->get('value', '');
}

$variable->update($value);

return true;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Cms/LanguageVariable.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public function key(): string
/**
* Sets a new value for the language variable
*/
public function update(string|null $value = null): static
public function update(string|array|null $value = null): static
{
$translations = $this->language->translations();
$translations[$this->key] = $value ?? '';
Expand All @@ -115,7 +115,7 @@ public function update(string|null $value = null): static
/**
* Returns the value if the variable has been translated.
*/
public function value(): string|null
public function value(): string|array|null
{
return $this->language->translations()[$this->key] ?? null;
}
Expand Down

0 comments on commit 1384147

Please sign in to comment.