You are here

class RemoteForm in Entity Share 8.3

Same name and namespace in other branches
  1. 8 modules/entity_share_client/src/Form/RemoteForm.php \Drupal\entity_share_client\Form\RemoteForm
  2. 8.2 modules/entity_share_client/src/Form/RemoteForm.php \Drupal\entity_share_client\Form\RemoteForm

Entity form of the remote entity.

@package Drupal\entity_share_client\Form

Hierarchy

Expanded class hierarchy of RemoteForm

File

modules/entity_share_client/src/Form/RemoteForm.php, line 20

Namespace

Drupal\entity_share_client\Form
View source
class RemoteForm extends EntityForm {

  /**
   * Injected plugin service.
   *
   * @var \Drupal\entity_share_client\ClientAuthorization\ClientAuthorizationPluginManager
   */
  protected $authPluginManager;

  /**
   * The currently configured auth plugin.
   *
   * @var \Drupal\entity_share_client\ClientAuthorization\ClientAuthorizationInterface
   */
  protected $authPlugin;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->authPluginManager = $container
      ->get('plugin.manager.entity_share_client_authorization');
    return $instance;
  }

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

    /** @var \Drupal\entity_share_client\Entity\RemoteInterface $remote */
    $remote = $this->entity;
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $remote
        ->label(),
      '#description' => $this
        ->t('Label for the remote website.'),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $remote
        ->id(),
      '#machine_name' => [
        'source' => [
          'label',
        ],
        'exists' => '\\Drupal\\entity_share_client\\Entity\\Remote::load',
      ],
      '#disabled' => !$remote
        ->isNew(),
    ];
    $form['url'] = [
      '#type' => 'url',
      '#title' => $this
        ->t('URL'),
      '#maxlength' => 255,
      '#description' => $this
        ->t('The remote URL. Example: http://example.com'),
      '#default_value' => $remote
        ->get('url'),
      '#required' => TRUE,
    ];
    $this
      ->addAuthOptions($form, $form_state);
    return $form;
  }

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

    // Validate URL.
    if (!UrlHelper::isValid($form_state
      ->getValue('url'), TRUE)) {
      $form_state
        ->setError($form['url'], $this
        ->t('Invalid URL.'));
    }
    $selectedPlugin = $this
      ->getSelectedPlugin($form, $form_state);
    if ($selectedPlugin instanceof PluginFormInterface) {
      $subformState = SubformState::createForSubform($form['auth']['data'], $form, $form_state);
      $selectedPlugin
        ->validateConfigurationForm($form['auth']['data'], $subformState);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $selectedPlugin = $this
      ->getSelectedPlugin($form, $form_state);
    $subformState = SubformState::createForSubform($form['auth']['data'], $form, $form_state);

    // Store the remote entity in case the plugin submission needs its data.
    $subformState
      ->set('remote', $this->entity);
    $selectedPlugin
      ->submitConfigurationForm($form['auth']['data'], $subformState);
  }

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

    /** @var \Drupal\entity_share_client\Entity\RemoteInterface $remote */
    $remote = $this->entity;
    if (!empty($form['auth']['#plugins'])) {
      $selectedPlugin = $this
        ->getSelectedPlugin($form, $form_state);
      $remote
        ->mergePluginConfig($selectedPlugin);
    }
    $status = $remote
      ->save();
    switch ($status) {
      case SAVED_NEW:
        $this
          ->messenger()
          ->addStatus($this
          ->t('Created the %label remote website.', [
          '%label' => $remote
            ->label(),
        ]));
        break;
      default:
        $this
          ->messenger()
          ->addStatus($this
          ->t('Saved the %label remote website.', [
          '%label' => $remote
            ->label(),
        ]));
    }
    $form_state
      ->setRedirectUrl($remote
      ->toUrl('collection'));
  }

  /**
   * Helper function to build the authorization options in the form.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  protected function addAuthOptions(array &$form, FormStateInterface $form_state) {
    $options = [];
    $plugins = [];
    $commonUuid = '';
    if ($this
      ->hasAuthPlugin()) {
      $options[$this->authPlugin
        ->getPluginId()] = $this->authPlugin
        ->getLabel();
      $plugins[$this->authPlugin
        ->getPluginId()] = $this->authPlugin;

      // Ensure all plugins will have the same uuid in the configuration to
      // avoid duplication of entries in the key value store.
      $existing_plugin_configuration = $this->authPlugin
        ->getConfiguration();
      $commonUuid = $existing_plugin_configuration['uuid'];
    }
    $availablePlugins = $this->authPluginManager
      ->getAvailablePlugins($commonUuid);
    foreach ($availablePlugins as $id => $plugin) {
      if (empty($options[$id])) {

        // This plugin type was not previously set as an option.
        $options[$id] = $plugin
          ->getLabel();
        $plugins[$id] = $plugin;
      }
    }

    // Do we have a value?
    $selected = $form_state
      ->getValue('pid');
    if (!empty($selected)) {
      $selectedPlugin = $plugins[$selected];
    }
    elseif (!empty($this->authPlugin)) {

      // Is a plugin previously stored?
      $selectedPlugin = $this->authPlugin;
    }
    else {

      // Fallback: take the first option.
      $selectedPlugin = reset($plugins);
    }
    $form['auth'] = [
      '#type' => 'container',
      '#plugins' => $plugins,
      'pid' => [
        '#type' => 'radios',
        '#title' => $this
          ->t('Authorization methods'),
        '#options' => $options,
        '#default_value' => $selectedPlugin
          ->getPluginId(),
        '#ajax' => [
          'wrapper' => 'plugin-form-ajax-container',
          'callback' => [
            get_class($this),
            'ajaxPluginForm',
          ],
        ],
      ],
      'data' => [],
    ];
    $subformState = SubformState::createForSubform($form['auth']['data'], $form, $form_state);
    $form['auth']['data'] = $selectedPlugin
      ->buildConfigurationForm($form['auth']['data'], $subformState);
    $form['auth']['data']['#tree'] = TRUE;
    $form['auth']['data']['#prefix'] = '<div id="plugin-form-ajax-container">';
    $form['auth']['data']['#suffix'] = '</div>';
  }

  /**
   * Callback function to return the credentials portion of the form.
   *
   * @param array $form
   *   The rebuilt form.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The current form state.
   *
   * @return array
   *   A portion of the render array.
   */
  public static function ajaxPluginForm(array $form, FormStateInterface $formState) {
    return $form['auth']['data'];
  }

  /**
   * Helper method to instantiate plugin from this entity.
   *
   * @return bool
   *   True if the remote entity has a plugin.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  protected function hasAuthPlugin() {

    /** @var \Drupal\entity_share_client\Entity\RemoteInterface $remote */
    $remote = $this->entity;
    $plugin = $remote
      ->getAuthPlugin();
    if ($plugin instanceof ClientAuthorizationInterface) {
      $this->authPlugin = $plugin;
      return TRUE;
    }
    return FALSE;
  }

  /**
   * Helper method to get selected plugin from the form.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return \Drupal\entity_share_client\ClientAuthorization\ClientAuthorizationInterface
   *   The selected plugin.
   */
  protected function getSelectedPlugin(array &$form, FormStateInterface $form_state) {
    $authPluginId = $form_state
      ->getValue('pid');
    $plugins = $form['auth']['#plugins'];

    /** @var \Drupal\entity_share_client\ClientAuthorization\ClientAuthorizationInterface $selectedPlugin */
    $selectedPlugin = $plugins[$authPluginId];
    return $selectedPlugin;
  }

}

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::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::__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.
RemoteForm::$authPlugin protected property The currently configured auth plugin.
RemoteForm::$authPluginManager protected property Injected plugin service.
RemoteForm::addAuthOptions protected function Helper function to build the authorization options in the form.
RemoteForm::ajaxPluginForm public static function Callback function to return the credentials portion of the form.
RemoteForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
RemoteForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
RemoteForm::getSelectedPlugin protected function Helper method to get selected plugin from the form.
RemoteForm::hasAuthPlugin protected function Helper method to instantiate plugin from this entity.
RemoteForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
RemoteForm::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
RemoteForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.