You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.2 KiB
62 lines
2.2 KiB
<?php |
|
|
|
namespace Drupal\dynamic_field_label\Form; |
|
|
|
use Drupal\Core\Form\ConfigFormBase; |
|
use Drupal\Core\Form\FormStateInterface; |
|
use Drupal\field\Entity\FieldConfig; |
|
use Drupal\Core\Render\Element\Checkboxes; |
|
|
|
/** |
|
* Selects existing configurable text fields by machine name. |
|
*/ |
|
final class SettingsForm extends ConfigFormBase { |
|
|
|
public function getFormId(): string { |
|
return 'dynamic_field_label_settings'; |
|
} |
|
|
|
protected function getEditableConfigNames(): array { |
|
return ['dynamic_field_label.settings']; |
|
} |
|
|
|
public function buildForm(array $form, FormStateInterface $form_state): array { |
|
$selected = $this->config('dynamic_field_label.settings')->get('fields') ?? []; |
|
$options = []; |
|
$locations = []; |
|
foreach (FieldConfig::loadMultiple() as $field) { |
|
if (!in_array($field->getType(), ['string', 'string_long', 'text', 'text_long', 'text_with_summary'], TRUE)) { |
|
continue; |
|
} |
|
$name = $field->getName(); |
|
$locations[$name][] = $field->getLabel() . ' (' . $field->getTargetEntityTypeId() . ':' . $field->getTargetBundle() . ')'; |
|
} |
|
foreach ($locations as $name => $labels) { |
|
$options[$name] = $name . ' — ' . implode('; ', array_unique($labels)); |
|
} |
|
// Preserve configured names when a field has temporarily been removed. |
|
foreach ($selected as $name) { |
|
$options[$name] ??= $name . ' (' . $this->t('not currently available') . ')'; |
|
} |
|
ksort($options); |
|
$form['fields'] = [ |
|
'#type' => 'checkboxes', |
|
'#title' => $this->t('Text fields'), |
|
'#options' => $options, |
|
'#default_value' => $selected, |
|
'#description' => $this->t('Selected machine names apply across entity types and bundles. Values must use label:value. Labels are plain text; values retain their assigned text format for formatted fields.'), |
|
]; |
|
return parent::buildForm($form, $form_state); |
|
} |
|
|
|
public function submitForm(array &$form, FormStateInterface $form_state): void { |
|
$fields = array_values( |
|
Checkboxes::getCheckedCheckboxes( |
|
$form_state->getValue('fields') ?? [] |
|
) |
|
); |
|
$this->config('dynamic_field_label.settings')->set('fields', $fields)->save(); |
|
parent::submitForm($form, $form_state); |
|
} |
|
|
|
}
|
|
|