username-1.0.x-dev/modules/username_phone/src/Entity/UsernamePhoneUser.php
modules/username_phone/src/Entity/UsernamePhoneUser.php
<?php
namespace Drupal\username_phone\Entity;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\Entity\User as BaseUser;
/**
* A custom username phone class for the User entity.
*
* This class extends the default User entity to add a phone field.
*/
class UsernamePhoneUser extends BaseUser {
/**
* Gets the phone number of the user.
*
* @return string
* The phone number of the user.
*/
public function getPhone() {
return $this->get('phone')->value;
}
/**
* Sets the phone number of the user.
*
* @param string $phone
* The phone number to set.
*
* @return $this
* The current object.
*/
public function setPhone($phone) {
$this->get('phone')->value = $phone;
return $this;
}
/**
* Defines base fields for the User entity.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
*
* @return \Drupal\Core\Field\BaseFieldDefinition[]
* An array of base field definitions.
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
/** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
$fields = parent::baseFieldDefinitions($entity_type);
// Define the phone field for the user entity.
$fields['phone'] = BaseFieldDefinition::create('string')
->setLabel(t('Phone number'))
->setDescription(t('The phone number of this user.'))
->setDefaultValue('')
// Ensure phone number is unique.
->addConstraint('UsernamePhoneUnique')
// Ensure phone number is required.
->addConstraint('UsernamePhoneRequired')
// Protect this field from unauthorized changes.
->addConstraint('ProtectedUserField');
return $fields;
}
}
