1

The LinkWidget uses a URL render element, which behaves differently in different browsers. In chrome, there is annoying pop-up, which is out of character with other validation within Drupal where there is an error message at the top of the page and a red border added to the form element.

In order to gain more control over the validation, I'd like to do away with the javascript (i.e. HTML 5) validation. There are various suggestions using javascript or CSS, but they are heavy handed as the most effective method is to set the "novalidate" parameter on the entire form, which loses the benefit of validation on other html 5 elements such as email or dates.

What is a good way to turn this off for link fields that are set to accept external links? (If you also accept internal links, this doesn't happen).

1 Answer 1

2

One way to do this is to simple not use the URL render element. You can still use its validation, but you replace the URL element with a textfield element.

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getType() == 'link') {
    $settings = $context['items']->getFieldDefinition()->getSettings();
    // If external link, don't use HTML5 URL element, to prevent its annoying
    // pop-ups.  Use a textfield with the backend validation from the URL element.
    if (!empty($settings['link_type']) && $settings['link_type'] == 16) {
      $element['uri']['#type'] = 'textfield';
      array_unshift($element['uri']['#element_validate'], ['Drupal\Core\Render\Element\Url', 'validateUrl']);
    }
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.