You are here

class DomainForm in Domain Access 8

Base form for domain edit forms.

Hierarchy

Expanded class hierarchy of DomainForm

File

domain/src/DomainForm.php, line 14

Namespace

Drupal\domain
View source
class DomainForm extends EntityForm {

  /**
   * The domain entity storage.
   *
   * @var \Drupal\domain\DomainStorageInterface
   */
  protected $domainStorage;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The domain validator.
   *
   * @var \Drupal\domain\DomainValidatorInterface
   */
  protected $validator;

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

  /**
   * Constructs a DomainForm object.
   *
   * @param \Drupal\domain\DomainStorageInterface $domain_storage
   *   The domain storage manager.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   * @param \Drupal\domain\DomainValidatorInterface $validator
   *   The domain validator.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(DomainStorageInterface $domain_storage, RendererInterface $renderer, DomainValidatorInterface $validator, EntityTypeManagerInterface $entity_type_manager) {
    $this->domainStorage = $domain_storage;
    $this->renderer = $renderer;
    $this->validator = $validator;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager')
      ->getStorage('domain'), $container
      ->get('renderer'), $container
      ->get('domain.validator'), $container
      ->get('entity_type.manager'));
  }

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

    /** @var \Drupal\domain\Entity\Domain $domain */
    $domain = $this->entity;

    // Create defaults if this is the first domain.
    $count_existing = $this->domainStorage
      ->getQuery()
      ->count()
      ->execute();
    if (!$count_existing) {
      $domain
        ->addProperty('hostname', $this->domainStorage
        ->createHostname());
      $domain
        ->addProperty('name', $this
        ->config('system.site')
        ->get('name'));
    }
    $form['domain_id'] = [
      '#type' => 'value',
      '#value' => $domain
        ->getDomainId(),
    ];
    $form['hostname'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Hostname'),
      '#size' => 40,
      '#maxlength' => 80,
      '#default_value' => $domain
        ->getCanonical(),
      '#description' => $this
        ->t('The canonical hostname, using the full <em>subdomain.example.com</em> format. Leave off the http:// and the trailing slash and do not include any paths.<br />If this domain uses a custom http(s) port, you should specify it here, e.g.: <em>subdomain.example.com:1234</em><br />The hostname may contain only lowercase alphanumeric characters, dots, dashes, and a colon (if using alternative ports).'),
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => !empty($domain
        ->id()) ? $domain
        ->id() : '',
      '#disabled' => !empty($domain
        ->id()),
      '#machine_name' => [
        'source' => [
          'hostname',
        ],
        'exists' => [
          $this->domainStorage,
          'load',
        ],
      ],
    ];
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#size' => 40,
      '#maxlength' => 80,
      '#default_value' => $domain
        ->label(),
      '#description' => $this
        ->t('The human-readable name is shown in domain lists and may be used as the title tag.'),
    ];

    // Do not use the :// suffix when storing data.
    $add_suffix = FALSE;
    $form['scheme'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Domain URL scheme'),
      '#options' => [
        'http' => 'http://',
        'https' => 'https://',
        'variable' => 'Variable',
      ],
      '#default_value' => $domain
        ->getRawScheme(),
      '#description' => $this
        ->t('This URL scheme will be used when writing links and redirects to this domain and its resources. Selecting <strong>Variable</strong> will inherit the current scheme of the web request.'),
    ];
    $form['status'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Domain status'),
      '#options' => [
        1 => $this
          ->t('Active'),
        0 => $this
          ->t('Inactive'),
      ],
      '#default_value' => (int) $domain
        ->status(),
      '#description' => $this
        ->t('"Inactive" domains are only accessible to user roles with that assigned permission.'),
    ];
    $form['weight'] = [
      '#type' => 'weight',
      '#title' => $this
        ->t('Weight'),
      '#delta' => $count_existing + 1,
      '#default_value' => $domain
        ->getWeight(),
      '#description' => $this
        ->t('The sort order for this record. Lower values display first.'),
    ];
    $form['is_default'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Default domain'),
      '#default_value' => $domain
        ->isDefault(),
      '#description' => $this
        ->t('If a URL request fails to match a domain record, the settings for this domain will be used. Only one domain can be default.'),
    ];
    $form['validate_url'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Test server response'),
      '#default_value' => TRUE,
      '#description' => $this
        ->t('Validate that  url of the host is accessible to Drupal before saving.'),
    ];
    $required = $this->validator
      ->getRequiredFields();
    foreach ($form as $key => $element) {
      if (in_array($key, $required)) {
        $form[$key]['#required'] = TRUE;
      }
    }
    return $form;
  }

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

    /** @var \Drupal\domain\DomainInterface $entity */
    $entity = $this->entity;
    $hostname = $entity
      ->getHostname();
    $errors = $this->validator
      ->validate($hostname);
    if (!empty($errors)) {

      // Render errors to display as message.
      $message = [
        '#theme' => 'item_list',
        '#items' => $errors,
      ];
      $message = $this->renderer
        ->renderPlain($message);
      $form_state
        ->setErrorByName('hostname', $message);
    }

    // Validate if the same hostname exists.
    // Do not use domain loader because it may change hostname.
    $existing = $this->domainStorage
      ->loadByProperties([
      'hostname' => $hostname,
    ]);
    $existing = reset($existing);

    // If we have already registered a hostname, make sure we don't create a
    // duplicate.
    // We cannot check id() here, as the machine name is editable.
    if ($existing && $existing
      ->getDomainId() != $entity
      ->getDomainId()) {
      $form_state
        ->setErrorByName('hostname', $this
        ->t('The hostname is already registered.'));
    }

    // Is validate_url set?
    if ($entity->validate_url) {

      // Check the domain response. First, clear the path value.
      $entity
        ->setPath();

      // Check the response.
      $response = $this->validator
        ->checkResponse($entity);

      // If validate_url is set, then we must receive a 200 response.
      if ($response !== 200) {
        if (empty($response)) {
          $response = 500;
        }
        $form_state
          ->setErrorByName('hostname', $this
          ->t('The server request to @url returned a @response response. To proceed, disable the <em>Test server response</em> in the form.', [
          '@url' => $entity
            ->getPath(),
          '@response' => $response,
        ]));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::save($form, $form_state);
    if ($status == SAVED_NEW) {
      \Drupal::messenger()
        ->addMessage($this
        ->t('Domain record created.'));
    }
    else {
      \Drupal::messenger()
        ->addMessage($this
        ->t('Domain record updated.'));
    }
    $form_state
      ->setRedirect('domain.admin');
  }

}

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
DomainForm::$domainStorage protected property The domain entity storage.
DomainForm::$entityTypeManager protected property The entity type manager. Overrides EntityForm::$entityTypeManager
DomainForm::$renderer protected property The renderer.
DomainForm::$validator protected property The domain validator.
DomainForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DomainForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
DomainForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
DomainForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
DomainForm::__construct public function Constructs a DomainForm object.
EntityForm::$entity protected property The entity being used by this form. 7
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::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
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.
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.
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.