---
url: 'https://metadrop.net/es/articulos/search-api-crear-campos-personalizados-usando-procesadores-en-drupal-8'
title: 'Search API - Crear campos personalizados usando procesadores en Drupal 8'
author: 'Agustin Gómez'
date: '2017-01-17T09:38:50+00:00'
updated: '2026-09-02T08:06:11+00:00'
type: article
summary: 'El módulo de Search API permite una solución rápida y completa de búsqueda para tu web, pero hay algunos casos en los que queremos modificar el comportamiento de los elementos a inidexar.'
tags:
  - 'Drupal 8'
  - 'Search API (Drupal module)'
  - Solr
image: 'https://metadrop.net/sites/default/files/styles/full/public/article/image/seach-api-architecture-overview.png.webp?itok=zbY6Tj2y'
published: true
og:
  determiner: Automatic
  site_name: Metadrop
  'image:url': 'https://metadrop.net/sites/default/files/styles/full/public/article/image/seach-api-architecture-overview.png.webp?itok=zbY6Tj2y'
  'image:type': image/png
  'image:width': '563'
  'image:height': '441'
  'image:alt': 'Search API - Crear campos personalizados usando procesadores en Drupal 8'
  street_address: 'Calle Manuel Luna, 12, 3 Dcha'
  locality: Madrid
  region: Madrid
  postal_code: '28020'
  country_name: España
  email: hola@metadrop.net
  phone_number: '910053180'
schema:
  '@context': 'https://schema.org'
  '@graph':
    -
      '@type': Article
      '@id': 'https://metadrop.net/es/articulos/search-api-crear-campos-personalizados-usando-procesadores-en-drupal-8#article'
      name: 'Search API - Crear campos personalizados usando procesadores en Drupal 8'
      headline: 'Search API - Crear campos personalizados usando procesadores en Drupal 8'
      description: "El módulo de Search API\_permite una solución rápida y completa de búsqueda para tu web, pero hay algunos casos en los que queremos modificar el comportamiento de los elementos a inidexar."
      about:
        - 'Drupal 8'
        - 'Search API (módulo de Drupal)'
        - Solr
      image:
        '@type': ImageObject
        url: 'https://metadrop.net/sites/default/files/styles/full/public/article/image/seach-api-architecture-overview.png.webp?itok=zbY6Tj2y'
        width: '563'
        height: '441'
      datePublished: '2017-01-01T00:00:00+0100'
      dateModified: '2026-09-02T10:06:11+0200'
      author:
        '@type': Person
        name: 'Agustin Gómez'
      publisher:
        '@type': Organization
        '@id': 'https://metadrop.net/#organization'
      mainEntityOfPage: 'https://metadrop.net/es/articulos/search-api-crear-campos-personalizados-usando-procesadores-en-drupal-8'
    -
      '@type': Organization
      '@id': 'https://metadrop.net/#organization'
      url: 'https://metadrop.net/'
      name: Metadrop
      sameAs:
        - 'https://www.drupal.org/metadrop'
        - 'https://twitter.com/metadrop'
        - 'https://asociaciondrupal.es/partner/metadrop'
        - 'https://www.linkedin.com/company/metadrop'
      logo:
        '@type': ImageObject
        url: 'https://metadrop.net/themes/custom/mdrop_radix/logo-metadrop-500-500.jpg'
        width: '500'
        height: '500'
    -
      '@type': ItemPage
      '@id': 'https://metadrop.net/es/articulos/search-api-crear-campos-personalizados-usando-procesadores-en-drupal-8'
      breadcrumb:
        '@type': BreadcrumbList
        itemListElement:
          -
            '@type': ListItem
            position: 1
            name: Inicio
            item: 'https://metadrop.net/es'
          -
            '@type': ListItem
            position: 2
            name: 'Artículos expertos sobre Drupal y tecnología'
            item: 'https://metadrop.net/es/articulos'
      publisher:
        '@type': Organization
        '@id': 'https://metadrop.net/#organization'
---
 1. [Artículos](https://metadrop.net/es/articulos)
 
  

# Search API - Crear campos personalizados usando procesadores en Drupal 8

Domingo 01 de Enero de 2017

 

 



El módulo de [Search API](https://www.drupal.org/project/search_api) permite una solución rápida y completa de búsqueda para tu web, pero hay algunos casos en los que queremos modificar el comportamiento de los elementos a inidexar.



   



## Resumen

El módulo de [Search API](https://www.drupal.org/project/search_api) permite una solución rápida y completa de búsqueda para tu web, pero hay algunos casos en los que queremos modificar el comportamiento de los elementos a inidexar.

## Escenario

Usamos el módulo Search API junto con el backend de [Search API Solr](https://www.drupal.org/project/search_api_solr).

Pongamos, por ejemplo, que tenemos un tipo de contenido llamado "Expediente". Este tipo de contenido tiene un campo (entity reference) apuntando a una entidad personalizada de la que queremos indexar y buscar algunos de sus metadatos. Probablemente tengamos varias soluciones para este caso pero nosotros vamos a usar un "Processor" personalizado para alcanzar nuestro objetivo.

## Ejemplo

En este ejemplo vamos a crear un Plugin processor basándonos en dos que ya existen: AddURL y AggregatedFields.

Seguiremos estos tres pasos:

1. **alterPropertyDefinitions**: Definimos (creamos) tres campos personalizados de diferente tipo.
2. **preprocessIndexItems**: Usamos estos tres campos dependiendo de ciertas condiciones "personalizadas".
3. **preIndexSave**: Hacemos saber al índice que existen estos tres campos, de ta forma que los podremos usar como si fueran un campo más del tipo de contenido (como puede ser el nid).

## Código

Puedes ver un [snippet](https://bitbucket.org/snippets/metadrop/aKrzK) actualizado y ver más información en la [documentación de la comunidad de drupal](https://www.drupal.org/node/2715959).

### 1. alterPropertyDefinitions()

Definiremos nestros campos con una *etiqueta*, *descripción* y *tipo*. Necesitamos definirlos si queremos usarlos después.

```php
<?php
/**
 * @file
 * Contains \Drupal\MY_MODULE\Plugin\search_api\processor\AddCustomField.
 *
 * A proccesor example that adds some custom fields.
 * 
 * @NOTE 
 *   - Replace any occurrences of MY_MODULE with your module machine_name.
 *   - Name this file AddCustomField.php and place it in the correct folder.
 *
 * @TODO Make some tests.
 */
namespace Drupal\MY_MODULE\Plugin\search_api\processor;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
/**
 * @SearchApiProcessor(
 *   id = "MY_MODULE_add_custom_field",
 *   label = @Translation("Custom field examples"),
 *   description = @Translation("Adds custom field examples."),
 *   stages = {
 *     "pre_index_save" = -10,
 *     "preprocess_index" = -30
 *   }
 * )
 */
class AddCustomField extends ProcessorPluginBase {
  /**
   * {@inheritdoc}
   *
   */
  public function alterPropertyDefinitions(array &$properties, DatasourceInterface $datasource = NULL) {
    // These fields will not have a Data source associated to them.
    if ($datasource) {
      return;
    }
    // Ensure that our fields are defined.
    $fields = $this->getFieldsDefinition();
    foreach ($fields as $field_id => $field_definition) {
      $properties[$field_id] = new DataDefinition($field_definition);
    }
  }
  /**
   * Helper function for defining our custom fields.
   */
  protected function getFieldsDefinition() {
    $fields['MY_MODULE_field_based_on_nid'] = array(
      'label' => 'Custom field based on nid',
      'description' => 'I will be used to make a text type field with an id if "nid" field exists.',
      'type' => 'text',
      'prefix' => 't', // For Solr fields I think it is ok.
    );
    $fields['MY_MODULE_field_active_standby'] = array(
      'label' => 'Custom field always added, could be used for facets',
      'description' => 'Custom field 2 of type string will be always added with values active/standby.',
      'type' => 'string',
      'prefix' => 's', // For Solr fields I think it is ok.
    );
    $fields['MY_MODULE_field_date_experiment'] = array(
      'label' => 'Custom field of date type, always added',
      'description' => 'I will be added as a time(), but it will be indexed differently.',
      'type' => 'date',
      'prefix' => 'd', // For Solr fields I think it is ok.
    );
    return $fields;
  }
}
```

### 2. preprocessIndexItems()

Aquí establecemos nuestra lógica de negocio poniendo nuestras condiciones para indexar los campos y sus valores.

```php
<?php
  /**
   * {@inheritdoc}
   */
  public function preprocessIndexItems(array &$items) {
    foreach ($items as $item) {
      // First custom field will only be added if we are indexing "nid" field.
      // Note that here we could check a "field_reference" (instead of the nid) to get an Id, pull data from that referenced entity
      // and add the proper values.
      foreach ($this->filterForPropertyPath($item->getFields(), 'nid') as $field_reference) {
        foreach ($this->filterForPropertyPath($item->getFields(), 'MY_MODULE_field_based_on_nid') as $nid_based_field) {
          $nid_based_field->addValue('Node Id: ' . reset($field_reference->getValues()));
        }
      }
      // We will add always this custom field, with random value.
      foreach ($this->filterForPropertyPath($item->getFields(), 'MY_MODULE_field_active_standby') as $always_added_field) {
        $active_standby = rand(0,1) ? 'active' : 'standby';
        $always_added_field->addValue($active_standby);
      }
      // We will add a time() and see how it is indexed.
      foreach ($this->filterForPropertyPath($item->getFields(), 'MY_MODULE_field_date_experiment') as $date_experiment_field) {
        $date_experiment_field->addValue(time());
      }
    }
  }
```

### 3. preIndexSave()

Guardaremos en el índice los campos de tal forma que estarán disponibles "mágicamente" en en la interfaz del usuario.

Hay que tener en cuenta que si pasamos un "tipo" en el tercer parámetro a la función *ensureField(), é*ste quedará bloqueado en la interfaz del usuario.

```php
<?php
  /**
   * {@inheritdoc}
   *
   */
  public function preIndexSave() {
    foreach ($this->getFieldsDefinition() as $field_id => $field_definition) {
      // We can specify or not a type in the 3rd parameter.
      // If you don't specify the type, the user will be able to change it through
      // the user interface (could be very useful), but if you specify it, the user won't
      // be able to alter the type.
      $this->ensureField(NULL, $field_id, $field_definition['type']);
    }
  }
```



[Drupal 8](https://metadrop.net/es/articulos?text=Drupal%208)

[Search API (módulo de Drupal)](https://metadrop.net/es/articulos?text=Search%20API%20%28m%C3%B3dulo%20de%20Drupal%29)

[Solr](https://metadrop.net/es/articulos?text=Solr)