5 * Contains \Drupal\linkit\Element\Linkit.
8 namespace Drupal\linkit\Element;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\BubbleableMetadata;
12 use Drupal\Core\Render\Element;
13 use Drupal\Core\Render\Element\FormElement;
14 use Drupal\Core\Render\Element\Textfield;
18 * Provides a form element for linkit.
20 * @FormElement("linkit")
22 class Linkit extends FormElement {
27 public function getInfo() {
28 $class = get_class($this);
33 array($class, 'processLinkitAutocomplete'),
34 array($class, 'processGroup'),
36 '#pre_render' => array(
37 array($class, 'preRenderLinkitElement'),
38 array($class, 'preRenderGroup'),
40 '#theme' => 'input__textfield',
41 '#theme_wrappers' => array('form_element'),
48 public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
49 return Textfield::valueCallback($element, $input, $form_state);
53 * Adds linkit custom autocomplete functionality to elements.
55 * Instead of using the core autocomplete, we use our own.
59 * @see \Drupal\Core\Render\Element\FormElement::processAutocomplete
61 public static function processLinkitAutocomplete(&$element, FormStateInterface $form_state, &$complete_form) {
65 if (!empty($element['#autocomplete_route_name'])) {
66 $parameters = isset($element['#autocomplete_route_parameters']) ? $element['#autocomplete_route_parameters'] : array();
67 $url = Url::fromRoute($element['#autocomplete_route_name'], $parameters)->toString(TRUE);
68 /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
69 $access_manager = \Drupal::service('access_manager');
70 $access = $access_manager->checkNamedRoute($element['#autocomplete_route_name'], $parameters, \Drupal::currentUser(), TRUE);
74 $metadata = BubbleableMetadata::createFromRenderArray($element);
75 if ($access->isAllowed()) {
76 $element['#attributes']['class'][] = 'form-linkit-autocomplete';
77 $metadata->addAttachments(['library' => ['linkit/linkit.autocomplete']]);
78 // Provide a data attribute for the JavaScript behavior to bind to.
79 $element['#attributes']['data-autocomplete-path'] = $url->getGeneratedUrl();
80 $metadata = $metadata->merge($url);
83 ->merge(BubbleableMetadata::createFromObject($access))
91 * Prepares a #type 'linkit' render element for input.html.twig.
93 * @param array $element
94 * An associative array containing the properties of the element.
95 * Properties used: #title, #value, #description, #size, #attributes.
98 * The $element with prepared variables ready for input.html.twig.
100 public static function preRenderLinkitElement($element) {
101 $element['#attributes']['type'] = 'text';
102 Element::setAttributes($element, array('id', 'name', 'value', 'size'));
103 static::setAttributes($element, array('form-text'));