You are here

public function IndexController::removeField in Search API 8

Removes a field from a search index.

Parameters

\Drupal\search_api\IndexInterface $search_api_index: The search index.

string $field_id: The ID of the field to remove.

Return value

\Symfony\Component\HttpFoundation\Response The response to send to the browser.

Throws

\Symfony\Component\HttpKernel\Exception\NotFoundHttpException Thrown when the field was not found.

1 string reference to 'IndexController::removeField'
search_api.routing.yml in ./search_api.routing.yml
search_api.routing.yml

File

src/Controller/IndexController.php, line 186

Class

IndexController
Provides route responses for search indexes.

Namespace

Drupal\search_api\Controller

Code

public function removeField(IndexInterface $search_api_index, $field_id) {
  $fields = $search_api_index
    ->getFields();
  $success = FALSE;
  if (isset($fields[$field_id])) {
    try {
      $search_api_index
        ->removeField($field_id);
      $search_api_index
        ->save();
      $success = TRUE;
    } catch (SearchApiException $e) {
      $args['%field'] = $fields[$field_id]
        ->getLabel();
      $this
        ->getMessenger()
        ->addError($this
        ->t('The field %field is locked and cannot be removed.', $args));
    }
  }
  else {
    throw new NotFoundHttpException();
  }

  // If this is an AJAX request, just remove the row in question.
  if ($success && $this
    ->getRequest()->request
    ->get(AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER)) {
    $response = new AjaxResponse();
    $response
      ->addCommand(new RemoveCommand("tr[data-field-row-id='{$field_id}']"));
    return $response;
  }

  // Redirect to the index's "Fields" page.
  $url = $search_api_index
    ->toUrl('fields');
  return $this
    ->redirect($url
    ->getRouteName(), $url
    ->getRouteParameters());
}