You are here

class ContributeSettingsForm in Contribute 8

Configure contribute settings for this site.

Hierarchy

Expanded class hierarchy of ContributeSettingsForm

1 string reference to 'ContributeSettingsForm'
contribute.routing.yml in ./contribute.routing.yml
contribute.routing.yml

File

src/Form/ContributeSettingsForm.php, line 20

Namespace

Drupal\contribute\Form
View source
class ContributeSettingsForm extends ConfigFormBase {

  /**
   * The contribute manager.
   *
   * @var \Drupal\contribute\ContributeManagerInterface
   */
  protected $contributeManager;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'contribute_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  public function getEditableConfigNames() {
    return [
      'contribute.settings',
    ];
  }

  /**
   * Constructs a ContributeSettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\contribute\ContributeManagerInterface $contribute_manager
   *   The contribute manager.
   */
  public function __construct(ConfigFactoryInterface $config_factory, ContributeManagerInterface $contribute_manager) {
    parent::__construct($config_factory);
    $this->contributeManager = $contribute_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('contribute.manager'));
  }

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

    // Add the core AJAX library.
    $form['#attached']['library'][] = 'core/drupal.ajax';
    $config = $this
      ->config('contribute.settings');
    $form['#attributes'] = [
      'novalidate' => TRUE,
    ];
    $form['account'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Drupal.org Account'),
      '#states' => [
        'visible' => [
          ':input[name="disable"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $form['account']['account_type'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Account type'),
      '#description' => $this
        ->t('Select the type of Drupal.org account that you use to contribute back to Drupal'),
      '#options' => [
        'user' => $this
          ->t('Individual user'),
        'organization' => $this
          ->t('Organization'),
      ],
      '#default_value' => $config
        ->get('account_type') ?: 'user',
      '#states' => [
        'required' => [
          ':input[name="disable"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $form['account']['user_id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Drupal.org user name'),
      '#description' => $this
        ->t('Enter your user name. <a href=":href">Create new user account</a>', [
        ':href' => 'https://register.drupal.org/user/register',
      ]),
      '#default_value' => $config
        ->get('account_type') === 'user' ? $config
        ->get('account_id') : '',
      '#autocomplete_route_name' => 'contribute.autocomplete',
      '#autocomplete_route_parameters' => [
        'account_type' => 'user',
      ],
      '#states' => [
        'required' => [
          ':input[name="account_type"]' => [
            'value' => 'user',
          ],
        ],
        'visible' => [
          ':input[name="account_type"]' => [
            'value' => 'user',
          ],
        ],
      ],
    ];
    $form['account']['organization_id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Drupal.org organization name'),
      '#description' => $this
        ->t('Enter your organization\'s name. <a href=":href">Create new organization</a>', [
        ':href' => 'https://www.drupal.org/node/add/organization',
      ]),
      '#default_value' => $config
        ->get('account_type') === 'organization' ? $config
        ->get('account_id') : '',
      '#autocomplete_route_name' => 'contribute.autocomplete',
      '#autocomplete_route_parameters' => [
        'account_type' => 'organization',
      ],
      '#states' => [
        'required' => [
          ':input[name="account_type"]' => [
            'value' => 'organization',
          ],
        ],
        'visible' => [
          ':input[name="account_type"]' => [
            'value' => 'organization',
          ],
        ],
      ],
    ];
    $form['warning'] = [
      '#type' => 'container',
      '#markup' => '<strong>' . $this
        ->t('Are you sure that you want to hide contribution information?') . '</strong><br/>' . $this
        ->t('Contribute information will only be configurable from the <a href=":href">Extend</a> page.', [
        ':href' => Url::fromRoute('system.modules_list')
          ->toString(),
      ]),
      '#attributes' => [
        'class' => [
          'messages messages--warning',
        ],
      ],
      '#states' => [
        'visible' => [
          ':input[name="disable"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['disable'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t("Do not display contribution information"),
      '#default_value' => !$config
        ->get('status'),
      '#return_value' => TRUE,
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#button_type' => 'primary',
    ];
    $form['actions']['delete'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Clear'),
      '#attributes' => [
        'class' => [
          'button--danger',
        ],
      ],
    ];

    // Add Ajax wrapper and submit to the form.
    if ($this
      ->isModal()) {
      $form['#form_wrapper_id'] = $this
        ->getWrapperId();
      $form['#prefix'] = '<div id="' . $this
        ->getWrapperId() . '">';
      $form['#suffix'] = '</div>';
      $form['actions']['submit']['#ajax'] = [
        'callback' => '::submitAjaxForm',
        'event' => 'click',
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    if ((string) $form_state
      ->getValue('op') === (string) $this
      ->t('Clear') || $form_state
      ->getValue('disable')) {
      return;
    }
    $account_type = $form_state
      ->getValue('account_type');
    $account_id = $form_state
      ->getValue($account_type . '_id');
    $this->contributeManager
      ->setAccountType($account_type);
    $this->contributeManager
      ->setAccountId($account_id);
    $account = $this->contributeManager
      ->getAccount();
    if (!$account['status']) {
      $t_args = [
        '@name' => $account_type === 'individual' ? $this
          ->t('Drupal.org user name') : $this
          ->t('Drupal.org organization name'),
      ];
      $form_state
        ->setErrorByName($account_type . '_id', $this
        ->t('Invalid @name.', $t_args));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ((string) $form_state
      ->getValue('op') === (string) $this
      ->t('Clear')) {
      $status = TRUE;
      $account_type = NULL;
      $account_id = NULL;
      $this
        ->messenger()
        ->addMessage($this
        ->t('Community information has been cleared.'));
    }
    elseif ($form_state
      ->getValue('disable')) {
      $status = FALSE;
      $account_type = NULL;
      $account_id = NULL;
      $this
        ->messenger()
        ->addMessage($this
        ->t('Community information has been disabled.'));
    }
    else {
      $status = TRUE;
      $account_type = $form_state
        ->getValue('account_type');
      $account_id = $form_state
        ->getValue($account_type . '_id');
      $this
        ->messenger()
        ->addMessage($this
        ->t('Your community information has been saved.'));
    }

    // Always clear cached information.
    Cache::invalidateTags([
      'contribute',
    ]);
    $this
      ->config('contribute.settings')
      ->set('status', $status)
      ->set('account_type', $account_type)
      ->set('account_id', $account_id)
      ->save();
    $form_state
      ->setRedirect('system.status');
  }

  /**
   * Submit form #ajax callback.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   An Ajax response that display validation error messages or redirects
   *   to a URL
   */
  public function submitAjaxForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->hasAnyErrors()) {

      // Display messages first by prefixing it the form and setting its weight
      // to -1000.
      $form = [
        'status_messages' => [
          '#type' => 'status_messages',
          '#weight' => -1000,
        ],
      ] + $form;

      // Remove wrapper.
      unset($form['#prefix'], $form['#suffix']);
      $response = new AjaxResponse();
      $response
        ->addCommand(new HtmlCommand('#' . $this
        ->getWrapperId(), $form));
      return $response;
    }
    else {
      $response = new AjaxResponse();
      $response
        ->addCommand(new RedirectCommand(Url::fromRoute('system.status')
        ->toString()));
      return $response;
    }
  }

  /**
   * Determine if this form is being displayed in a modal dialog.
   *
   * @return bool
   *   TRUE is the form is being display in a modal dialog.
   */
  protected function isModal() {
    $wrapper_format = $this
      ->getRequest()
      ->get(MainContentViewSubscriber::WRAPPER_FORMAT);
    return in_array($wrapper_format, [
      'drupal_modal',
      'drupal_ajax',
    ]);
  }

  /**
   * Get the form's Ajax wrapper id.
   *
   * @return string
   *   The form's Ajax wrapper id.
   */
  protected function getWrapperId() {
    return $this
      ->getFormId() . '-ajax';
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
ContributeSettingsForm::$contributeManager protected property The contribute manager.
ContributeSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
ContributeSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
ContributeSettingsForm::getEditableConfigNames public function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
ContributeSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ContributeSettingsForm::getWrapperId protected function Get the form's Ajax wrapper id.
ContributeSettingsForm::isModal protected function Determine if this form is being displayed in a modal dialog.
ContributeSettingsForm::submitAjaxForm public function Submit form #ajax callback.
ContributeSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
ContributeSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ContributeSettingsForm::__construct public function Constructs a ContributeSettingsForm object. Overrides ConfigFormBase::__construct
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
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.