You are here

class UserSettings in Notify 8

Same name and namespace in other branches
  1. 2.0.x src/Form/UserSettings.php \Drupal\notify\Form\UserSettings
  2. 1.0.x src/Form/UserSettings.php \Drupal\notify\Form\UserSettings

Defines a form that configures forms module settings.

Hierarchy

Expanded class hierarchy of UserSettings

1 string reference to 'UserSettings'
notify.routing.yml in ./notify.routing.yml
notify.routing.yml

File

src/Form/UserSettings.php, line 19

Namespace

Drupal\notify\Form
View source
class UserSettings extends ConfigFormBase {

  /**
   * Drupal\Core\Messenger\MessengerInterface definition.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Class constructor.
   *
   * @param ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param MessengerInterface $messenger
   *   The core messenger service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, MessengerInterface $messenger) {
    parent::__construct($config_factory);
    $this->messenger = $messenger;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $config = $this
      ->config('notify.settings');
    $userprofile = \Drupal::routeMatch()
      ->getParameter('user');
    $account = \Drupal\user\Entity\User::load($userprofile);
    if (!is_object($account)) {
      return;
    }
    $result = \Drupal::database()
      ->select('users', 'u');
    $result
      ->leftjoin('users_field_data', 'v', 'u.uid = v.uid');
    $result
      ->leftjoin('notify', 'n', 'u.uid = n.uid');
    $result
      ->fields('u', [
      'uid',
    ]);
    $result
      ->fields('v', [
      'name',
      'mail',
    ]);
    $result
      ->fields('n', [
      'node',
      'teasers',
      'comment',
      'status',
    ]);
    $result
      ->condition('u.uid', $userprofile);
    $result->allowRowCount = TRUE;
    $notify = $result
      ->execute()
      ->fetchObject();

    // Internal error.
    if (!is_object($notify)) {
      $notify = NULL;
    }
    $form = [];
    if (!$notify->mail) {
      $url = '/user/' . $userprofile . '/edit';
      $this->messenger
        ->addMessage($this
        ->t('Your e-mail address must be specified on your <a href="@url">my account</a> page.', [
        '@url' => $url,
      ]), 'error');
    }
    $form['notify_page_master'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Master switch'),
    ];

    // If user existed before notify was enabled, these are not set in db.
    if (!isset($notify->status)) {
      $notify->status = 0;
      $notify->node = 0;
      $notify->teasers = 0;
      $notify->comment = 0;
    }
    if (\Drupal::service('module_handler')
      ->moduleExists('advanced_help')) {
      $output = theme('advanced_help_topic', [
        'module' => 'notify',
        'topic' => 'users',
      ]);
    }
    else {
      $output = '';
    }
    $form['notify_page_master']['status'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Notify status'),
      '#default_value' => $notify->status,
      '#options' => [
        $this
          ->t('Disabled'),
        $this
          ->t('Enabled'),
      ],
      '#description' => $output . '&nbsp;' . $this
        ->t('The master switch overrides all other settings for Notify.  You can use it to suspend notifications without having to disturb any of your settings under &#8220;Detailed settings&#8221; and &#8220;Subscriptions&#8221;.'),
    ];
    $form['notify_page_detailed'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Detailed settings'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#description' => $this
        ->t('These settings will only be effective if the master switch is set to &#8220;Enabled&#8221;.'),
    ];
    $form['notify_page_detailed']['node'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Notify new content'),
      '#default_value' => $notify->node,
      '#options' => [
        $this
          ->t('Disabled'),
        $this
          ->t('Enabled'),
      ],
      '#description' => $this
        ->t('Include new posts in the notification mail.'),
    ];
    $form['notify_page_detailed']['comment'] = [
      '#type' => 'radios',
      '#access' => \Drupal::service('module_handler')
        ->moduleExists('comment'),
      '#title' => $this
        ->t('Notify new comments'),
      '#default_value' => $notify->comment,
      '#options' => [
        $this
          ->t('Disabled'),
        $this
          ->t('Enabled'),
      ],
      '#description' => $this
        ->t('Include new comments in the notification mail.'),
    ];
    $form['notify_page_detailed']['teasers'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('How much to include?'),
      '#default_value' => $notify->teasers,
      '#options' => [
        $this
          ->t('Title only'),
        $this
          ->t('Title + Teaser/Excerpt'),
        $this
          ->t('Title + Body'),
        $this
          ->t('Title + Body + Fields'),
      ],
      '#description' => $this
        ->t('Select the amount of each item to include in the notification e-mail.'),
    ];
    $set = 'notify_page_nodetype';
    $form[$set] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Subscriptions'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#description' => $this
        ->t('Tick the content types you want to subscribe to.'),
    ];
    $alltypes = \Drupal\node\Entity\NodeType::loadMultiple();
    $enatypes = [];
    foreach (\Drupal\node\Entity\NodeType::loadMultiple() as $type => $object) {
      if ($config
        ->get(NOTIFY_NODE_TYPE . $type)) {
        $enatypes[] = [
          $type,
          $object
            ->label(),
        ];
      }
    }
    if (\Drupal::currentUser()
      ->hasPermission('administer notify queue') || empty($enatypes)) {
      $enatypes = [];
      foreach ($alltypes as $type => $obj) {
        $enatypes[] = [
          $type,
          $obj
            ->label(),
        ];
      }
    }

    //TODO: FIX '_notify_user_has_subscriptions' LATER ON
    $exists = _notify_user_has_subscriptions($userprofile);
    if ($exists) {

      // Custom subscriptions exists, use those.
      foreach ($enatypes as $type) {
        $field = \Drupal::database()
          ->select('notify_subscriptions', 'n')
          ->fields('n', [
          'uid',
          'type',
        ])
          ->condition('uid', $userprofile)
          ->condition('type', $type[0])
          ->execute()
          ->fetchObject();
        $default = $field ? TRUE : FALSE;
        $form[$set][NOTIFY_NODE_TYPE . $type[0]] = [
          '#type' => 'checkbox',
          '#title' => $type[1],
          '#return_value' => 1,
          '#default_value' => $default,
        ];
      }
    }
    else {

      // No custom subscriptions, so inherit default.
      foreach ($enatypes as $type) {
        $form[$set][NOTIFY_NODE_TYPE . $type[0]] = [
          '#type' => 'checkbox',
          '#title' => $type[1],
          '#return_value' => 1,
          '#default_value' => TRUE,
        ];
      }
    }
    $form['uid'] = [
      '#type' => 'value',
      '#value' => $userprofile,
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $uid = $values['uid'];
    \Drupal::database()
      ->delete('notify')
      ->condition('uid', $uid)
      ->execute();
    $id = \Drupal::database()
      ->insert('notify')
      ->fields([
      'uid' => $uid,
      'status' => $values['status'],
      'node' => $values['node'],
      'teasers' => $values['teasers'],
      'comment' => $values['comment'],
    ])
      ->execute();
    $subscriptions = [];

    // Remember that this is a custom subscriber.
    $subscriber = _notify_user_has_subscriptions($uid);
    if (!$subscriber) {
      \Drupal::database()
        ->insert('notify_subscriptions')
        ->fields([
        'uid' => $uid,
        'type' => 'magic custom subscription',
      ])
        ->execute();
    }
    foreach ($values as $key => $value) {
      if (preg_match("/^" . NOTIFY_NODE_TYPE . "/", $key)) {
        $key = substr($key, 17);
        $id = \Drupal::database()
          ->select('notify_subscriptions', 'n')
          ->fields('n', [
          'id',
          'uid',
          'type',
        ])
          ->condition('uid', $uid)
          ->condition('type', $key)
          ->execute()
          ->fetchObject();
        if ($id) {
          $id = $id->id;
          if (!$value) {
            \Drupal::database()
              ->delete('notify_subscriptions')
              ->condition('id', $id)
              ->execute();
          }
        }
        else {
          if ($value) {
            \Drupal::database()
              ->insert('notify_subscriptions')
              ->fields([
              'uid' => $uid,
              'type' => $key,
            ])
              ->execute();
          }
        }
      }
    }
    $this->messenger
      ->addMessage($this
      ->t('Notify settings saved.'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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.
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 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.
UserSettings::$messenger protected property Drupal\Core\Messenger\MessengerInterface definition. Overrides MessengerTrait::$messenger
UserSettings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
UserSettings::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
UserSettings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
UserSettings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UserSettings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
UserSettings::__construct public function Class constructor. Overrides ConfigFormBase::__construct