You are here

public static function OpignoGroupManagerController::ajaxFormEntityCallback in Opigno group manager 8

Same name and namespace in other branches
  1. 3.x src/Controller/OpignoGroupManagerController.php \Drupal\opigno_group_manager\Controller\OpignoGroupManagerController::ajaxFormEntityCallback()

Form ajax callback.

File

src/Controller/OpignoGroupManagerController.php, line 208

Class

OpignoGroupManagerController
Controller for all the actions of the Opigno group manager app.

Namespace

Drupal\opigno_group_manager\Controller

Code

public static function ajaxFormEntityCallback(&$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If errors, returns the form with errors and messages.
  if ($form_state
    ->hasAnyErrors()) {

    // Add class for displaying form errors in iframe.
    $form['#attributes']['class'][] = 'lp-content-item-errors';
    return $form;
  }
  $entity = $form_state
    ->getBuildInfo()['callback_object']
    ->getEntity();

  // Load image.
  if ($entity
    ->hasField('field_course_media_image')) {
    $image_field = 'field_course_media_image';
  }
  elseif ($entity
    ->hasField('module_media_image')) {
    $image_field = 'module_media_image';
  }
  if ($entity
    ->hasField($image_field)) {
    $media = $entity
      ->get($image_field)->entity;
    $file = isset($media) ? File::load($media
      ->get('field_media_image')->target_id) : NULL;
  }
  $item = [];
  $item['cid'] = $entity
    ->id();
  $item['contentType'] = \Drupal::routeMatch()
    ->getParameter('type');
  $item['entityId'] = $entity
    ->id();
  $item['entityBundle'] = \Drupal::routeMatch()
    ->getParameter('type');
  $item['title'] = $entity
    ->label();
  $item['imageUrl'] = isset($file) && $file ? file_create_url($file
    ->getFileUri()) : self::getDefaultBundleImageUrl($entity
    ->bundle());
  $item['in_skills_system'] = FALSE;
  $item['isMandatory'] = FALSE;
  if ($item['contentType'] == 'ContentTypeModule') {
    $item['in_skills_system'] = $entity
      ->getSkillsActive();
    $group = \Drupal::routeMatch()
      ->getParameter('group');
    $managed_contents = OpignoGroupManagedContent::loadByProperties([
      'group_content_type_id' => 'ContentTypeModule',
      'group_id' => $group
        ->id(),
      'entity_id' => $entity
        ->id(),
    ]);
    if (!empty($managed_contents)) {
      $content = reset($managed_contents);
      $item['isMandatory'] = $content
        ->isMandatory();
    }
  }
  $response
    ->addCommand(new SettingsCommand([
    'formValues' => $item,
    'messages' => \Drupal::messenger()
      ->all(),
  ], TRUE));
  \Drupal::messenger()
    ->deleteAll();
  return $response;
}