Mostrar IDs de nó junto com títulos na lista de preenchimento automático de referência de entidade


8

Gostaria de adicionar essa funcionalidade ao widget de preenchimento automático no campo Referência da entidade para mostrar o ID do nó ao lado dos títulos na lista suspensa. A razão por trás da ideia é diferenciar entre vários nós com o mesmo título.

Exemplo:

  • Este é um título (3)
  • Este é um título (2)
  • Este é um título (1)

Sei que o ID do nó é mostrado depois que uma seleção é feita, mas gosto de mostrá-lo na lista suspensa para escolher o nó certo rapidamente, com base no ID do nó.



@ oksana-c verifique minha resposta com outra maneira fácil #
Adrian Cid Almaguer

Respostas:


20

Instale os módulos Views e Entity Reference , crie uma nova View e adicione uma exibição de referência de entidade:

insira a descrição da imagem aqui

Em seguida, adicione nos campos o título do conteúdo e o nid, clique no nid e marque Excluir da exibição, Salvar e clique no título e reescreva a saída do título como [title] - ([nid])

insira a descrição da imagem aqui insira a descrição da imagem aqui

Vá para editar as configurações do formato e verifique o título, isso permitirá que você pesquise por título.

insira a descrição da imagem aqui

Salve a vista.

Vá para editar o campo Referência da entidade e selecione nas Visualizações de modo: .... (como na imagem a seguir) e selecione sua Visualização (nesse caso, o nome é: articles_with_id) e salve as configurações:

insira a descrição da imagem aqui

Então vá para ver o resultado:

insira a descrição da imagem aqui

EDIT: Agora está funcionando no Drupal 8, pelo menos na versão 8.3.4.


2
OMG, eu sempre me perguntei para que servem as opções de exibição. Isso é imundo !!!
No Sssweat,

11
@NoSssweat Estou aprendendo inglês agora, você pode me fornecer um sinônimo de imundo, por favor? Eu não consigo entender a frase "Isso é nojento"
Adrian Cid Almaguer

3
Não, isso significa que é uma solução realmente boa / impressionante. Ex: Objetivo Sujo de Tiroteio de Alexander Nylander
Sem Sssweat

11
@AdrianCidAlmaguer Concordo que esta solução está "doente"! (idiom)
John R

2
O único problema com esta solução é que o campo de referência da entidade, uma vez selecionado, mostra o ID duas vezes no formulário de edição da entidade, porque é incluído por padrão quando é selecionado.
Yuri

5

Campo Criar referência de entidade com a configuração padrão

insira a descrição da imagem aqui

A função entityreference_autocomplete_callback_get_matches determina qual deve ser a saída do preenchimento automático.

function entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
  $matches = array();

  $entity = NULL;
  if ($entity_id !== 'NULL') {
    $entity = entity_load_single($entity_type, $entity_id);
    $has_view_access = (entity_access('view', $entity_type, $entity) !== FALSE);
    $has_update_access = (entity_access('update', $entity_type, $entity) !== FALSE);
    if (!$entity || !($has_view_access || $has_update_access)) {
      return MENU_ACCESS_DENIED;
    }
  }

  $handler = entityreference_get_selection_handler($field, $instance, $entity_type, $entity);

  if ($type == 'tags') {
    // The user enters a comma-separated list of tags. We only autocomplete the last tag.
    $tags_typed = drupal_explode_tags($string);
    $tag_last = drupal_strtolower(array_pop($tags_typed));
    if (!empty($tag_last)) {
      $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
    }
  }
  else {
    // The user enters a single tag.
    $prefix = '';
    $tag_last = $string;
  }

  if (isset($tag_last)) {
    // Get an array of matching entities.
    $entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'], 10);

    // Loop through the products and convert them into autocomplete output.
    foreach ($entity_labels as $values) {
      foreach ($values as $entity_id => $label) {
        $key = "$label ($entity_id)";
        // Strip things like starting/trailing white spaces, line breaks and tags.
        $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
        // Names containing commas or quotes must be wrapped in quotes.
        if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
          $key = '"' . str_replace('"', '""', $key) . '"';
        }
        /* *** */$matches[$prefix . $key] = '<div class="reference-autocomplete">' . $label .' - ('. $entity_id . ')</div>';//****
      }
    }
  }
  drupal_json_output($matches);
}

a última linha $matches[$prefix . $key] = '<div class="reference-autocomplete">'determina a saída e $entity_idestá disponível qual é o ID. Você pode fazer o que fiz nessa linha (mostrada por **), basta escrever:

 $matches[$prefix . $key] = '<div class="reference-autocomplete">' . $label .' - ('. $entity_id . ')</div>';

você pode usar $entity_idpara buscar outros campos e o que quiser.

Mais uma coisa!

Algumas vezes, não é uma boa ideia alterar a função do módulo principal (se não for importante para você, a solução acima é suficiente).

Se você precisar substituir a função principal do entity_referencemódulo, crie um pequeno módulo e nomeie-oelabel

isto é elabel.info

;$Id;
name = My Entity Reference Label
description = This module creates special Entity Reference Label
package = My Modules
core = 7.x
php = 5.1
files[] = elabel.module

e isso é elabel.module

<?php function elabel_menu_alter(&$items){
    unset($items['entityreference/autocomplete/single/%/%/%']);
    unset($items['entityreference/autocomplete/tags/%/%/%']);

      $items['entityreference/autocomplete/single/%/%/%'] = array(
    'title' => 'Entity Reference Autocomplete',
    'page callback' => 'elabel_autocomplete_callback',
    'page arguments' => array(2, 3, 4, 5),
    'access callback' => 'entityreference_autocomplete_access_callback',
    'access arguments' => array(2, 3, 4, 5),
    'type' => MENU_CALLBACK,
  );

    $items['entityreference/autocomplete/tags/%/%/%'] = array(
    'title' => 'Entity Reference Autocomplete',
    'page callback' => 'elabel_autocomplete_callback',
    'page arguments' => array(2, 3, 4, 5),
    'access callback' => 'entityreference_autocomplete_access_callback',
    'access arguments' => array(2, 3, 4, 5),
    'type' => MENU_CALLBACK,
  );
  return $items;

}

function elabel_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $entity_id = '', $string = '') {
  // If the request has a '/' in the search text, then the menu system will have
  // split it into multiple arguments and $string will only be a partial. We want
  //  to make sure we recover the intended $string.
  $args = func_get_args();
  // Shift off the $type, $field_name, $entity_type, $bundle_name, and $entity_id args.
  array_shift($args);
  array_shift($args);
  array_shift($args);
  array_shift($args);
  array_shift($args);
  $string = implode('/', $args);

  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);

  return elabel_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string);
}

function elabel_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
  $matches = array();

  $entity = NULL;
  if ($entity_id !== 'NULL') {
    $entity = entity_load_single($entity_type, $entity_id);
    $has_view_access = (entity_access('view', $entity_type, $entity) !== FALSE);
    $has_update_access = (entity_access('update', $entity_type, $entity) !== FALSE);
    if (!$entity || !($has_view_access || $has_update_access)) {
      return MENU_ACCESS_DENIED;
    }
  }

  $handler = entityreference_get_selection_handler($field, $instance, $entity_type, $entity);

  if ($type == 'tags') {
    // The user enters a comma-separated list of tags. We only autocomplete the last tag.
    $tags_typed = drupal_explode_tags($string);
    $tag_last = drupal_strtolower(array_pop($tags_typed));
    if (!empty($tag_last)) {
      $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
    }
  }
  else {
    // The user enters a single tag.
    $prefix = '';
    $tag_last = $string;
  }

  if (isset($tag_last)) {
    // Get an array of matching entities.
    $entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'], 10);

    // Loop through the products and convert them into autocomplete output.
    foreach ($entity_labels as $values) {
      foreach ($values as $entity_id => $label) {
        $key = "$label ($entity_id)";
        // Strip things like starting/trailing white spaces, line breaks and tags.
        $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
        // Names containing commas or quotes must be wrapped in quotes.
        if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
          $key = '"' . str_replace('"', '""', $key) . '"';
        }
        /* *** */ $matches[$prefix . $key] = '<div class="reference-autocomplete">' . $label .'('.$entity_id.')' .'</div>';
      }
    }
  }

  drupal_json_output($matches);
}

Eu tentei esse código e ele funciona perfeitamente Se houver outro tipo de referência de entidade e você não precisar fazer isso por eles, basta adicionar uma IFinstrução e verificar o tipo de pacote ou conteúdo.

Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.