pino-8.x-1.2-no-core/modules/member_export/src/Controller/MemberExportController.php

modules/member_export/src/Controller/MemberExportController.php
<?php

namespace Drupal\member_export\Controller;

use Drupal\member\Entity\Member;
use Drupal\Core\Controller\ControllerBase;
use Drupal\taxonomy\Entity\Term;


use Yectep\PhpSpreadsheetBundle\Factory;

/**
 * Provides route responses for the Member Export module.
 */
class MemberExportController extends ControllerBase {

  /**
   * Returns a xlsx file of all members.
   *
   * @return \Symfony\Component\HttpFoundation\StreamedResponse
   */
  public function exportAllMembers() {

    $factory = new Factory();

    $spreadsheet = $factory->createSpreadsheet();

    $sheet = $spreadsheet->getActiveSheet();

    // Get fields for Member entity.
    $entityManager = \Drupal::service('entity_field.manager');
    $fields = $entityManager->getFieldDefinitions('member', 'member');

    // Remove fields which are not shown in sheet.
    unset($fields['uuid'], $fields['vid'], $fields['langcode'], $fields['revision_created'], $fields['revision_user'], $fields['revision_log_message'], $fields['user_id'], $fields['created'], $fields['changed'], $fields['revision_translation_affected'], $fields['default_langcode'], $fields['revision_default']);

    // Set the header row.
    $b = 1;

    foreach ($fields as $field) {

      $sheet->setCellValueByColumnAndRow($b, 1, $field->getLabel());

      $b++;

    }

    // Make header row bold.
    $sheet->getStyle("A1:ZZ1")->getFont()->setBold(TRUE);

    // Get all members.
    $ids = \Drupal::entityQuery('member')->execute();

    $members = Member::loadMultiple($ids);

    // Loop through all members and set the values accordingly.
    $a = 2;

    foreach ($members as $member) {

      $b = 1;

      foreach ($fields as $field_name => $field) {

        $field_type = $field->getType();

        if($field_type == 'entity_reference') {

          $values = $member->get($field_name)->getValue();

          $row = [];

          foreach($values as $value) {

            $term = Term::load($value['target_id']);

            $row[] = $term->label();

          }

          $sheet->setCellValueByColumnAndRow($b, $a, implode(", ", $row));

        } else {

          $sheet->setCellValueByColumnAndRow($b, $a, $member->get($field_name)->value);

        }

        $b++;

      }

      $a++;

    }


    // Create response and necessary headers.
    $response = $factory->createStreamedResponse($spreadsheet, 'Xlsx');

    $response->headers->set('Content-Type', 'application/vnd.ms-excel');
    $response->headers->set('Content-Disposition', 'attachment;filename="members-' . date('Y-m-d') . '.xlsx"');
    $response->headers->set('Cache-Control', 'max-age=0');

    return $response;

  }

}

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

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