You are here

class PhoneNumberSettingsForm in SMS Framework 8

Form controller for phone number settings.

Hierarchy

Expanded class hierarchy of PhoneNumberSettingsForm

1 file declares its use of PhoneNumberSettingsForm
PhoneNumberSettings.php in src/Plugin/migrate/destination/PhoneNumberSettings.php

File

src/Form/PhoneNumberSettingsForm.php, line 17

Namespace

Drupal\sms\Form
View source
class PhoneNumberSettingsForm extends EntityForm {

  /**
   * Form field value used to indicate to create a new attached field.
   */
  const CREATE_NEW_FIELD = '!create';

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity type bundle info.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * {@inheritdoc}
   *
   * @var \Drupal\sms\Entity\PhoneNumberSettingsInterface
   */
  protected $entity;

  /**
   * Constructs a new PhoneNumberSettingsForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle info.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityFieldManagerInterface $entity_field_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->entityFieldManager = $entity_field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('entity_type.bundle.info'), $container
      ->get('entity_field.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config =& $this->entity;
    $form = parent::buildForm($form, $form_state);
    $bundles = [];
    $storage = $this->entityTypeManager
      ->getStorage('phone_number_settings');

    // Generate a list of field-able bundles.
    foreach ($this->entityTypeManager
      ->getDefinitions() as $entity_type) {
      if ($entity_type
        ->isSubclassOf(ContentEntityInterface::class)) {
        foreach ($this->entityTypeBundleInfo
          ->getBundleInfo($entity_type
          ->id()) as $bundle => $bundle_info) {

          // Do not show combinations with pre-existing phone number settings.
          // But, make sure all options are available on existing phone
          // number settings. They are hidden + read only from user anyway.
          if (!$storage
            ->load($entity_type
            ->id() . '.' . $bundle) || !$config
            ->isNew()) {
            $bundles[(string) $entity_type
              ->getLabel()][$entity_type
              ->id() . '|' . $bundle] = $bundle_info['label'];
          }
        }
      }
    }
    $bundle_default_value = !$config
      ->isNew() ? $config
      ->getPhoneNumberEntityTypeId() . '|' . $config
      ->getPhoneNumberBundle() : NULL;

    // Field cannot be called 'bundle' or odd behaviour will happen on re-saves.
    $form['entity_bundle'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Bundle'),
      '#options' => $bundles,
      '#default_value' => $bundle_default_value,
      '#required' => TRUE,
      '#access' => $config
        ->isNew(),
      '#ajax' => [
        'callback' => '::updateFieldMapping',
        'wrapper' => 'edit-field-mapping-wrapper',
      ],
    ];
    if (!$bundles) {
      $form['entity_bundle']['#empty_option'] = $this
        ->t('No Bundles Available');
    }
    $field_options = [];
    $field_options['telephone'][self::CREATE_NEW_FIELD] = $this
      ->t('- Create a new telephone field -');
    $field_options['boolean'][self::CREATE_NEW_FIELD] = $this
      ->t('- Create a new boolean field -');
    if ($entity_bundle = $form_state
      ->getValue('entity_bundle', $bundle_default_value ?: NULL)) {
      list($entity_type_id, $bundle) = explode('|', $entity_bundle);
      if (!empty($entity_type_id) && !empty($bundle)) {
        $field_definitions = $this->entityFieldManager
          ->getFieldDefinitions($entity_type_id, $bundle);
        foreach ($field_definitions as $field_definition) {
          $field_type = $field_definition
            ->getType();
          if (isset($field_options[$field_type])) {
            $field_options[$field_type][$field_definition
              ->getName()] = $field_definition
              ->getLabel();
          }
        }
      }
    }
    $form['field_mapping'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Field mapping'),
      '#prefix' => '<div id="edit-field-mapping-wrapper">',
      '#suffix' => '</div>',
      '#tree' => TRUE,
    ];

    // Form ID must be the same as found in $config->getFieldName().
    // ($config->getFieldName($config_key) ==
    // $form['field_mapping'][$config_key]).
    $form['field_mapping']['phone_number'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Phone number'),
      '#description' => $this
        ->t('Select the field storing phone numbers.'),
      '#options' => $field_options['telephone'],
      '#required' => TRUE,
      '#empty_option' => $this
        ->t('- Select -'),
      '#default_value' => $config
        ->getFieldName('phone_number'),
    ];
    $form['field_mapping']['automated_opt_out'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Automated messages opt out'),
      '#description' => $this
        ->t('Select the field storing preference to opt out of automated messages.'),
      '#options' => $field_options['boolean'],
      '#empty_option' => $this
        ->t('- None -'),
      '#default_value' => $config
        ->getFieldName('automated_opt_out'),
    ];
    $form['message'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Messages'),
    ];
    $form['message']['verification_message'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Verification message'),
      '#description' => $this
        ->t('SMS message sent to verify a phone number. The message should contain the verification code and a link to the verification page.'),
      '#default_value' => $config
        ->isNew() ? "Your verification code is '[sms-message:verification-code]'.\nGo to [sms:verification-url] to verify your phone number.\n- [site:name]" : $config
        ->getVerificationMessage(),
    ];
    $tokens = [
      'sms-message',
    ];
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $form['message']['tokens']['list'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => $tokens,
      ];
    }
    else {
      foreach ($tokens as &$token) {
        $token = "[{$token}:*]";
      }
      $form['message']['tokens']['list'] = [
        '#markup' => $this
          ->t('Available tokens include: @token_types', [
          '@token_types' => implode(' ', $tokens),
        ]),
      ];
    }
    $form['expiration'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Verification expiration'),
    ];
    $form['expiration']['code_lifetime'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Verification code lifetime'),
      '#description' => $this
        ->t('How long a verification code is valid, before it expires. Existing verification codes are retroactively updated.'),
      '#field_suffix' => $this
        ->t('seconds'),
      '#required' => TRUE,
      '#min' => 60,
      '#default_value' => $config
        ->isNew() ? 3600 : $config
        ->getVerificationCodeLifetime(),
    ];
    $form['expiration']['phone_number_purge'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Purge phone numbers'),
      '#description' => $this
        ->t('Remove phone number if verification code expires.'),
      '#default_value' => $config
        ->isNew() ?: $config
        ->getPurgeVerificationPhoneNumber(),
    ];
    return $form;
  }

  /**
   * Handles AJAX callback for bundle field on new phone number settings.
   */
  public function updateFieldMapping($form, FormStateInterface $form_state) {
    return $form['field_mapping'];
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $config =& $this->entity;
    list($entity_type_id, $bundle) = explode('|', $form_state
      ->getValue('entity_bundle'));
    $config
      ->setPhoneNumberEntityTypeId($entity_type_id)
      ->setPhoneNumberBundle($bundle);
    $config
      ->setVerificationMessage($form_state
      ->getValue('verification_message'))
      ->setVerificationCodeLifetime($form_state
      ->getValue('code_lifetime'))
      ->setPurgeVerificationPhoneNumber((bool) $form_state
      ->getValue('phone_number_purge'));
    foreach ($form_state
      ->getValue('field_mapping') as $config_key => $field_name) {
      if ($field_name == self::CREATE_NEW_FIELD) {
        $field_config = $this
          ->createNewField($entity_type_id, $bundle, $config_key);
        $field_name = $field_config
          ->getName();
      }
      else {

        // Use existing field.

        /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $entity_form_display */
        $entity_form_display = $field_storage_config = $this->entityTypeManager
          ->getStorage('entity_form_display')
          ->load($entity_type_id . '.' . $bundle . '.default');
        if ($entity_form_display) {
          $component = $entity_form_display
            ->getComponent($field_name) ?: [];

          // Only change existing form formatter if it is using default
          // widget, or none at all.
          if (!$component || $component && $component['type'] == 'telephone_default') {
            $component['type'] = 'sms_telephone';
            $entity_form_display
              ->setComponent($field_name, $component)
              ->save();
          }
        }
      }
      $config
        ->setFieldName($config_key, $field_name);
    }
    $saved = $config
      ->save();
    $t_args['%id'] = $config
      ->id();
    if ($saved == SAVED_NEW) {
      drupal_set_message($this
        ->t('Phone number settings %id created.', $t_args));
    }
    else {
      drupal_set_message($this
        ->t('Phone number settings %id saved.', $t_args));
    }
    $form_state
      ->setRedirectUrl(Url::fromRoute('sms.phone_number_settings.list'));
  }

  /**
   * Create a new field storage and field, and modify form display.
   *
   * @param string $entity_type_id
   *   An entity type ID.
   * @param string $bundle
   *   A bundle ID.
   * @param string $config_key
   *   A config ID as found in sms.phone.*.*.fields.$config_key.
   *
   * @return \Drupal\field\FieldConfigInterface
   *   A field config entity.
   */
  public static function createNewField($entity_type_id, $bundle, $config_key) {
    $entity_type_manager = \Drupal::entityTypeManager();

    // Definitions for field_storage_config.
    $definitions['field_storage']['phone_number']['type'] = 'telephone';
    $definitions['field_storage']['automated_opt_out']['type'] = 'boolean';

    // Definitions for field_config.
    $definitions['field']['phone_number']['label'] = t('Phone number');
    $definitions['field']['automated_opt_out'] = [
      'label' => t('Opt out of SMS messages.'),
      'description' => t('SMS messages requested by you are exempt.'),
      'settings' => [
        'on_label' => t('Do not receive SMS messages from this site.'),
        'off_label' => t('Receive SMS messages from this site.'),
      ],
    ];

    // Definitions for form displays.
    $definitions['form_display']['phone_number']['type'] = 'sms_telephone';
    $definitions['form_display']['automated_opt_out']['type'] = 'boolean_checkbox';

    // Generate a unique field name.
    $i = 1;
    $field_name = $config_key;
    while ($entity_type_manager
      ->getStorage('field_storage_config')
      ->load($entity_type_id . '.' . $field_name)) {
      $i++;
      $field_name = $config_key . '_' . $i;
    }

    /** @var \Drupal\field\FieldStorageConfigInterface $field_storage_config */
    $field_storage_config = $entity_type_manager
      ->getStorage('field_storage_config')
      ->create([
      'entity_type' => $entity_type_id,
      'field_name' => $field_name,
    ] + $definitions['field_storage'][$config_key]);
    $field_storage_config
      ->save();
    $field_config = $entity_type_manager
      ->getStorage('field_config')
      ->create([
      'entity_type' => $entity_type_id,
      'bundle' => $bundle,
      'field_name' => $field_name,
    ] + $definitions['field'][$config_key]);
    $field_config
      ->save();

    /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $entity_form_display */
    $entity_form_display = $field_storage_config = $entity_type_manager
      ->getStorage('entity_form_display')
      ->load($entity_type_id . '.' . $bundle . '.default');

    // Only modify display if it already exists. Don't attempt to create it.
    if ($entity_form_display) {
      $entity_form_display
        ->setComponent($field_name, $definitions['form_display'][$config_key]);
      $entity_form_display
        ->save();
    }
    return $field_config;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::form public function Gets the actual form array to be built. 30
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PhoneNumberSettingsForm::$entity protected property Overrides EntityForm::$entity
PhoneNumberSettingsForm::$entityFieldManager protected property The entity field manager.
PhoneNumberSettingsForm::$entityTypeBundleInfo protected property The entity type bundle info.
PhoneNumberSettingsForm::$entityTypeManager protected property The entity type manager. Overrides EntityForm::$entityTypeManager
PhoneNumberSettingsForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
PhoneNumberSettingsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
PhoneNumberSettingsForm::createNewField public static function Create a new field storage and field, and modify form display.
PhoneNumberSettingsForm::CREATE_NEW_FIELD constant Form field value used to indicate to create a new attached field.
PhoneNumberSettingsForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
PhoneNumberSettingsForm::updateFieldMapping public function Handles AJAX callback for bundle field on new phone number settings.
PhoneNumberSettingsForm::__construct public function Constructs a new PhoneNumberSettingsForm object.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.