*/
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);
}
}
+ /**
+ * 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}
*/
// 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.
}
$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'] = [
return $values;
}
-
/**
* {@inheritdoc}
*