Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / link / src / Plugin / Field / FieldWidget / LinkWidget.php
index 56f65218e5aca68269702df5fa85260139ba8a1a..ee3b77dad6f90b607b85942170e4a12c09b56695 100644 (file)
@@ -101,7 +101,7 @@ class LinkWidget extends WidgetBase {
    */
   protected static function getUserEnteredStringAsUri($string) {
     // By default, assume the entered string is an URI.
-    $uri = $string;
+    $uri = trim($string);
 
     // Detect entity autocomplete string, map to 'entity:' URI.
     $entity_id = EntityAutocomplete::extractEntityIdFromAutocompleteInput($string);
@@ -157,6 +157,17 @@ class LinkWidget extends WidgetBase {
     }
   }
 
+  /**
+   * Form element validation handler for the 'title' element.
+   *
+   * Requires the URL value if a link title was filled in.
+   */
+  public static function validateTitleNoLink(&$element, FormStateInterface $form_state, $form) {
+    if ($element['uri']['#value'] === '' && $element['title']['#value'] !== '') {
+      $form_state->setError($element['uri'], t('The @uri field is required when the @title field is specified.', ['@title' => $element['title']['#title'], '@uri' => $element['uri']['#title']]));
+    }
+  }
+
   /**
    * {@inheritdoc}
    */
@@ -222,8 +233,12 @@ class LinkWidget extends WidgetBase {
     // Post-process the title field to make it conditionally required if URL is
     // non-empty. Omit the validation on the field edit form, since the field
     // settings cannot be saved otherwise.
+    //
+    // Validate that title field is filled out (regardless of uri) when it is a
+    // required field.
     if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') === DRUPAL_REQUIRED) {
       $element['#element_validate'][] = [get_called_class(), 'validateTitleElement'];
+      $element['#element_validate'][] = [get_called_class(), 'validateTitleNoLink'];
 
       if (!$element['title']['#required']) {
         // Make title required on the front-end when URI filled-in.
@@ -237,11 +252,17 @@ class LinkWidget extends WidgetBase {
         }
 
         $element['title']['#states']['required'] = [
-          ':input[name="' . $selector . '[' . $delta . '][uri]"]' => ['filled' => TRUE]
+          ':input[name="' . $selector . '[' . $delta . '][uri]"]' => ['filled' => TRUE],
         ];
       }
     }
 
+    // Ensure that a URI is always entered when an optional title field is
+    // submitted.
+    if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') == DRUPAL_OPTIONAL) {
+      $element['#element_validate'][] = [get_called_class(), 'validateTitleNoLink'];
+    }
+
     // Exposing the attributes array in the widget is left for alternate and more
     // advanced field widgets.
     $element['attributes'] = [
@@ -377,7 +398,6 @@ class LinkWidget extends WidgetBase {
     return $values;
   }
 
-
   /**
    * {@inheritdoc}
    *