3 namespace Drupal\path\Plugin\Field\FieldWidget;
5 use Drupal\Core\Field\FieldItemListInterface;
6 use Drupal\Core\Field\WidgetBase;
7 use Drupal\Core\Form\FormStateInterface;
8 use Symfony\Component\Validator\ConstraintViolationInterface;
11 * Plugin implementation of the 'path' widget.
15 * label = @Translation("URL alias"),
21 class PathWidget extends WidgetBase {
26 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
27 $entity = $items->getEntity();
30 '#element_validate' => [[get_class($this), 'validateFormElement']],
33 '#type' => 'textfield',
34 '#title' => $element['#title'],
35 '#default_value' => $items[$delta]->alias,
36 '#required' => $element['#required'],
38 '#description' => $this->t('Specify an alternative path by which this data can be accessed. For example, type "/about" when writing an about page.'),
42 '#value' => $items[$delta]->pid,
44 $element['source'] = [
46 '#value' => !$entity->isNew() ? '/' . $entity->toUrl()->getInternalPath() : NULL,
48 $element['langcode'] = [
50 '#value' => $items[$delta]->langcode,
53 // If the advanced settings tabs-set is available (normally rendered in the
54 // second column on wide-resolutions), place the field as a details element
56 if (isset($form['advanced'])) {
59 '#title' => t('URL path settings'),
60 '#open' => !empty($items[$delta]->alias),
61 '#group' => 'advanced',
62 '#access' => $entity->get('path')->access('edit'),
64 'class' => ['path-form'],
67 'library' => ['path/drupal.path'],
70 $element['#weight'] = 30;
77 * Form element validation handler for URL alias form element.
79 * @param array $element
81 * @param \Drupal\Core\Form\FormStateInterface $form_state
84 public static function validateFormElement(array &$element, FormStateInterface $form_state) {
85 // Trim the submitted value of whitespace and slashes.
86 $alias = rtrim(trim($element['alias']['#value']), " \\/");
88 $form_state->setValueForElement($element['alias'], $alias);
90 // Validate that the submitted alias does not exist yet.
91 $is_exists = \Drupal::service('path.alias_storage')->aliasExists($alias, $element['langcode']['#value'], $element['source']['#value']);
93 $form_state->setError($element['alias'], t('The alias is already in use.'));
97 if ($alias && $alias[0] !== '/') {
98 $form_state->setError($element['alias'], t('The alias needs to start with a slash.'));
105 public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
106 return $element['alias'];