View source
<?php
namespace Drupal\synonyms\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
class EntityReferenceSynonymsAutocomplete extends WidgetBase {
public static function defaultSettings() {
return [
'suggestion_size' => 10,
'suggest_only_unique' => FALSE,
'match' => 'CONTAINS',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['suggestion_size'] = [
'#type' => 'textfield',
'#title' => $this
->t('Suggestions Size'),
'#description' => $this
->t('Please, enter how many suggested entities to show in the autocomplete textfield.'),
'#required' => TRUE,
'#default_value' => $this
->getSetting('suggestion_size'),
];
$elements['suggest_only_unique'] = [
'#type' => 'checkbox',
'#title' => t('Suggest only one entry per entity'),
'#description' => t('If you want to include only name or a single synonym, suggesting a particular entity, while disregarding all ongoing ones, please, tick this checkbox on.'),
'#default_value' => $this
->getSetting('suggest_only_unique'),
];
$elements['match'] = [
'#type' => 'radios',
'#title' => $this
->t('Match operator'),
'#description' => $this
->t('Choose how to match the keyword against existing data.'),
'#options' => $this
->getMatchOperatorOptions(),
'#default_value' => $this
->getSetting('match'),
'#required' => TRUE,
];
return $elements;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
$summary[] = $this
->t('Suggestion size: @size', [
'@size' => $this
->getSetting('suggestion_size'),
]);
$summary[] = $this
->t('Only unique: @unique', [
'@unique' => $this
->getSetting('suggest_only_unique') ? $this
->t('Yes') : $this
->t('No'),
]);
$summary[] = $this
->t('Match: @match', [
'@match' => $this
->getMatchOperatorOptions()[$this
->getSetting('match')],
]);
return $summary;
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$default_value = [];
foreach ($items as $item) {
if ($item->entity) {
$default_value[] = $item->entity;
}
}
$handler_settings = $this->fieldDefinition
->getSetting('handler_settings') ?: [];
$target_bundles = isset($handler_settings['target_bundles']) ? $handler_settings['target_bundles'] : NULL;
$element += [
'#type' => 'synonyms_entity_autocomplete',
'#target_type' => $this
->getFieldSetting('target_type'),
'#target_bundles' => $target_bundles,
'#suggestion_size' => $this
->getSetting('suggestion_size'),
'#suggest_only_unique' => $this
->getSetting('suggest_only_unique'),
'#validate_reference' => FALSE,
'#maxlength' => 1024,
'#match' => $this
->getSetting('match'),
'#default_value' => $default_value,
];
return $element;
}
protected function getMatchOperatorOptions() {
return [
'STARTS_WITH' => t('Starts with'),
'CONTAINS' => t('Contains'),
];
}
}