function PathItem::postSave

Same name in other branches
  1. 8.9.x core/modules/path/src/Plugin/Field/FieldType/PathItem.php \Drupal\path\Plugin\Field\FieldType\PathItem::postSave()
  2. 10 core/modules/path/src/Plugin/Field/FieldType/PathItem.php \Drupal\path\Plugin\Field\FieldType\PathItem::postSave()
  3. 11.x core/modules/path/src/Plugin/Field/FieldType/PathItem.php \Drupal\path\Plugin\Field\FieldType\PathItem::postSave()

Overrides FieldItemBase::postSave

File

core/modules/path/src/Plugin/Field/FieldType/PathItem.php, line 65

Class

PathItem
Defines the 'path' entity field type.

Namespace

Drupal\path\Plugin\Field\FieldType

Code

public function postSave($update) {
    $path_alias_storage = \Drupal::entityTypeManager()->getStorage('path_alias');
    $entity = $this->getEntity();
    // If specified, rely on the langcode property for the language, so that the
    // existing language of an alias can be kept. That could for example be
    // unspecified even if the field/entity has a specific langcode.
    $alias_langcode = $this->langcode && $this->pid ? $this->langcode : $this->getLangcode();
    // If we have an alias, we need to create or update a path alias entity.
    if ($this->alias) {
        if (!$update || !$this->pid) {
            $path_alias = $path_alias_storage->create([
                'path' => '/' . $entity->toUrl()
                    ->getInternalPath(),
                'alias' => $this->alias,
                'langcode' => $alias_langcode,
            ]);
            $path_alias->save();
            $this->pid = $path_alias->id();
        }
        elseif ($this->pid) {
            $path_alias = $path_alias_storage->load($this->pid);
            if ($this->alias != $path_alias->getAlias()) {
                $path_alias->setAlias($this->alias);
                $path_alias->save();
            }
        }
    }
    elseif ($this->pid && !$this->alias) {
        // Otherwise, delete the old alias if the user erased it.
        $path_alias = $path_alias_storage->load($this->pid);
        if ($entity->isDefaultRevision()) {
            $path_alias_storage->delete([
                $path_alias,
            ]);
        }
        else {
            $path_alias_storage->deleteRevision($path_alias->getRevisionID());
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.