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",
21 * constraints = {"PathAlias" = {}},
24 class PathItem extends FieldItemBase {
29 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
30 $properties['alias'] = DataDefinition::create('string')
31 ->setLabel(t('Path alias'));
32 $properties['pid'] = DataDefinition::create('integer')
33 ->setLabel(t('Path id'));
34 $properties['langcode'] = DataDefinition::create('string')
35 ->setLabel(t('Language Code'));
42 public static function schema(FieldStorageDefinitionInterface $field_definition) {
49 public function isEmpty() {
50 return ($this->alias === NULL || $this->alias === '') && ($this->pid === NULL || $this->pid === '') && ($this->langcode === NULL || $this->langcode === '');
56 public function preSave() {
57 if ($this->alias !== NULL) {
58 $this->alias = trim($this->alias);
65 public function postSave($update) {
66 // If specified, rely on the langcode property for the language, so that the
67 // existing language of an alias can be kept. That could for example be
68 // unspecified even if the field/entity has a specific langcode.
69 $alias_langcode = ($this->langcode && $this->pid) ? $this->langcode : $this->getLangcode();
73 $entity = $this->getEntity();
74 if ($path = \Drupal::service('path.alias_storage')->save('/' . $entity->urlInfo()->getInternalPath(), $this->alias, $alias_langcode)) {
75 $this->pid = $path['pid'];
80 // Delete old alias if user erased it.
81 if ($this->pid && !$this->alias) {
82 \Drupal::service('path.alias_storage')->delete(['pid' => $this->pid]);
84 // Only save a non-empty alias.
85 elseif ($this->alias) {
86 $entity = $this->getEntity();
87 \Drupal::service('path.alias_storage')->save('/' . $entity->urlInfo()->getInternalPath(), $this->alias, $alias_langcode, $this->pid);
95 public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
96 $random = new Random();
97 $values['alias'] = '/' . str_replace(' ', '-', strtolower($random->sentences(3)));
104 public static function mainPropertyName() {