You are here

search_api_glossary.module in Search API AZ Glossary 8.2

Search api glossary module file.

File

search_api_glossary.module
View source
<?php

/**
 * @file
 * Search api glossary module file.
 */
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\search_api\IndexInterface;

/**
 * Add search_api_glossary settings to Search API Index configuration.
 *
 * Implements hook_form_FORM_ID_alter()
 */
function search_api_glossary_form_search_api_index_fields_alter(&$form, FormStateInterface $form_state) {

  // TODO Cleanup this as per Drupal standards.
  $config = \Drupal::config('search_api_glossary.settings');
  $entity = $form_state
    ->getFormObject()
    ->getEntity();

  // TODO Check if there are any limitations.
  // If not, maybe expand this in future.
  $allowed_field_types = array(
    'integer',
    'text',
    'string',
  );
  foreach ($entity
    ->getDatasources() as $datasource_id => $datasource) {
    $fields = $entity
      ->getFieldsByDatasource($datasource_id);
    foreach ($fields as $field) {
      $field_settings_array = $field
        ->getSettings();
      $datasource_id = $field_settings_array['datasource_id'];
      $datasource_id_clean = str_replace('entity:', '', $datasource_id);
      $field_name = $field_settings_array['property_path'];
      $field_label = $field_settings_array['label'];
      $field_type = $field_settings_array['type'];
      $locked = $field
        ->isTypeLocked();

      // Identify glossary fields and skip them.
      // Glossary field should be excluded always.
      // Make it default and prevent changing.
      if (substr($field_name, 0, strlen('field_glossaryaz')) !== 'field_glossaryaz') {
        if (!$locked && in_array($field_type, $allowed_field_types)) {
          $form[$datasource_id]['fields'][$field_name]['glossary_az'] = array(
            '#type' => 'checkbox',
            '#title' => t('Enable'),
            '#default_value' => $config
              ->get($field_name)['enabled'],
          );
          if (array_key_exists('glossary_az_grouping', $config
            ->get($field_name))) {
            $glossary_az_grouping_defaults = $config
              ->get($field_name)['glossary_az_grouping'];
          }
          else {
            $glossary_az_grouping_defaults = array(
              //'glossary_az_grouping_09' => 'glossary_az_grouping_09',
              'glossary_az_grouping_other' => 'glossary_az_grouping_other',
            );
          }
          $form[$datasource_id]['fields'][$field_name]['glossary_az_grouping'] = array(
            '#type' => 'checkboxes',
            #'#title' => t('Glossary grouping'),

            #'#description' => t('When grouping is enabled, individual values such as 1, 2, 3 will get grouped like "0-9"'),
            '#options' => array(
              'glossary_az_grouping_az' => 'Group Alphabetic (A-Z)',
              'glossary_az_grouping_09' => 'Group Numeric (0-9)',
              'glossary_az_grouping_other' => 'Group Non Alpha Numeric (#)',
            ),
            '#default_value' => $glossary_az_grouping_defaults,
            '#required' => FALSE,
            '#size' => 1,
          );

          // TODO Glossary field TYPE should always be STRING.
          // Array to identify which header(s) to alter.
          $datasource_ids[$datasource_id] = $datasource_id;
        }
      }
    }
  }

  // Add glossary header to each fieldset.
  if (!empty($datasource_ids)) {
    foreach ($datasource_ids as $datasource_id_unique) {
      $form[$datasource_id_unique]['#header'][] = t('Glossary');
      $form[$datasource_id_unique]['#header'][] = t('Glossary Grouping');
    }
  }

  // Add a custom validate handler.
  $form['actions']['submit']['#validate'][] = 'search_api_glossary_search_api_index_fields_validate';

  // Add a custom submit handler to save the
  // array of types back to the config file.
  $form['actions']['submit']['#submit'][] = 'search_api_glossary_search_api_index_fields_submit';
}

/**
 * Validate search_api_glossary settings for Search API Index configuration.
 */
function search_api_glossary_search_api_index_fields_validate($form, FormStateInterface $form_state) {
  $values = $form_state
    ->getValues();
  $fields = $values['fields'];
  $entity = $form_state
    ->getFormObject()
    ->getEntity();
  $field_settings_array = $entity
    ->get('field_settings');

  // If a glossary field exists but
  // parent field has been removed or
  // Glossary option is disabled and
  // Glossary field is still enabled
  // throw an error.
  foreach ($fields as $field_name => $field_values) {

    // Identify glossary fields and check parents.
    // This case would occur if Glossary field is added
    // but parent is removed or disabled.
    if (substr($field_name, 0, strlen('field_glossaryaz')) === 'field_glossaryaz') {

      // Check if the parent field for
      // this glossary field exists and is enabled.
      $glossary_parent_field = str_replace('field_glossaryaz_', '', $field_name);

      // We dont seem to have a parent field for Glossary.
      if (!array_key_exists($glossary_parent_field, $fields)) {

        // Throw an exception to remove the Glossary field.
        $form_state
          ->setErrorByName($field_name, t('@parent field is missing or removed. Please remove @glossary field or add @parent field.', array(
          '@parent' => $glossary_parent_field,
          '@glossary' => $field_settings_array[$field_name]['label'],
        )));
      }
      elseif ($fields[$glossary_parent_field]['glossary_az'] == 0) {

        // Throw an exception to remove the Glossary field.
        // Or enable glossary option.
        $form_state
          ->setErrorByName($field_name, t('@parent field does not have Glossary enabled. Please remove @glossary field or enable Glossary on @parent field.', array(
          '@parent' => $field_settings_array[$glossary_parent_field]['label'],
          '@glossary' => $field_settings_array[$field_name]['label'],
        )));
      }
    }
  }
}

/**
 * Save search_api_glossary settings for Search API Index configuration.
 */
function search_api_glossary_search_api_index_fields_submit($form, FormStateInterface $form_state) {
  $values = $form_state
    ->getValues();
  $fields = $values['fields'];
  $entity = $form_state
    ->getFormObject()
    ->getEntity();
  $field_settings_array = $entity
    ->get('field_settings');

  // TODO Cleanup this as per Drupal standards.
  \Drupal::configFactory()
    ->reset('search_api_glossary.settings');
  $config = \Drupal::configFactory()
    ->getEditable('search_api_glossary.settings');
  foreach ($fields as $field_name => $field_values) {
    $glossary_field_id = 'field_glossaryaz_' . $field_name;
    $config_values = array(
      'enabled' => 0,
      'field_type' => $field_values['type'],
      'field_name' => $field_name,
      'label' => $field_settings_array[$field_name]['label'],
      'glossary_field_id' => $glossary_field_id,
      'glossary_field_name' => 'AZ Glossary - ' . $field_settings_array[$field_name]['label'],
      'glossary_field_desc' => 'Glossary field for ' . $field_settings_array[$field_name]['label'] . '.',
    );
    if (isset($field_values['glossary_az']) && $field_values['glossary_az'] == 1) {
      $config_values['enabled'] = 1;
      $config_values['glossary_az_grouping'] = $field_values['glossary_az_grouping'];
    }

    // Set the variables.
    $config
      ->set($field_name, $config_values)
      ->save();
  }
  drupal_set_message(t("Glossary fields have been created for the chosen fields. These newly created Glossary fields can now be added by clicking on ADD FIELDS button."));
}

Functions

Namesort descending Description
search_api_glossary_form_search_api_index_fields_alter Add search_api_glossary settings to Search API Index configuration.
search_api_glossary_search_api_index_fields_submit Save search_api_glossary settings for Search API Index configuration.
search_api_glossary_search_api_index_fields_validate Validate search_api_glossary settings for Search API Index configuration.