Skip to content
This repository was archived by the owner on Mar 7, 2024. It is now read-only.

Normal autocomplete fields and not showing entity id #1

Open
wants to merge 2 commits into
base: 8.x-2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 32 additions & 13 deletions js/select2.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,24 @@
(function ($) {

Drupal.behaviors.select2 = {
attach: function (context, settings) {
attach: function (context, drupalSettings) {
// Taxonomy tagging widget.
$('[data-select2-taxonomy-widget]').once().each(function () {
var url = $(this).data('autocomplete-path');
$(this).select2({
tokenSeparators: [","],
tags: [],
multiple: true,
$('[data-select2-field-name]').once().each(function () {
var fieldName = $(this).data('select2-field-name'),
settings = drupalSettings.select2[fieldName],
url = $(this).data('autocomplete-path');

var opts = {
tokenSeparators: settings.token_separator,
multiple: settings.multiple
};
// Do not add tags to settings, as soon as it is added, select2 enables it
// ignoring the value
if (settings.tags) {
opts.tags = settings.tags;
}

$(this).select2($.extend(opts, {
width: 'element',
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
Expand All @@ -27,13 +37,13 @@
data: function (term, page) {
return {
q: term
}
};
},
results: function (data, page) {
// map keys from taxonomy to select2
var res = [];
$.each(data, function (key, val) {
res.push({'id': val.value, 'text': val.value});
res.push({'id': val.value, 'text': settings.display_id ? val.value : val.label});
});
var more = (page * 10) < data.length; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
Expand All @@ -44,12 +54,21 @@
var data = [];
// @todo Needs testing, this does not seem to work anymore.
$(element.val().split(",")).each(function () {
var value = this.trim();
data.push({id: value, text: value});
var value = this.trim(),
match = value.match(/^(.*) \((\d+)\)$/);
if (!settings.display_id && match) {
data.push({id: value, text: match[1]});
}
else {
data.push({id: value, text: value});
}
});
if (!settings.multiple) {
data = data.shift();
}
callback(data);
}
});
}));
});

// @todo merge both widget configurations; the only difference should be
Expand Down Expand Up @@ -84,7 +103,7 @@
return {
q: term,
page: page
}
};
},
results: function (data, page) {
// map keys from taxonomy to select2
Expand Down
1 change: 0 additions & 1 deletion select2.libraries.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ select2:
js/vendor/select2/select2.css: {}
js:
js/vendor/select2/select2.min.js: {}
js/vendor/select2/select2_locale_de.js: {}
dependencies:
- core/jquery

Expand Down
23 changes: 1 addition & 22 deletions src/Plugin/Field/FieldWidget/Select2AutocompleteTagsWidget.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@

namespace Drupal\select2\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteTagsWidget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\entity_reference\Plugin\Field\FieldWidget\AutocompleteTagsWidget;
use Drupal\user\EntityOwnerInterface;

/**
* Plugin implementation of the 'entity_reference autocomplete-tags' widget.
Expand All @@ -27,23 +23,6 @@
*/
class Select2AutocompleteTagsWidget extends EntityReferenceAutocompleteTagsWidget {

/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$element['target_id'] += [
'#attributes' => [
'data-select2-taxonomy-widget' => 'true',
// Disable core autocomplete
'data-jquery-once-autocomplete' => 'true',
'class' => [
'select2-widget',
],
],
];
$element['target_id']['#attached']['library'][] = 'select2/select2.widget';
return $element;
}
use Select2AutocompleteTrait;

}
75 changes: 75 additions & 0 deletions src/Plugin/Field/FieldWidget/Select2AutocompleteTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

namespace Drupal\select2\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;

trait Select2AutocompleteTrait {

/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$fieldDefinition = $this->fieldDefinition;
$allow_multiple_values = $this->getPluginDefinition()['multiple_values'];
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$element['target_id'] += [
'#attributes' => [
'data-select2-field-name' => $fieldDefinition->getName(),
// Disable core autocomplete
'data-jquery-once-autocomplete' => 'true',
'class' => [
'select2-widget',
],
],
];
$element['target_id']['#attached']['library'][] = 'select2/select2.widget';
$element['target_id']['#attached']['drupalSettings']['select2'] = array(
$fieldDefinition->getName() => array(
'multiple' => $allow_multiple_values,
'display_id' => $this->getSetting('display_id'),
'token_separator' => $allow_multiple_values ? array(',') : null,
'tags' => $allow_multiple_values,
),
);
return $element;
}

/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);

$form['display_id'] = [
'#type' => 'checkbox',
'#title' => t('Display Entity ID in parentheses behind the name'),
'#default_value' => $this->getSetting('display_id'),
];

return $form;
}

/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'display_id' => TRUE,
] + parent::defaultSettings();
}

/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($this->getSetting('display_id') == FALSE) {
$summary[] = t("Don't show entity IDs in parentheses");
}
return $summary;
}


}
28 changes: 28 additions & 0 deletions src/Plugin/Field/FieldWidget/Select2AutocompleteWidget.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php
/**
* @file
* Contains \Drupal\select2\Entity\FieldWidget\AutocompleteWidget.
*/

namespace Drupal\select2\Plugin\Field\FieldWidget;

use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;

/**
* Plugin implementation of the 'entity_reference autocomplete-tags' widget.
*
* @FieldWidget(
* id = "select2_autocomplete",
* label = @Translation("Autocomplete (Select2)"),
* description = @Translation("An autocomplete text field."),
* field_types = {
* "entity_reference"
* },
* multiple_values = FALSE
* )
*/
class Select2AutocompleteWidget extends EntityReferenceAutocompleteWidget {

use Select2AutocompleteTrait;

}