username-1.0.x-dev/modules/username_phone/src/Form/UsernamePhoneForm.php
modules/username_phone/src/Form/UsernamePhoneForm.php
<?php
namespace Drupal\username_phone\Form;
use Drupal\Core\Entity\EntityConstraintViolationListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\RegisterForm;
/**
* Form handler for the user register forms.
*
* This class extends the default user register form to include phone number
* field and related functionalities.
*/
class UsernamePhoneForm extends RegisterForm {
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
// Start with the default user account fields.
$form = parent::form($form, $form_state);
/** @var \Drupal\user\UserInterface $account */
$account = $this->entity;
// Check if this is a new account.
$register = $account->isNew();
// Load Username phone settings.
$config = \Drupal::config('username_phone.settings');
$configUsername = \Drupal::config('username.settings');
$username = $configUsername->get('username');
// Add phone field to the user account form.
$form['account']['phone'] = [
'#title' => $this->t('Phone number'),
'#description' => $this->t('The phone number is not made public. It will only be used if you need to be contacted about your account or for opted-in notifications.'),
'#type' => 'phone',
'#phone' => [
'countries' => $config->get('countries'),
'exclude_countries' => [],
'initial_country' => $config->get('initial_country'),
'preferred_countries' => $config->get('preferred_countries'),
'show_flags' => $config->get('show_flags'),
'allow_dropdown' => $config->get('allow_dropdown'),
'separate_dial_code' => $config->get('separate_dial_code'),
],
'#required' => (isset($username['phone']) || $configUsername->get('phone.verification')) && !(!$account->getPhone() && \Drupal::currentUser()->hasPermission('administer users')),
'#default_value' => $register ? '' : $account->getPhone(),
'#access' => $account->phone->access('edit'),
];
$form['account']['phone_number'] = [
'#type' => 'hidden',
'#attributes' => ['class' => 'temporary-phone'],
];
$form['account']['country_code'] = [
'#type' => 'hidden',
'#attributes' => ['class' => 'temporary-phone'],
];
$form['account']['country_iso2'] = [
'#type' => 'hidden',
'#attributes' => ['class' => 'temporary-phone'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Get form values.
$values = $form_state->getValues();
if (isset($values['phone_number'])) {
// If phone number is set, switch values to ensure phone mask validation.
$phone_mask = $values['phone'];
$form_state->setValue('phone', $values['phone_number']);
$form_state->setValue('phone_number', $phone_mask);
}
// Call parent validation to ensure other fields are validated.
parent::validateForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
// Save user account information first.
parent::save($form, $form_state);
$account = $this->entity;
$values = $form_state->getValues();
// Check if phone number and related fields are set.
if (isset($values['phone']) && isset($values['phone_number']) && isset($values['country_code']) && isset($values['country_iso2'])) {
// Save the phone number and related details to the database.
\Drupal::database()->merge('user__phones')
->key(['uid' => $account->id()])
->fields([
'phone_number' => $values['phone'],
'local_number' => $values['phone_number'],
'country_code' => $values['country_code'],
'country_iso2' => $values['country_iso2'],
'created' => \Drupal::time()->getRequestTime(),
])
->execute();
}
}
/**
* {@inheritdoc}
*/
protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
// Flag phone field for any constraint violations.
$field_names = ['phone'];
foreach ($violations->getByFields($field_names) as $violation) {
[$field_name] = explode('.', $violation->getPropertyPath(), 2);
$form_state->setErrorByName($field_name, $violation->getMessage());
}
// Call parent method to flag other violations.
parent::flagViolations($violations, $form, $form_state);
}
}
