You are here

class SmsGatewayForm in SMS Framework 8

Form controller for SMS Gateways.

Hierarchy

Expanded class hierarchy of SmsGatewayForm

File

src/Form/SmsGatewayForm.php, line 22

Namespace

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

  /**
   * The route builder.
   *
   * @var \Drupal\Core\Routing\RouteBuilderInterface
   */
  protected $routeBuilder;

  /**
   * The request context.
   *
   * @var \Drupal\Core\Routing\RequestContext
   */
  protected $requestContext;

  /**
   * The access manager service.
   *
   * @var \Drupal\Core\Access\AccessManagerInterface
   */
  protected $accessManager;

  /**
   * The entity query factory.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $entityQueryFactory;

  /**
   * The gateway manager.
   *
   * @var \Drupal\sms\Plugin\SmsGatewayPluginManagerInterface
   */
  protected $gatewayManager;

  /**
   * Constructs a new SmsGatewayForm object.
   *
   * @param \Drupal\Core\Routing\RouteBuilderInterface $route_builder
   *   The route builder.
   * @param \Drupal\Core\Routing\RequestContext $request_context
   *   The request context.
   * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
   *   The access manager.
   * @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
   *   The entity query factory.
   * @param \Drupal\sms\Plugin\SmsGatewayPluginManagerInterface $gateway_manager
   *   The gateway manager service.
   */
  public function __construct(RouteBuilderInterface $route_builder, RequestContext $request_context, AccessManagerInterface $access_manager, QueryFactory $query_factory, SmsGatewayPluginManagerInterface $gateway_manager) {
    $this->routeBuilder = $route_builder;
    $this->requestContext = $request_context;
    $this->accessManager = $access_manager;
    $this->entityQueryFactory = $query_factory;
    $this->gatewayManager = $gateway_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('router.builder'), $container
      ->get('router.request_context'), $container
      ->get('access_manager'), $container
      ->get('entity.query'), $container
      ->get('plugin.manager.sms_gateway'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);

    /** @var \Drupal\sms\Entity\SmsGatewayInterface $sms_gateway */
    $sms_gateway = $this
      ->getEntity();
    if (!$sms_gateway
      ->isNew()) {
      $form['#title'] = $this
        ->t('Edit gateway %label', [
        '%label' => $sms_gateway
          ->label(),
      ]);
    }
    $form['gateway'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Gateway'),
      '#open' => TRUE,
    ];
    $form['gateway']['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $sms_gateway
        ->label(),
      '#required' => TRUE,
    ];
    $form['gateway']['id'] = [
      '#type' => 'machine_name',
      '#title' => $this
        ->t('Machine name'),
      '#default_value' => $sms_gateway
        ->id(),
      '#machine_name' => [
        'source' => [
          'gateway',
          'label',
        ],
        'exists' => [
          $this,
          'exists',
        ],
        'replace_pattern' => '([^a-z0-9_]+)|(^custom$)',
        'error' => 'The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores.',
      ],
      '#disabled' => !$sms_gateway
        ->isNew(),
    ];
    $form['gateway']['status'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable'),
      '#description' => $this
        ->t('Enable this gateway?'),
      '#default_value' => $sms_gateway
        ->status(),
    ];
    $plugins = [];
    foreach ($this->gatewayManager
      ->getDefinitions() as $plugin_id => $definition) {
      $plugins[$plugin_id] = $definition['label'];
    }
    $form['gateway']['plugin_id'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Gateway'),
      '#options' => $plugins,
      '#required' => TRUE,
      '#disabled' => !$sms_gateway
        ->isNew(),
      '#default_value' => !$sms_gateway
        ->isNew() ? $sms_gateway
        ->getPlugin()
        ->getPluginId() : '',
    ];
    $form['message_queue'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Message queue'),
      '#open' => TRUE,
    ];
    $form['message_queue']['skip_queue'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Skip queue'),
      '#description' => $this
        ->t('Whether messages sent with this gateway skip the load balancing queue and process immediately. Only turn on this setting when debugging, do not use it on production sites.'),
      '#default_value' => $sms_gateway
        ->getSkipQueue(),
    ];
    $form['message_queue']['retention_duration_incoming'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Incoming message retention'),
      '#description' => $this
        ->t('How many seconds to keep messages after they are received. Use -1 to never expire.'),
      '#field_suffix' => $this
        ->t('seconds'),
      '#default_value' => $sms_gateway
        ->getRetentionDuration(Direction::INCOMING),
      '#min' => -1,
    ];
    $form['message_queue']['retention_duration_outgoing'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Outgoing message retention'),
      '#description' => $this
        ->t('How many seconds to keep messages after they are sent. Use -1 to never expire.'),
      '#field_suffix' => $this
        ->t('seconds'),
      '#default_value' => $sms_gateway
        ->getRetentionDuration(Direction::OUTGOING),
      '#min' => -1,
    ];
    $form['incoming_messages'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Incoming messages'),
      '#open' => TRUE,
      '#optional' => TRUE,
      '#tree' => TRUE,
    ];
    $form['incoming_messages']['push_path'] = [
      '#type' => 'textfield',
      '#title' => t('Pushed messages url'),
      '#default_value' => $sms_gateway
        ->getPushIncomingPath(),
      '#description' => t('The path where incoming messages are received.'),
      '#size' => 60,
      '#field_prefix' => $this->requestContext
        ->getCompleteBaseUrl(),
      '#access' => !$sms_gateway
        ->isNew() ? $sms_gateway
        ->autoCreateIncomingRoute() : TRUE,
      '#group' => 'incoming_messages',
    ];

    // Don't check for incoming support yet, plugin type unknown.
    if (!$sms_gateway
      ->isNew()) {

      // Remove optional tag so the plain text element is shown.
      $form['incoming_messages']['#optional'] = FALSE;
      if (!$sms_gateway
        ->supportsIncoming()) {
        $form['incoming_messages']['unsupported']['#plain_text'] = $this
          ->t('This gateway does not support receiving messages.');
      }
    }
    $form['delivery_reports'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Delivery reports'),
      '#open' => TRUE,
      '#optional' => TRUE,
    ];
    $form['delivery_reports']['#tree'] = TRUE;
    $form['delivery_reports']['push_path'] = [
      '#type' => 'textfield',
      '#title' => t('Pushed delivery report Url'),
      '#default_value' => $sms_gateway
        ->getPushReportPath(),
      '#description' => t('The path where pushed delivery reports are received.'),
      '#size' => 60,
      '#field_prefix' => $this->requestContext
        ->getCompleteBaseUrl(),
      '#access' => !$sms_gateway
        ->isNew() ? $sms_gateway
        ->supportsReportsPush() : TRUE,
      '#group' => 'delivery_reports',
    ];
    if (!$sms_gateway
      ->isNew()) {
      $instance = $sms_gateway
        ->getPlugin();
      $form += $instance
        ->buildConfigurationForm($form, $form_state);
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    /** @var \Drupal\sms\Entity\SmsGatewayInterface $sms_gateway */
    $sms_gateway = $this
      ->getEntity();
    if ($sms_gateway
      ->isNew()) {
      $sms_gateway = SmsGateway::create([
        'plugin' => $form_state
          ->getValue('plugin_id'),
      ]);
      $this
        ->setEntity($sms_gateway);
    }
    else {
      $sms_gateway
        ->getPlugin()
        ->validateConfigurationForm($form, $form_state);
    }
    $path_elements_parents = [
      [
        'incoming_messages',
        'push_path',
      ],
      [
        'delivery_reports',
        'push_path',
      ],
    ];
    foreach ($path_elements_parents as $parents) {
      $element = NestedArray::getValue($form, $parents);
      $path = $form_state
        ->getValue($parents);
      $path_length = Unicode::strlen($path);

      // Length must be more than 2 chars, including leading slash character.
      if ($path_length > 0) {
        if (Unicode::substr($path, 0, 1) !== '/') {
          $form_state
            ->setError($element, $this
            ->t("Path must begin with a '/' character."));
        }
        if ($path_length == 1) {
          $form_state
            ->setError($element, $this
            ->t("Not enough characters for path."));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    /** @var \Drupal\sms\Entity\SmsGatewayInterface $sms_gateway */
    $sms_gateway = $this
      ->getEntity();
    if (!$sms_gateway
      ->isNew()) {
      $sms_gateway
        ->getPlugin()
        ->submitConfigurationForm($form, $form_state);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\sms\Entity\SmsGatewayInterface $sms_gateway */
    $sms_gateway = $this
      ->getEntity();
    $incoming_push_path_original = $sms_gateway
      ->getPushIncomingPath();
    $incoming_push_path = $form_state
      ->getValue([
      'incoming_messages',
      'push_path',
    ]);
    $reports_push_path_original = $sms_gateway
      ->getPushReportPath();
    $reports_push_path = $form_state
      ->getValue([
      'delivery_reports',
      'push_path',
    ]);
    $sms_gateway
      ->setStatus($form_state
      ->getValue('status'))
      ->setPushReportPath($reports_push_path)
      ->setPushIncomingPath($incoming_push_path);
    $saved = $sms_gateway
      ->save();
    if ($saved == SAVED_NEW) {
      drupal_set_message($this
        ->t('Gateway created.'));
      $rebuild = !empty($incoming_push_path) || !empty($reports_push_path);

      // Redirect to edit form.
      $form_state
        ->setRedirectUrl(Url::fromRoute('entity.sms_gateway.edit_form', [
        'sms_gateway' => $sms_gateway
          ->id(),
      ]));
    }
    else {
      drupal_set_message($this
        ->t('Gateway saved.'));

      // Only rebuild routes if the paths changed.
      $rebuild_incoming = $incoming_push_path_original != $incoming_push_path;
      $rebuild_reports = $reports_push_path_original != $reports_push_path;
      $rebuild = $rebuild_incoming || $rebuild_reports;

      // Back to list page.
      $form_state
        ->setRedirect('sms.gateway.list');
    }
    if ($rebuild) {
      $this->routeBuilder
        ->setRebuildNeeded();
    }
  }

  /**
   * {@inheritdoc}
   *
   * Callback for `id` form element in SmsGatewayForm->buildForm.
   */
  public function exists($entity_id, array $element, FormStateInterface $form_state) {
    $query = $this->entityQueryFactory
      ->get('sms_gateway');
    return (bool) $query
      ->condition('id', $entity_id)
      ->execute();
  }

}

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::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
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::__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.
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.
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.
SmsGatewayForm::$accessManager protected property The access manager service.
SmsGatewayForm::$entityQueryFactory protected property The entity query factory.
SmsGatewayForm::$gatewayManager protected property The gateway manager.
SmsGatewayForm::$requestContext protected property The request context.
SmsGatewayForm::$routeBuilder protected property The route builder.
SmsGatewayForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
SmsGatewayForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
SmsGatewayForm::exists public function Callback for `id` form element in SmsGatewayForm->buildForm.
SmsGatewayForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
SmsGatewayForm::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 EntityForm::submitForm
SmsGatewayForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
SmsGatewayForm::__construct public function Constructs a new SmsGatewayForm object.
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.