You are here

public function PasswordItem::preSave in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/PasswordItem.php \Drupal\Core\Field\Plugin\Field\FieldType\PasswordItem::preSave()
  2. 9 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/PasswordItem.php \Drupal\Core\Field\Plugin\Field\FieldType\PasswordItem::preSave()

Defines custom presave behavior for field values.

This method is called during the process of saving an entity, just before values are written into storage. When storing a new entity, its identifier will not be available yet. This should be used to massage item property values or perform any other operation that needs to happen before values are stored. For instance this is the proper phase to auto-create a new entity for an entity reference field item, because this way it will be possible to store the referenced entity identifier.

Overrides FieldItemBase::preSave

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldType/PasswordItem.php, line 40

Class

PasswordItem
Defines the 'password' entity field type.

Namespace

Drupal\Core\Field\Plugin\Field\FieldType

Code

public function preSave() {
  parent::preSave();
  $entity = $this
    ->getEntity();
  if ($this->pre_hashed) {

    // Reset the pre_hashed value since it has now been used.
    $this->pre_hashed = FALSE;
  }
  elseif (!$entity
    ->isNew() && empty($this->value)) {

    // If the password is empty, that means it was not changed, so use the
    // original password.
    $this->value = $entity->original->{$this
      ->getFieldDefinition()
      ->getName()}->value;
  }
  elseif ($entity
    ->isNew() || strlen(trim($this->value)) > 0 && $this->value != $entity->original->{$this
    ->getFieldDefinition()
    ->getName()}->value) {

    // Allow alternate password hashing schemes.
    $this->value = \Drupal::service('password')
      ->hash(trim($this->value));

    // Abort if the hashing failed and returned FALSE.
    if (!$this->value) {
      throw new EntityMalformedException('The entity does not have a password.');
    }
  }

  // Ensure that the existing password is unset to minimise risks of it
  // getting serialized and stored somewhere.
  $this->existing = NULL;
}