Chris 2pha Brown

Chris Brown

Drupal, Javascript, Three.js, 3D

website blog

Removing the entity ID from Drupal entity reference fields

On a site I am currently working on I have a content type that includes an entity reference field. When creating a node, the entity reference autocomplete includes the entity id in the field after selecting the entity desired. This can be confusing for the user.
When trying to find a solution to this problem I came across many issues and different proposed solutions including a sandbox module called Entity reference trim.

I tried the entity reference trim module but it has problems when the form was submitted and had errors.
Taking a closer look into this module I could see that it was altering the widget (adding a hidden field) and overriding some of the core Drupal js to do with the autocomplete functionality. While poking around the autocomplete javascript I noticed that the autocomplete fires a 'autocompleteValue' event.
Using this event I could change the entity reference field value and store it, then change it back when the form is submitted.

Below is the code that I am using but be aware that I have not yet tested it extensively and not tested it with multiple entity reference fields. Also, as the event bubbles, a more generic version could probably be coded.

NOTE: you will have to change the jQuery selector and this code will need to be changed to work for multivalue fields.

(function ($) {
  Drupal.behaviors.damnId = {
      attach: function (context, settings){
        // Get the entity reference input
        $eref = $('#edit-field-postcode-suburb-und-0-target-id', context);
        if($eref.val()){
          // If field has value on page load, change it.
          var val = $eref.val();
          var match = val.match(/\((.*?)\)$/);
          $eref.data('real-value', val);
          $eref.val(val.replace(match[0], ''));
        }
        // Listen for the autocompleteSelect event
        $eref.once().on('autocompleteSelect', function(e, node){
          var val = $(node).data('autocompleteValue');
          var match = val.match(/\((.*?)\)$/);
          // Put the value with id into data storage
          $eref.data('real-value', val);
          // Set the value without the id
          $eref.val(val.replace(match[0], ''));
        }).closest('form').submit(function(e){
          // On form submit, set the value back to the stored value with id
          $eref.val($eref.data('real-value'));
        });
      }
  };
})(jQuery);