3 namespace Drupal\metatag\Form;
5 use Drupal\Core\Form\ConfigFormBase;
6 use Drupal\Core\Form\FormStateInterface;
9 * Defines the configuration export form.
11 class MetatagSettingsForm extends ConfigFormBase {
16 public function getFormId() {
17 return 'metatag_admin_settings';
23 protected function getEditableConfigNames() {
24 return ['metatag.settings'];
30 public function buildForm(array $form, FormStateInterface $form_state) {
31 $settings = $this->config('metatag.settings')->get('entity_type_groups');
33 $form['entity_type_groups'] = [
36 '#title' => $this->t('Entity type / Group Mapping'),
37 '#description' => $this->t('Identify which metatag groups should be available on which entity type / bundle combination. Unselected groups will not appear on the configuration form for that entity type, reducing the size of the form and increasing performance. If no groups are selected for a type, all groups will appear.'),
41 $metatag_manager = \Drupal::service('metatag.manager');
42 $bundle_manager = \Drupal::service('entity_type.bundle.info');
43 $metatag_groups = $metatag_manager->sortedGroups();
44 $entity_types = MetatagDefaultsForm::getSupportedEntityTypes();
45 foreach ($entity_types as $entity_type => $entity_label) {
46 $bundles = $bundle_manager->getBundleInfo($entity_type);
47 foreach ($bundles as $bundle_id => $bundle_info) {
48 // Create an option list for each bundle.
50 foreach ($metatag_groups as $group_name => $group_info) {
51 $options[$group_name] = $group_info['label'];
53 // Format a collapsible fieldset for each group for easier readability.
54 $form['entity_type_groups'][$entity_type][$bundle_id] = [
56 '#title' => $entity_label . ': ' . $bundle_info['label'],
58 $form['entity_type_groups'][$entity_type][$bundle_id][] = [
59 '#type' => 'checkboxes',
60 '#options' => $options,
61 '#default_value' => isset($settings[$entity_type]) && isset($settings[$entity_type][$bundle_id]) ? $settings[$entity_type][$bundle_id] : [],
66 return parent::buildForm($form, $form_state);
72 public function submitForm(array &$form, FormStateInterface $form_state) {
73 $settings = $this->config('metatag.settings');
74 $value = $form_state->getValue('entity_type_groups');
75 $value = static::arrayFilterRecursive($value);
76 // Remove the extra layer created by collapsible fieldsets.
77 foreach ($value as $entity_type => $bundle) {
78 foreach ($bundle as $bundle_id => $groups) {
79 $value[$entity_type][$bundle_id] = $groups[0];
82 $settings->set('entity_type_groups', $value)->save();
83 parent::submitForm($form, $form_state);
87 * Recursively filter results.
90 * The array to filter.
95 public static function arrayFilterRecursive(array $input) {
96 foreach ($input as &$value) {
97 if (is_array($value)) {
98 $value = static::arrayFilterRecursive($value);
101 return array_filter($input);