PathItem.php 2.22 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\path\Plugin\Field\FieldType\PathItem.
6 7
 */

8
namespace Drupal\path\Plugin\Field\FieldType;
9

10
use Drupal\Core\Field\FieldDefinitionInterface;
11
use Drupal\Core\Field\FieldItemBase;
12
use Drupal\Core\TypedData\DataDefinition;
13 14

/**
15
 * Defines the 'path' entity field type.
16
 *
17 18 19
 * @FieldType(
 *   id = "path",
 *   label = @Translation("Path"),
20
 *   description = @Translation("An entity field containing a path alias and related data."),
21
 *   no_ui = TRUE
22
 * )
23 24 25 26
 */
class PathItem extends FieldItemBase {

  /**
27
   * {@inheritdoc}
28
   */
29 30
  public static function propertyDefinitions(FieldDefinitionInterface $field_definition) {
    $properties['alias'] = DataDefinition::create('string')
31
        ->setLabel(t('Path alias'));
32
    $properties['pid'] = DataDefinition::create('string')
33
        ->setLabel(t('Path id'));
34
    return $properties;
35 36
  }

37 38 39 40 41 42 43
  /**
   * {@inheritdoc}
   */
  public static function schema(FieldDefinitionInterface $field_definition) {
    return array();
  }

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
  /**
   * {@inheritdoc}
   */
  public function preSave() {
    $this->alias = trim($this->alias);
  }

  /**
   * {@inheritdoc}
   */
  public function insert() {
    if ($this->alias) {
      $entity = $this->getEntity();

      // Ensure fields for programmatic executions.
      $langcode = $entity->language()->id;

      if ($path = \Drupal::service('path.crud')->save($entity->getSystemPath(), $this->alias, $langcode)) {
        $this->pid = $path['pid'];
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function update() {
    // Delete old alias if user erased it.
    if ($this->pid && !$this->alias) {
      \Drupal::service('path.crud')->delete(array('pid' => $this->pid));
    }
    // Only save a non-empty alias.
    elseif ($this->alias) {
      $entity = $this->getEntity();

      // Ensure fields for programmatic executions.
      $langcode = $entity->language()->id;

      \Drupal::service('path.crud')->save($entity->getSystemPath(), $this->alias, $langcode, $this->pid);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function delete() {
    // Delete all aliases associated with this entity.
    $entity = $this->getEntity();
    \Drupal::service('path.crud')->delete(array('source' => $entity->getSystemPath()));
  }

95
}