contacts_events-8.x-1.x-dev/modules/teams/c_events_team_app.page.inc

modules/teams/c_events_team_app.page.inc
<?php

/**
 * @file
 * Contains c_events_team_app.page.inc.
 *
 * Page callback for Team application entities.
 */

use Drupal\Core\Field\FieldItemList;
use Drupal\Core\Form\FormState;
use Drupal\Core\Render\Element;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\field\Entity\FieldConfig;
use Drupal\state_machine\Form\StateTransitionForm;

/**
 * Prepares variables for Team application templates.
 *
 * Default template: c_events_team_app.html.twig.
 *
 * Rather than rendering all the fields on the entity, this will prepare
 * variables containing information about the applicant, the questions and
 * references.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the user information and any
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_c_events_team_app(array &$variables) {
  $variables['#attached']['library'][] = 'contacts_events_teams/manage_application';

  // Fetch TeamApplication Entity Object.
  /** @var \Drupal\contacts_events_teams\Entity\TeamApplication $app */
  $app = $variables['elements']['#c_events_team_app'];
  /** @var \Drupal\contacts_events\Entity\TicketInterface|null $ticket */
  $ticket = $app->getTicket();
  $applicant = $app->getOwner();
  /** @var \Drupal\profile\Entity\ProfileInterface $profile */
  $profile = $applicant->profile_crm_indiv->entity;

  // Build up different sections of the team application display.
  // application_summary: a brief summary of the application
  // applicant_details: information on the applicant
  // questions: team app questions and their answers
  // references: reference details
  // other_applications: other applications
  // log: Application status log.
  // footer: Items to display below the tabs.
  $variables['application_summary'] = [
    'event' => ['#markup' => new TranslatableMarkup('Unknown event')],
    'team' => $app->getTeam() ? $app->getTeam()->get('name')->view(['label' => 'inline']) : new TranslatableMarkup('Team has been deleted'),
    'submitted' => $app->get('created')->view(['label' => 'inline']),
    'booking_link' => [],
    'status' => $app->state->view([
      'label' => 'inline',
      'type' => 'list_default',
    ]),
    'dbs_status' => '',
  ];

  if ($ticket) {
    $variables['application_summary']['event'] = $ticket->getEvent()->get('title')->view([
      'label' => 'inline',
    ]);
    $variables['application_summary']['booking_link'] = $ticket->getOrderItem()->get('order_id')->view(['label' => 'inline']);
  }

  // Override titles to make sense in team application context.
  $variables['application_summary']['event']['#title'] = new TranslatableMarkup('Event');
  $variables['application_summary']['submitted']['#title'] = new TranslatableMarkup('Submitted');

  // Only override team title if a team is present. The team might be missing
  // if it's been deleted, in which case the team key won't be an array but
  // a string "Team has been deleted", which is set above.
  if ($app->getTeam()) {
    $variables['application_summary']['team']['#title'] = new TranslatableMarkup('Team');
  }

  $variables['applicant_details'] = [
    'id' => $app->user_id->view([
      'label' => 'inline',
      'type' => 'entity_reference_entity_id',
    ]),
    'dob' => [],
    'email' => [],
    'name' => $app->user_id->entity->label(),
  ];
  if ($ticket) {
    $variables['applicant_details']['dob'] = $ticket->date_of_birth->view([
      'label' => 'inline',
      'settings' => ['format_type' => 'html_date'],
    ]);
    $variables['applicant_details']['ticket'] = $ticket->email->view(['label' => 'inline']);
    $variables['applicant_details']['name'] = $ticket->name->view(['label' => 'hidden']);
  }
  if ($profile) {
    if ($profile->hasField('crm_address')) {
      $variables['applicant_details']['address'] = $profile->crm_address->view(['label' => 'hidden']);
    }
    if ($profile->hasField('crm_gender')) {
      $variables['applicant_details']['gender'] = $profile->crm_gender->view(['label' => 'inline']);
    }
    if ($profile->hasField('crm_photo')) {
      $variables['applicant_details']['image'] = $profile->crm_photo->view([
        'label' => 'hidden',
        'settings' => ['image_style' => 'contacts_small'],
      ]);
    }
  }

  // Replace title for ID.
  $variables['applicant_details']['id']['#title'] = new TranslatableMarkup('User ID');

  $references = [];
  // Don't want all fields from the application, only those that represent
  // questions which will be the config fields rather than the base fields.
  // Exclude references - these will be put in the reference tab.
  foreach (Element::children($variables['elements']) as $key) {
    if (isset($variables['elements'][$key]['#items']) && $variables['elements'][$key]['#items'] instanceof FieldItemList) {
      /** @var \Drupal\Core\Field\FieldItemList $list */
      $list = $variables['elements'][$key]['#items'];
      if ($list->getFieldDefinition()->getType() == 'entity_reference' && $list->getFieldDefinition()->getSetting('target_type') == 'contacts_reference') {
        $references[] = [
          'reference' => $list->entity,
          // Include the field as context for preprocess later.
          'field' => $list->getFieldDefinition(),
        ];
      }
      elseif ($list->getFieldDefinition() instanceof FieldConfig) {
        $variables['questions'][$key] = $variables['elements'][$key];
      }
    }
  }

  if ($app->access('update')) {
    $variables['questions']['edit'] = [
      '#type' => 'link',
      '#title' => new TranslatableMarkup('Edit Application'),
      '#attributes' => ['class' => ['button']],
      '#url' => $app->toUrl('edit-form'),
      '#weight' => 100,
    ];
  }

  // Other team applications for this user.
  $storage = \Drupal::entityTypeManager()->getStorage('c_events_team_app');
  $query = $storage->getQuery();
  $query->accessCheck(TRUE);
  $query->condition('user_id', $applicant->id());
  $query->condition('id', $app->id(), '<>');
  /** @var \Drupal\contacts_events_teams\Entity\TeamApplication[] $other_applications */
  $other_applications = $storage->loadMultiple($query->execute());

  $variables['other_applications'] = [
    '#header' => [
      new TranslatableMarkup('Event'),
      new TranslatableMarkup('Date'),
      new TranslatableMarkup('Team'),
      new TranslatableMarkup('Status'),
      '',
    ],
    '#type' => 'table',
    '#empty' => new TranslatableMarkup('No other applications'),
  ];

  /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
  $date_formatter = \Drupal::service('date.formatter');
  foreach ($other_applications as $other_application) {
    /** @var \Drupal\contacts_events\Entity\EventInterface $event */
    $event = $other_application->get('event')->entity;
    $variables['other_applications']['#rows'][$other_application->id()] = [
      'event' => $event->label(),
      'date' => $date_formatter->format($event->get('date')->start_date->getTimestamp(), 'short'),
      'team' => $other_application->getTeam() ? $other_application->getTeam()->label() : new TranslatableMarkup('Team has been deleted'),
      'status' => $other_application->get('state')->first()->getLabel(),
      'link' => $other_application->toLink(new TranslatableMarkup('View')),
    ];
  }

  if (count($references)) {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('contacts_reference');
    foreach ($references as $reference_array) {
      /** @var \Drupal\contacts_references\Entity\Reference $reference */
      $reference = $reference_array['reference'];
      $variables['references'][$reference->id()] = $view_builder->view($reference);
      $variables['references'][$reference->id()]['#team_app_field'] = $reference_array['field'];
    }
  }

  // Checkout for dbs integration.
  // @todo Should we check if the module is enabled as well?
  if ($app->getTeam() && $app->getTeam()->hasField('dbs_workforce') && $workforce = $app->getTeam()->get('dbs_workforce')->value) {
    /** @var \Drupal\contacts_dbs\DBSManager $dbs_manager */
    $dbs_manager = \Drupal::service('contacts_dbs.dbs_manager');
    /** @var \Drupal\contacts_dbs\DBSStatusStorage $dbs_storage */
    $dbs_storage = \Drupal::entityTypeManager()->getStorage('dbs_status');
    $dbs_statuses = $dbs_manager->getAllDbs($app->getOwnerId(), $workforce);

    $variables['dbs'] = [
      '#header' => [
        new TranslatableMarkup('Status'),
        new TranslatableMarkup('Date'),
        new TranslatableMarkup('Workforce'),
        new TranslatableMarkup('Updated by'),
      ],
      '#type' => 'table',
      '#empty' => new TranslatableMarkup('No DBS history'),
    ];

    if ($dbs_statuses) {
      /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager */
      $entity_field_manager = \Drupal::service('entity_field.manager');
      $definitions = $entity_field_manager->getFieldStorageDefinitions('dbs_status');
      $status_options = options_allowed_values($definitions['status']);

      foreach ($dbs_statuses as $dbs_status) {
        foreach ($dbs_storage->revisionIds($dbs_status) as $revision_id) {
          /** @var \Drupal\contacts_dbs\Entity\DBSStatusInterface $revision */
          $revision = $dbs_storage->loadRevision($revision_id);

          $variables['dbs']['#rows'][$revision->getRevisionId()] = [
            'status' => $status_options[$revision->get('status')->value],
            'date' => $date_formatter->format($revision->getRevisionCreationTime(), 'short'),
            'workforce' => $revision->get('workforce')->entity->label(),
            'updated' => $revision->getRevisionUser() ? $revision->getRevisionUser()
              ->label() : '',
            // Include the raw timestamp as hidden property for sorting.
            '#date' => $revision->getChangedTime(),
          ];
        }
      }

      // Sort the rows by created date descending.
      usort($variables['dbs']['#rows'], function ($a, $b) {
        return $b['#date'] <=> $a['#date'];
      });

      // Set the status in the summary.
      $variables['application_summary']['dbs_status'] = [
        '#type' => 'item',
        '#title' => new TranslatableMarkup('DBS Status'),
        '#markup' => $variables['dbs']['#rows'][0]['status'],
      ];
    }
  }

  $variables['log'] = $variables['elements']['status_log'];

  // Render state transition form as team leaders dont have entity update
  // permission.
  // @see \Drupal\state_machine\Plugin\Field\FieldFormatter\StateTransitionFormFormatter::viewElements
  $state_form = $variables['elements']['state'];
  /** @var \Drupal\state_machine\Form\StateTransitionFormInterface $form_object */
  $form_object = \Drupal::classResolver()->getInstanceFromDefinition(StateTransitionForm::class);
  $form_object->setEntity($app);
  $form_object->setFieldName('state');
  $form_state = new FormState();
  $state_form = \Drupal::formBuilder()->buildForm($form_object, $form_state);

  $variables['footer']['state'] = $state_form;
}

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

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