I am trying to create a log record of searches made though my Search API View exposed form block in Drupal 9.
For some reason on a brand new search I get 2 duplicates (3 total entries), and it seems like I remember reading somewhere that the forms can be submitted multiple times. So I would like to know how I could eliminate that.
Update: here is an issue for Drupal 7 https://www.drupal.org/project/views/issues/2088549
Also, on searches for keywords that result in "no results" I am not seeing an entry in the log This behaviour seems hit and miss. I am using the following code with limited success:
/**
* Implements hook_form_views_exposed_form_alter().
*/
function MY_form_views_exposed_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
// Create a search_log submission function for watchdog
$view_names = array('search_api_view');
$view = $form_state->getStorage('view');
if ($form_id == 'views_exposed_form' && in_array($view['view']->id(), $view_names)) {
if ($form['#id'] == 'views-exposed-form-search-api-view-page-1') {
$form['#submit'][] = 'MY_search_api_log';
}
}
}
function MY_search_api_log(&$form, FormStateInterface $form_state) {
if ($form_state->getValue('search_api_fulltext') != "") {
// Create a link
$link = Url::fromRoute('view.search_api_view.page_1', [], ['query' => ['search_api_fulltext' => $form_state->getValue('search_api_fulltext'), ], ]);
// log the submission
\Drupal::logger('search_api_results')->info($form_state->getValue('search_api_fulltext'), ['link' => Link::fromTextAndUrl('results', $link)->toString()]);
}
}
I am trying to convert this function from a hook I am using in D7 which works fine:
/**
* Implements hook_form_views_exposed_form_alter().
*/
function MY_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
//Create a search_log submission function for watchdog
if($form_state["view"]->base_field == 'search_api_id') {
$form['#submit'][] = 'MY_search_api_log';
}
}
function MY_search_api_log(&$form, $form_state) {
if ($form_state['values']['search_api_views_fulltext'] != "") {
$link = l('results', '/search-results', ['query' => ['search_api_views_fulltext' => $form_state['values']['search_api_views_fulltext'], ], ]);
watchdog('search_api_results', $form_state['values']['search_api_views_fulltext'], [], WATCHDOG_INFO, $link);
}
}