Browse Source

trimmed consoldation

main
astanley 3 months ago
parent
commit
2715379e47
  1. 8
      css/styles.css
  2. 18
      js/help_modal.js
  3. 2
      roblib_alter_solr.services.yml
  4. 71
      src/EventSubscriber/RoblibAlterSolrSubscriber.php
  5. 78
      src/Form/RoblibAlterSolrSettingsForm.php

8
css/styles.css

@ -32,3 +32,11 @@
text-decoration: none;
cursor: pointer;
}
#pairs-wrapper .source-field,
#pairs-wrapper .destination-field {
max-width: 49%;
width: 49%;
box-sizing: border-box;
display: inline-block; /* keeps both at 49% inside a cell */
}

18
js/help_modal.js

@ -7,17 +7,15 @@
var modalContent = '<div id="help-modal" class="modal">' +
'<div class="modal-content">' +
'<span class="close-button">&times;</span>' +
'<h3>Consolidating existing Solr fields</h3>' +
'<p>The form allows you concatenate two or more existing Solr fields to a new multivalue field. </ br>' +
'Select existing fields from the dropdowns on the left to pair them with a new field</ br> ' +
'entered in the column on the right. </ br>The new field name need not exist in your Solr config already.</p>' +
'<h3>Normalizing Custom Strings</h3>' +
'<p>Create a Custom value string on your Solr index, and populate it with pipe separated tokens ' +
'such as <em>[node:field_country]|[node:field_geo_area]|node:field_geo_city]</em>, ' +
'then select this field in the Normalize selector below. The resulting Solr field will be a comma-separated string, ' +
'allowing multiple values per tokenized Drupal field. </p>'
'<h3>Append Solr Fields</h3>' +
'<p>The form allows you append results from one or more Solr fields to an existing Solr field. <br>' +
'Select Source fields from the dropdowns on the left to append them with a Destination field on the right.' +
'</p>' +
'<p>Multiple source fields may be appended to a single destination field.</p>'
'</div>' +
'</div>';
'</div>';
$('body').append(modalContent);
$('#help-modal').fadeIn();

2
roblib_alter_solr.services.yml

@ -1,6 +1,6 @@
services:
roblib_alter_solr.event_subscriber:
class: Drupal\roblib_alter_solr\EventSubscriber\RoblibAlterSolrSubscriber
arguments: ['@logger.factory', '@config.factory']
arguments: ['@logger.factory', '@config.factory', '@entity_type.manager']
tags:
- { name: event_subscriber }

71
src/EventSubscriber/RoblibAlterSolrSubscriber.php

@ -7,6 +7,9 @@ use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\search_api_solr\Event\SearchApiSolrEvents;
use Drupal\search_api_solr\Event\PostCreateIndexDocumentEvent;
use Drupal\Core\Config\ConfigFactory;
use Drupal\search_api\Plugin\search_api\data_type\value\TextValue;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Allows users to combine Solr fields dynamically.
@ -27,6 +30,13 @@ final class RoblibAlterSolrSubscriber implements EventSubscriberInterface {
*/
protected $config;
/**
* The Entity Type Manager.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $entityTypeManager;
/**
* Constructs a new RoblibAlterSolrSubscriber.
*
@ -34,10 +44,13 @@ final class RoblibAlterSolrSubscriber implements EventSubscriberInterface {
* The logger factory service.
* @param \Drupal\Core\Config\ConfigFactory $config
* The config factory service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* The EntityTypeManager.
*/
public function __construct(LoggerChannelFactoryInterface $logger_factory, ConfigFactory $config) {
public function __construct(LoggerChannelFactoryInterface $logger_factory, ConfigFactory $config, EntityTypeManagerInterface $entityTypeManager) {
$this->logger = $logger_factory->get('roblib_alter_solr');
$this->config = $config->get('roblib_alter_solr.settings');
$this->entityTypeManager = $entityTypeManager;
}
/**
@ -59,35 +72,45 @@ final class RoblibAlterSolrSubscriber implements EventSubscriberInterface {
$solrDocument = $event->getSolariumDocument();
$item = $event->getSearchApiItem();
$pairs = $this->config->get('pairs');
foreach ($pairs as $index => $values) {
$fields = array_values($values['source']);
$consolidated_values = [];
$results = [];
foreach ($pairs as $pair) {
$dest = $pair['destination'];
if (!isset($results[$dest])) {
$results[$dest] = [];
}
$results[$dest][] = $pair['source'];
}
$consolidated_values = [];
foreach ($results as $index => $fields) {
$consolidated_values[$index] = [];
foreach ($fields as $field) {
$field_value = $item->getField($field);
if ($field_value && $field_value->getValues()) {
$all_values = $field_value->getValues();
$consolidated_values[] = $all_values[0];
$values = $field_value->getValues();
$normalized = array_map(function($v) {
if ($v instanceof TextValue) {
return $v->getText();
}
elseif (is_object($v) && method_exists($v, 'getValue')) {
return $v->getValue();
}
elseif (is_array($v)) {
return implode(', ', array_map('strval', $v));
}
return (string) $v;
}, $values);
$consolidated_values[$index] = array_merge($normalized, $consolidated_values[$index]);
}
}
if ($consolidated_values) {
$field_name = "sm_{$values['destination']}";
$solrDocument->setField($field_name, $consolidated_values);
}
foreach ($this->config->get('normalize') as $name) {
$field_value = $item->getField($name);
if ($field_value && $field_value->getValues()) {
$value = $field_value->getValues()[0] ?? '';
$cleaned_string = preg_match('/^\|+$/', $value) ? '' : preg_replace('/\|+/', ', ', $value);
if ($cleaned_string) {
$solrDocument->setField("ss_{$name}", $cleaned_string);
}
else {
$solrDocument->removeField("ss_{$name}");
}
}
}
if ($consolidated_values) {
foreach ($consolidated_values as $field_name => $values) {
$source = $item->getField($field_name);
$source_values = $source->getValues();
$array_values = array_merge($source_values, $values);
$field_name = "sm_{$field_name}";
$solrDocument->setField($field_name, $array_values);
}
}
}

78
src/Form/RoblibAlterSolrSettingsForm.php

@ -35,7 +35,7 @@ final class RoblibAlterSolrSettingsForm extends ConfigFormBase {
$solr_fields = $solr_config->get('field_settings');
$fields_options = [];
foreach ($solr_fields as $name => $field) {
$fields_options[$name] = $field['label'];
$fields_options[$name] = $field['label'] . ' - ' . $name;
}
// Use getStorage() to persist state across AJAX calls.
$pairs = $form_state->getStorage()['pairs'] ?? $form_state->get('pairs') ?? $config->get('pairs') ?? [];
@ -46,6 +46,9 @@ final class RoblibAlterSolrSettingsForm extends ConfigFormBase {
'#prefix' => '<div id="open_link-wrapper">',
'#suffix' => '</div>',
];
$form['pairs_description'] = [
'#type' => 'markup',
'#markup' => '<p><strong>' . $this->t('Define the source and destination mappings.') . '</strong></p>',
@ -53,26 +56,52 @@ final class RoblibAlterSolrSettingsForm extends ConfigFormBase {
$form['pairs'] = [
'#type' => 'table',
'#header' => [
'',
$this->t('Source'),
$this->t('Destination'),
$this->t('Operations'),
$this->t('Weight'),
],
'#tabledrag' => [
[
'action' => 'order', // we are ordering rows
'relationship' => 'sibling',
'group' => 'pairs-weight', // CSS class applied to the weight field
],
],
'#prefix' => '<div id="pairs-wrapper">',
'#suffix' => '</div>',
];
$added = FALSE;
foreach ($pairs as $index => $pair) {
$form['pairs'][$index]['#attributes']['class'][] = 'draggable';
$form['pairs'][$index]['handle'] = [
'#markup' => '',
'#attributes' => ['class' => ['tabledrag-handle']],
];
$form['pairs'][$index]['source'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#options' => $fields_options,
'#default_value' => $pair['source'] ?? '',
'#attributes' => ['class' => ['source-field']],
];
$form['pairs'][$index]['destination'] = [
'#type' => 'textfield',
'#type' => 'select',
'#options' => $fields_options,
'#default_value' => $pair['destination'] ?? '',
'#attributes' => ['class' => ['destination-field']],
];
$form['pairs'][$index]['weight'] = [
'#type' => 'weight',
'#title' => $this->t('Weight for row @row', ['@row' => $index]),
'#title_display' => 'invisible',
'#default_value' => $pair['weight'] ?? 0,
'#attributes' => [
'class' => ['pairs-weight', 'tabledrag-hide'],
],
];
if ($pair['source'] && $pair['destination']) {
$form['pairs'][$index]['remove'] = [
@ -101,25 +130,37 @@ final class RoblibAlterSolrSettingsForm extends ConfigFormBase {
$form['pairs'][$index]['destination']['#attributes'] = ['class' => ['destination-field']];
$added = TRUE;
}
}
if (!$added) {
$unique_id = uniqid();
$pairs[$unique_id] = ['source' => '', 'destination' => ''];
$form['pairs'][$unique_id]['handle'] = [
'#markup' => '',
'#attributes' => ['class' => ['tabledrag-handle']],
];
$form['pairs'][$unique_id]['source'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#options' => $fields_options,
'#default_value' => '',
'#default_value' => $pair['source'] ?? '',
'#attributes' => ['class' => ['source-field']],
];
$form['pairs'][$unique_id]['destination'] = [
'#type' => 'textfield',
'#type' => 'select',
'#options' => $fields_options,
'#default_value' => '',
'#attributes' => ['class' => ['destination-field']],
];
$form['add'] = [
$form['pairs'][$unique_id]['weight'] = [
'#type' => 'weight',
'#title' => $this->t('Weight for row @row', ['@row' => $unique_id]),
'#title_display' => 'invisible',
'#default_value' => $pair['weight'] ?? 0,
'#attributes' => [
'class' => ['pairs-weight', 'tabledrag-hide'],
],
];
$form['pairs'][$unique_id]['add'] = [
'#type' => 'submit',
'#value' => $this->t('Add Row'),
'#submit' => ['::addCallback'],
@ -128,18 +169,8 @@ final class RoblibAlterSolrSettingsForm extends ConfigFormBase {
'wrapper' => 'pairs-wrapper',
],
];
}
$form['normalize_description'] = [
'#type' => 'markup',
'#markup' => '<p><strong>' . $this->t('Select aggregated field(s) to be normalized..') . '</strong></p>',
];
$form['normalize'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#options' => $fields_options,
'#default_value' => $config->get('normalize') ?? '',
];
$form['#attached']['library'][] = 'roblib_alter_solr/roblib_alter_solr';
return parent::buildForm($form, $form_state);
@ -185,12 +216,15 @@ final class RoblibAlterSolrSettingsForm extends ConfigFormBase {
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$pairs = $form_state->getValue('pairs');
$filtered_pairs= array_filter($pairs, function ($item) {
return !empty($item['destination']);
});
$normalize = $form_state->getValue('normalize');
$this->config('roblib_alter_solr.settings')
->set('pairs', $pairs)
->set('normalize', $normalize)
->set('pairs', $filtered_pairs)
->save();
$this->messenger()->addStatus($this->t('Configuration saved successfully.'));
$this->messenger()
->addStatus($this->t('Configuration saved successfully.'));
}
}

Loading…
Cancel
Save