rc-1.0.x-dev/modules/rc_group/src/Form/GroupsChatSettingsForm.php

modules/rc_group/src/Form/GroupsChatSettingsForm.php
<?php

namespace Drupal\rc_group\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;

/**
 * Class GroupsChatSettingsForm.
 */
class GroupsChatSettingsForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'groups_chat_settings';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $config = $this->config('rc_group.settings');

    $form['#tree'] = TRUE;

    $form['groups_settings'] = [
      '#type' => 'details',
      '#title' => t('Group settings'),
      '#open' => TRUE,
      '#attributes' => [
        'id' => 'rc-group-settings',
      ],
    ];

    $form['groups_settings']['auto_create_room'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Automatically create a new Rocket chat channel when a new group is created.'),
      '#default_value' => ($config->get('group.auto_create_room')) ?? TRUE,
    ];

    $form['groups_settings']['auto_update_room'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Automatically create a new Rocket chat channel when a group is updated.'),
      '#default_value' => ($config->get('group.auto_update_room')) ?? TRUE,
    ];

    // @todo creat chatrooms and add members when cron is run.
    //   $form['groups_settings']['create_rooms_cron'] = [
    //      '#type' => 'checkbox',
    //      '#title' => $this->t('Create chat rooms while running maintenance tasks.'),
    //      '#description' => $this->t('Use this option to allow creating chat rooms while running cron job.'),
    //      '#default_value' => ($config->get('user.create_group_cron')) ?? TRUE,
    //    ];
    //
    //    $form['groups_settings']['update_rooms_cron'] = [
    //      '#type' => 'checkbox',
    //      '#title' => $this->t('Update chat rooms while running maintenance tasks.'),
    //      '#description' => $this->t('Use this option to allow updating chat rooms while running cron job.'),
    //      '#default_value' => ($config->get('user.update_user_cron')) ?? TRUE,
    //    ];
    // @todo Will be implemented when action to add users to group.
    //   $form['groups_settings']['auto_add_members'] = [
    //      '#type' => 'checkbox',
    //      '#title' => $this->t('Automatically add group members to channel.'),
    //      '#default_value' => ($config->get('groups_settings.auto_add_members')) ?? TRUE,
    //    ];
    $form['groups_settings']['visibility_room_id_form'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Show the Rocket Chat Room ID at the group edit form'),
      '#default_value' => ($config->get('group.visibility_room_id_form')) ?? FALSE,
    ];

    $form['group_chat_types'] = [
      '#type' => 'details',
      '#title' => t('Chat channels per group type options'),
      '#open' => TRUE,
      '#attributes' => [
        'id' => 'rc-basic-config',
      ],
    ];

    $form['group_chat_types']['all_groups'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('All group types will have chat channels'),
      '#default_value' => $config->get('group_chat_types.all') ?? FALSE,
      '#attributes' => [
        'id' => 'rc-all-groups',
      ],
    ];

    $groupList = $this->groupsList();

    $form['group_chat_types']['group_types'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Select group types that will have chat channels.'),
      '#description' => $this->t('Select the group types that you want the chat to be used with, USE WITH CAUTIOUS, disabling the group type will permanently delete the chat channel associated with the group type that is not sellected.'),
      '#options' => $groupList,
      '#default_value' => $config->get('group_chat_types.types') ?? [],
      '#states' => [
        'visible' => [
          '#rc-all-groups' => ['unchecked' => TRUE],
        ],
      ],
    ];

    // Generating forms for each group type to have owner and moderator roles.
    $groupTypesConfig = $config->get('group_chat_types.types');

    if ($config->get('group_chat_types.all') == TRUE) {
      $groupTypesConfig = $this->groupsList();
    }

    if ($groupTypesConfig) {

      $rcRoleTypes = $this->rcGroupRoles();

      foreach ($rcRoleTypes as $rcRoleType => $rcRoleLabel) {
        $form[$rcRoleType] = [
          '#type' => 'details',
          '#title' => t('Group chat ' . $rcRoleLabel . ' roles'),
          '#description' => t('Select the group roles that you want them to have ' . $rcRoleLabel . ' role on the chat group.'),
          '#open' => TRUE,
        ];

        foreach ($groupTypesConfig as $groupType => $groupLabel) {

          if ($groupLabel != '0') {
            $form[$rcRoleType][$groupType] = [
              '#type' => 'checkboxes',
              '#title' => $this->t($groupLabel . ' roles'),
              '#options' => $this->groupRoles($groupType),
              '#default_value' => $config->get($rcRoleType . '.' . $groupType) ?? [],
            ];

          }
        }
      }

    }

    // @todo update group members to sync the roles with Rocket Chat group roles.
    //   $form['update_groups'] = [
    //      '#type' => 'submit',
    //      '#value' => t('Save and update all groups and members'),
    //      '#submit' => [$this, 'update_groups'],
    //    ];
    // @todo Groups chat operations to create channels for existing groups that don't have channels.
    //   $form['group_types_operations'] = [
    //      '#type' => 'details',
    //      '#title' => t('Groups chat operations'),
    //      '#open' => TRUE,
    //      '#attributes' => [
    //        'id' => 'rc-groups-chat-operations',
    //      ],
    //    ];
    //    // Generating submit action per activated group type.
    //    // Get the selected bundles.
    //    $bundles = $config->get('chat-groups.types');
    //    // If "All" is selected, get all bundels.
    //    $groupTypesAll = $config->get('chat-groups.all');
    //    // Use all existing bundles if all is selected.
    //    if ($groupTypesAll) {
    //      $bundles = [];
    //      $groupsList = $this->groupsList();
    //      foreach ($groupsList as $key => $value) {
    //        $bundles[$key] = 1;
    //      }
    //    }
    //
    //    foreach ($bundles as $bundle => $value) {
    //      // Create field_rc_room_id and attach it to group types.
    //
    //      if ($value == 1) {
    //
    //
    //      }
    //    }
    return parent::buildForm($form, $form_state);
  }

  /**
   *
   */
  public function groupsList(): array {
    $list = [];
    $bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('group');
    foreach ($bundles as $key => $bundle) {
      $list[$key] = $bundle['label'];
    }

    return $list;

  }

  /**
   *
   */
  public function rcGroupRoles(): array {
    return [
      'groups_admin_roles' => 'Owner',
      'groups_moderator_roles' => 'Moderator',
    ];
  }


  /**
   * @param $groupType
   *
   * @return array
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function groupRoles($groupType): array {
    $groupRoles = (array) \Drupal::entityTypeManager()
      ->getStorage('group_role')
      ->loadByProperties([
        'group_type' => $groupType,
        'internal' => FALSE,
      ]);
    $roles = [];
    foreach ($groupRoles as $roleId => $roleLabel) {
      $roles[$roleId] = $roleLabel->label();
    }

    return $roles;
  }

  // @todo update group members to sync the roles with Rocket Chat group roles.
  //   public function update_groups(array &$form, FormStateInterface $form_state) {
  //
  //  }

  /**
   * {@inheritdoc}
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    // Get the original configurations to check the room ID fields in group
    // types. This will help escape the previously created fields.
    $config = $this->config('rc_group.settings');
    $bundlesConfig = $config->get('group_chat_types.types');

    // Get the form fields values.
    $values = $form_state->getValues();

    // Load the RcGroup service.
    $rcGroup = \Drupal::service('rc_group.group');

    // Get all_groups value to update the config.
    $groupTypesAll = $values['group_chat_types']['all_groups'];
    $bundles = $values['group_chat_types']['group_types'];

    // Use all existing bundles if all is selected.
    if ($groupTypesAll) {
      $bundles = [];
      $groupsList = $this->groupsList();
      foreach ($groupsList as $key => $value) {
        $bundles[$key] = $value;
      }
      // Updating the value of group types to have them all.
      $form_state->setValue(['group_chat_types', 'group_types'], $bundles);
    }



    foreach ($bundles as $bundle => $value) {

      // Escape field if it's already created and set in config.
      if (isset($bundlesConfig) && in_array($value, $bundlesConfig)) {
        continue;
      }
      // Create field_rc_room_id and attach it to group types.
      if ($value) {

        $rcGroup->createRcRoomIdField('group', $bundle, 'field_rc_room_id', 'Room ID');
      }
      else {
        $field = FieldConfig::loadByName('group', $bundle, 'field_rc_room_id');
        if (isset($field)) {

          // @todo delete all Rocket chat channels associated with group type.
          // Deleting the Room ID field.
          FieldConfig::loadByName('group', $bundle, 'field_rc_room_id')
            ->delete();
          \Drupal::messenger()->addStatus('The Room ID field has been removed from ' . $bundle . ' group type.');

        }
      }
      $this->configFactory()->getEditable('rc_group.settings')
        ->set('group_chat_types.types.' . $bundle, $value)
        ->save();
    }

    if(isset($values['groups_admin_roles'])){
      foreach ($values['groups_admin_roles'] as $adminGroup => $adminRoles) {
        foreach ($adminRoles as $adminRole => $value) {
          $this->configFactory()->getEditable('rc_group.settings')
            ->set('groups_admin_roles.' . $adminGroup . '.' . $adminRole, $value)
            ->save();
        }
      }
    }

    if(isset($values['groups_moderator_roles'])){
      foreach ($values['groups_moderator_roles'] as $moderatorGroup => $moderatorRoles) {
        foreach ($moderatorRoles as $moderatorRole => $value) {
          $this->configFactory()->getEditable('rc_group.settings')
            ->set('groups_moderator_roles.' . $moderatorGroup . '.' . $moderatorRole, $value)
            ->save();
        }
      }
    }

    $this->configFactory()->getEditable('rc_group.settings')
      ->set('group.auto_create_room', $values['groups_settings']['auto_create_room'])
      ->set('group.auto_update_room', $values['groups_settings']['auto_update_room'])
      // @todo creat chatrooms and add members when cron is run.
    //   ->set('groups_settings.create_rooms_cron', $values['groups_settings']['create_rooms_cron'])
    //      ->set('groups_settings.update_rooms_cron', $values['groups_settings']['update_rooms_cron'])
      // @todo Groups chat operations to create channels for existing groups that don't have channels.
      // ->set('groups_settings.auto_add_members', $values['groups_settings']['auto_add_members'])
      ->set('group.visibility_room_id_form', $values['groups_settings']['visibility_room_id_form'])
      ->set('group_chat_types.all', $groupTypesAll)
      ->save();

  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc