3 namespace Drupal\path\Plugin\Field\FieldType;
5 use Drupal\Component\Utility\Random;
6 use Drupal\Core\Field\FieldDefinitionInterface;
7 use Drupal\Core\Field\FieldStorageDefinitionInterface;
8 use Drupal\Core\Field\FieldItemBase;
9 use Drupal\Core\TypedData\DataDefinition;
12 * Defines the 'path' entity field type.
16 * label = @Translation("Path"),
17 * description = @Translation("An entity field containing a path alias and related data."),
19 * default_widget = "path",
20 * list_class = "\Drupal\path\Plugin\Field\FieldType\PathFieldItemList"
23 class PathItem extends FieldItemBase {
28 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
29 $properties['alias'] = DataDefinition::create('string')
30 ->setLabel(t('Path alias'));
31 $properties['pid'] = DataDefinition::create('integer')
32 ->setLabel(t('Path id'));
39 public static function schema(FieldStorageDefinitionInterface $field_definition) {
46 public function preSave() {
47 $this->alias = trim($this->alias);
53 public function postSave($update) {
56 $entity = $this->getEntity();
57 if ($path = \Drupal::service('path.alias_storage')->save('/' . $entity->urlInfo()->getInternalPath(), $this->alias, $this->getLangcode())) {
58 $this->pid = $path['pid'];
63 // Delete old alias if user erased it.
64 if ($this->pid && !$this->alias) {
65 \Drupal::service('path.alias_storage')->delete(['pid' => $this->pid]);
67 // Only save a non-empty alias.
68 elseif ($this->alias) {
69 $entity = $this->getEntity();
70 \Drupal::service('path.alias_storage')->save('/' . $entity->urlInfo()->getInternalPath(), $this->alias, $this->getLangcode(), $this->pid);
78 public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
79 $random = new Random();
80 $values['alias'] = str_replace(' ', '-', strtolower($random->sentences(3)));
87 public static function mainPropertyName() {