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,
56 * Form element validation handler for URL alias form element.
58 * @param array $element
60 * @param \Drupal\Core\Form\FormStateInterface $form_state
63 public static function validateFormElement(array &$element, FormStateInterface $form_state) {
64 // Trim the submitted value of whitespace and slashes.
65 $alias = rtrim(trim($element['alias']['#value']), " \\/");
67 $form_state->setValueForElement($element['alias'], $alias);
69 // Validate that the submitted alias does not exist yet.
70 $is_exists = \Drupal::service('path.alias_storage')->aliasExists($alias, $element['langcode']['#value'], $element['source']['#value']);
72 $form_state->setError($element['alias'], t('The alias is already in use.'));
76 if ($alias && $alias[0] !== '/') {
77 $form_state->setError($element['alias'], t('The alias needs to start with a slash.'));
84 public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
85 return $element['alias'];