You are here

function opigno_learning_path_form_alter in Opigno Learning path 8

Same name and namespace in other branches
  1. 3.x opigno_learning_path.module \opigno_learning_path_form_alter()

Implements hook_form_alter().

File

./opigno_learning_path.module, line 1189
Contains opigno_learning_path.module.

Code

function opigno_learning_path_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $build_info = $form_state
    ->getBuildInfo();
  $route_name = \Drupal::routeMatch()
    ->getRouteName();
  if ($form_id == 'opigno_module_edit_form' || $form_id == 'opigno_module_add_form' || $form_id == 'opigno_module_form') {
    $form['created']['#access'] = FALSE;
    $form['uid']['#access'] = FALSE;
  }

  // Check if there is an entry with the key "learning_path_id".
  $is_learning_path = FALSE;
  foreach ($build_info['args'] as $info_value) {
    if (is_array($info_value) && array_key_exists('learning_path_info', $info_value)) {
      $is_learning_path = TRUE;
      break;
    }
  }

  // If the form is from the learning_path_manager and has an entity,
  // ajaxify it.
  if ($is_learning_path && method_exists($build_info['callback_object'], 'getEntity')) {

    // Get the entity.
    $entity = $build_info['callback_object']
      ->getEntity();
    $entity_type = $entity
      ->getEntityTypeId();
    $bundle = $entity
      ->bundle();
    $id = $entity
      ->id();

    // Add form class for ajaxification. In case of add form,
    // append "new" instead of the entity ID.
    if ($id) {
      $ajax_id = 'ajax-form-entity-' . $entity_type . '-' . $bundle . '-' . $id;
    }
    else {
      $ajax_id = 'ajax-form-entity-' . $entity_type . '-' . $bundle . '-new';
    }
    $form['#attributes']['class'][] = $ajax_id;

    // Ajaxification settings of the buttons.
    $ajax_settings = [
      'callback' => 'Drupal\\opigno_learning_path\\Controller\\LearningPathManagerController::ajaxFormEntityCallback',
      'wrapper' => $ajax_id,
      'effect' => 'fade',
    ];
    $form['#attached']['library'][] = 'opigno_learning_path/ajax_form';
    $form['actions']['submit']['#ajax'] = $ajax_settings;
    $form['actions']['publish']['#ajax'] = $ajax_settings;
    $form['actions']['unpublish']['#ajax'] = $ajax_settings;
    $form['actions']['preview']['#access'] = FALSE;
    unset($form['actions']['publish']['#dropbutton']);
    unset($form['actions']['unpublish']['#dropbutton']);

    // Ajaxify the buttons.
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'Drupal\\opigno_learning_path\\Controller\\LearningPathManagerController::ajaxFormEntityFormSubmit';
      }
    }

    // Handle case of entity edition : define the options.
    if ($id) {
      $current_path = \Drupal::service('path.current')
        ->getPath();
      $path_args = explode('/', $current_path);

      // Case of edit link.
      if ($path_args[1] == 'ajax-form-entity') {
        $view_mode = $path_args[5];
        $reload = FALSE;
      }
      else {
        $view_mode = 'default';
        $reload = 'reload_entity';
      }
    }
    else {
      $view_mode = 'default';
      $reload = TRUE;
    }

    // Add all configurations to the form to make it available everywhere.
    $form['ajax_form_entity'] = [
      '#type' => 'hidden',
      '#value' => [
        'view_mode' => $view_mode,
        'reload' => $reload,
        'content_selector' => '.' . $ajax_id,
        'form_selector' => '.' . $ajax_id,
      ],
    ];
  }

  // Set fields visibility dependencies.
  if (in_array($form_id, [
    'group_learning_path_add_form',
    'group_learning_path_edit_form',
  ])) {
    $form['field_requires_validation']['#states'] = [
      'visible' => [
        ':input[name="field_learning_path_visibility"]' => [
          'value' => 'semiprivate',
        ],
      ],
    ];
    $form['field_anonymous_visibility']['#states'] = [
      'visible' => [
        ':input[name="field_learning_path_visibility"]' => [
          'value' => 'semiprivate',
        ],
      ],
    ];
    $form['field_certificate_expire_results']['#states'] = [
      'visible' => [
        ':input[name="field_certificate_expire[value]"]' => [
          'checked' => TRUE,
        ],
      ],
    ];
    unset($form["field_certificate_expire_results"]["widget"]["#options"]["_none"]);

    // Change the submit button title.
    $form['actions']['submit']['#value'] = t('Next');

    // Add redirect to the step 2.
    $form['actions']['submit']['#submit'][] = 'opigno_learning_path_add_form_redirect';

    // Unpublish existing training.
    if ($route_name == 'entity.group.edit_form') {
      $group = \Drupal::routeMatch()
        ->getParameter('group');
      $state = $group
        ->get('field_learning_path_published')->value;
      if ($state == 0) {
        $title = t('Publish');
        $route = 'opigno_learning_path.manager.publish';
      }
      else {
        $title = t('Unpublish');
        $route = 'opigno_learning_path.manager.unpublish';
      }
      $form['actions']['submit']['unpublish'] = [
        '#type' => 'link',
        '#title' => $title,
        '#url' => Url::fromRoute($route, [
          'group' => $group
            ->id(),
        ]),
        '#attributes' => [
          'class' => [
            'button',
          ],
        ],
        '#weight' => 2,
      ];
    }

    // Remove field if opigno_commerce module is disabled.
    if (isset($form['field_lp_price'])) {
      $moduleHandler = \Drupal::service('module_handler');
      if (!$moduleHandler
        ->moduleExists('opigno_commerce')) {
        unset($form['field_lp_price']);
      }
    }

    // Add validation for field.
    if (isset($form['field_required_trainings'])) {
      $form['field_required_trainings']['#element_validate'] = [
        'opigno_learning_path_field_required_trainings_validate',
      ];
    }
  }

  // Set title for learning path step 1.
  if ($form_id === 'group_learning_path_add_form') {
    $form['#title'] = t('Create training');
  }

  // Add custom submit callback to join/leave group form.
  if (in_array($form_id, [
    'group_content_learning_path-group_membership_group-join_form',
    'group_content_learning_path-group_membership_group-leave_form',
  ])) {
    $group = \Drupal::routeMatch()
      ->getParameter('group');
    if ($form_id == 'group_content_learning_path-group_membership_group-join_form') {
      $visibility = $group->field_learning_path_visibility->value;

      // Check if we need to wait validation.
      $validation = LearningPathAccess::requiredValidation($group);
      if ($visibility === 'semiprivate' && $validation) {

        // User message.
        $form['user_message'] = [
          '#type' => 'textarea',
          '#title' => t('Request message'),
          '#description' => t('You can enter 200 symbols.'),
          '#attributes' => [
            'maxlength' => 200,
          ],
        ];
      }
    }

    // Save group object for submit function.
    $form_state
      ->setFormState([
      'group' => $group,
    ]);
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {

        // Unset path alias field.
        unset($form['path']);

        // Add custom submit to user join group form.
        $form['actions'][$action]['#submit'][] = 'opigno_learning_path_group_membership_form_submit';

        // Change submit button text.
        $form['actions'][$action]['#value'] = t('Join training');
      }
    }

    // Cancel link.
    unset($form['actions']['cancel']);
    $url = Url::fromRoute('entity.group.canonical', [
      'group' => $group
        ->id(),
    ], [
      'attributes' => [
        'class' => 'button',
      ],
    ]);
    $link = Link::fromTextAndUrl(t('Cancel'), $url)
      ->toRenderable();
    $form['actions']['submit']['#suffix'] = render($link);
  }
  if ($form_id === 'group_content_learning_path-group_membership_edit_form') {

    /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
    $form_object = $form_state
      ->getFormObject();

    /** @var \Drupal\group\Entity\GroupContentInterface $membership */
    $membership = $form_object
      ->getEntity();
    if ($membership) {
      $status = LearningPathAccess::getMembershipStatus($membership
        ->id());
      $access = $membership
        ->getGroup()
        ->hasPermission('administer members', \Drupal::currentUser());
    }
    $form['user_status'] = [
      '#type' => 'radios',
      '#title' => t('Status'),
      '#options' => LearningPathAccess::getMembershipStatusesArray(),
      '#required' => TRUE,
      '#default_value' => !empty($status) ? $status : '',
      '#weight' => $form['group_roles']['#weight'] - 1,
      '#access' => !empty($access),
    ];
    unset($_SESSION['opigno_learning_path_group_membership_edit']);
    $form['#validate'][] = '_opigno_learning_path_group_membership_edit_form_validate';
  }
  if (in_array($form_id, [
    'group_content_learning_path-group_membership_add_form',
    'group_content_opigno_class-group_membership_add_form',
  ])) {
    $is_class = $form_id == 'group_content_opigno_class-group_membership_add_form';
    unset($form['entity_id']);
    unset($form['path']);
    unset($form['actions']);
    unset($form['#validate']);
    unset($form['#submit']);
    if (!$is_class) {
      unset($form['group_roles']);
    }

    // Get the current learning path group.

    /** @var \Drupal\group\Entity\Group $group */
    $group = \Drupal::routeMatch()
      ->getParameter('group');
    $form['#title'] = $is_class ? t('Members in class') : t('Members in learning path');
    $form['btn_create'] = Link::createFromRoute(t('Create new users'), 'opigno_learning_path.membership.create_member', [
      'group' => $group
        ->id(),
    ])
      ->toRenderable();
    $form['btn_create']['#attributes']['class'][] = 'use-ajax';
    $form['btn_create']['#attributes']['class'][] = 'btn';
    $form['btn_create']['#attributes']['class'][] = 'btn-success';
    $form['btn_create']['#attributes']['data-dialog-type'] = 'modal';
    $form['btn_create']['#attributes']['data-dialog-options'] = json_encode([
      'dialogClass' => 'modal-dialog-sidebar',
    ]);
    $form['training_users_autocomplete'] = [
      '#type' => 'textfield',
      '#title' => $is_class ? t('Find existing users') : t('Find existing users or groups'),
      '#autocomplete_route_name' => 'opigno_learning_path.membership.add_user_to_training_autocomplete',
      '#autocomplete_route_parameters' => [
        'group' => $group
          ->id(),
      ],
      '#placeholder' => t('Enter a user’s name or email'),
      '#attributes' => [
        'id' => 'training_users_autocomplete',
      ],
    ];
    $form['training_users'] = [
      '#type' => 'multiselect',
      '#attributes' => [
        'id' => 'training_users',
        'class' => [
          'row',
        ],
      ],
      '#options' => [],
      // Allow modifying option with AJAX.
      '#validated' => TRUE,
      // Fixes multiselect issue 2852654.
      '#process' => [
        [
          'Drupal\\multiselect\\Element\\MultiSelect',
          'processSelect',
        ],
      ],
    ];
    if ($is_class) {
      $form['group_roles_fieldset'] = [
        '#type' => 'fieldset',
      ];
      $form["group_roles"]["#group"] = 'group_roles_fieldset';
    }
    $form['send_message'] = [
      '#type' => 'checkbox',
      '#title' => t('Notify user ?'),
    ];
    $form['message'] = [
      '#type' => 'textarea',
      '#placeholder' => $is_class ? t('You were added to "@group" class', [
        '@group' => $group
          ->label(),
      ]) : t('I invite you to take part in my learning program to boost your skills'),
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => t('Send invitation'),
    ];
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $form['#attached']['library'][] = 'opigno_learning_path/member_add';
    $form['#attached']['library'][] = 'opigno_learning_path/create_member';
    $form['#attached']['drupalSettings']['opigno_learning_path']['gid'] = $group
      ->id();
    $form['#validate'] = [];
    $form['#submit'] = [
      'opigno_learning_path_group_membership_add_form_submit',
    ];
  }
  if (in_array($form_id, [
    'entity_browser_media_entity_browser_badge_images_form',
    'entity_browser_media_entity_browser_groups_form',
    'entity_browser_media_entity_browser_file_pdf_form',
  ])) {
    $form["#attached"]['library'][] = 'opigno_learning_path/opigno_dropzonejs_widgets';
  }
  if (in_array($form_id, [
    'opigno_moxtra_score_meeting_form',
    'opigno_ilt_create_result_form',
    'opigno_ilt_score_form',
    'opigno_moxtra_create_meeting_result_form',
  ])) {

    // Attach addition styles for entity forms in embedded html page.
    $form["#attached"]['library'][] = 'opigno_learning_path/iframe_opigno_lp_manager';
  }
}