arch-8.x-1.x-dev/modules/order/modules/addressbook/arch_addressbook.module

modules/order/modules/addressbook/arch_addressbook.module
<?php
/**
 * @file
 * ARCH Addressbook module file.
 */

use Drupal\arch_addressbook\Entity\AddressbookitemViewBuilder;
use Drupal\arch_addressbook\Services\UserAddressesService;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\Element;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;

/**
 * Implements hook_theme().
 */
function arch_addressbook_theme($existing, $type, $theme, $path) {
  return [
    'addressbookitem' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Prepares variables for addressbookitem templates.
 *
 * Default template: addressbookitem.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An array of elements to display in view mode.
 *   - addressbookitem: The addressbookitem object.
 *   - view_mode: View mode; e.g., 'full', 'teaser', 'address', etc.
 */
function template_preprocess_addressbookitem(array &$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];

  // Provide a distinct $teaser boolean.
  $variables['teaser'] = $variables['view_mode'] === 'teaser';
  $variables['page'] = $variables['view_mode'] === 'full';

  $variables['addressbookitem'] = $variables['elements']['#addressbookitem'];

  /** @var \Drupal\arch_addressbook\AddressbookitemInterface $addressbookitem */
  $addressbookitem =& $variables['addressbookitem'];

  $variables['title'] = $addressbookitem->label();
  if (empty($variables['title'])) {
    $variables['title'] = t('Address', [], ['context' => 'arch_addressbook']);
  }

  $variables['date'] = \Drupal::service('renderer')->render($variables['elements']['created']);
  unset($variables['elements']['created']);

  $variables['display_edit_link'] = TRUE;
  $url = $addressbookitem->toUrl('edit-form', [
    'language' => \Drupal::languageManager()->getCurrentLanguage(),
  ]);
  $query = $url->getOption('query');
  $query['destination'] = \Drupal::destination()->get();
  $url->setOption('query', $query);
  $variables['url'] = $url;

  // Helpful $content variable for templates.
  $variables += ['content' => []];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
    if ($key === 'title') {
      $variables['content'][$key]['#access'] = FALSE;
    }
  }

  // Add article ARIA role.
  $variables['attributes']['role'] = 'article';

  // Default classes for addressbookitem entity.
  $variables['attributes']['class'][] = $addressbookitem->getEntityTypeId();
  $variables['attributes']['class'][] = $addressbookitem->getEntityTypeId() . '-' . $addressbookitem->id();
  $variables['attributes']['class'][] = $addressbookitem->getEntityTypeId() . '--' . $variables['view_mode'];
  $variables['attributes']['class'][] = $addressbookitem->getEntityTypeId() . '--' . $variables['view_mode'] . '-' . $addressbookitem->id();
  $variables['attributes']['class'][] = $variables['view_mode'];
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function arch_addressbook_theme_suggestions_addressbookitem(array $variables) {
  $suggestions = [];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'addressbookitem__' . $sanitized_view_mode;
  $suggestions[] = 'addressbookitem__' . $variables['elements']['#addressbookitem']->bundle();
  $suggestions[] = 'addressbookitem__' . $variables['elements']['#addressbookitem']->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'addressbookitem__' . $variables['elements']['#addressbookitem']->id();
  $suggestions[] = 'addressbookitem__' . $variables['elements']['#addressbookitem']->id() . '__' . $sanitized_view_mode;

  return $suggestions;
}

/**
 * Implements hook_preprocess_page().
 */
function arch_addressbook_preprocess_page(&$variables) {
  $routes = [
    'entity.addressbookitem.collection',
    'entity.addressbookitem.delete_form',
  ];
  if (!in_array(\Drupal::routeMatch()->getRouteName(), $routes)) {
    return;
  }

  $variables['content_attributes']['class'][] = 'col-sm-12';
  $variables['content_attributes']['class'][] = 'addressbookitem-page';

  $variables['page']['sidebar_first'] = [];
  $variables['page']['sidebar_second'] = [];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function arch_addressbook_form_addressbookitem_delete_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#attributes']['class'][] = 'btn-default';
  $form['actions']['submit']['#attributes']['class'][] = 'btn-error';

  $form['actions']['cancel']['#attributes']['class'][] = 'btn-default';
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function arch_addressbook_form_addressbookitem_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  _arch_addressbook_form_alter($form, $form_state, $form_id);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function arch_addressbook_form_addressbookitem_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  _arch_addressbook_form_alter($form, $form_state, $form_id);
}

/**
 * Alters addressbook edit form.
 */
function _arch_addressbook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** @var \Drupal\Core\Session\AccountProxy $current_user */
  $current_user = \Drupal::currentUser();

  // Enable revision log message to edit only for Administrators/Editors.
  $form['user_id']['#access'] = FALSE;
  if (
    in_array('administrator', $current_user->getRoles())
    || in_array('editor', $current_user->getRoles())
    || $current_user->id() == '1'
  ) {
    $form['user_id']['#access'] = TRUE;
  }

  // Enable revision log message to edit only for Administrators/Editors.
  $form['revision']['#access'] = FALSE;
  $form['revision']['#default_value'] = TRUE;
  $form['revision_log']['#access'] = FALSE;
  $form['revision_information']['#access'] = FALSE;
  if (
    in_array('administrator', $current_user->getRoles())
    || in_array('editor', $current_user->getRoles())
    || $current_user->id() == '1'
  ) {
    $form['revision']['#access'] = TRUE;
    $form['revision_log']['#access'] = TRUE;
    $form['revision_information']['#access'] = TRUE;

    $form['revision_log']['widget'][0]['value']['#default_value'] = t('Changes has made by an administrator/editor.', [], ['context' => 'arch_addressbook']);
  }

  $form['actions']['delete']['#attributes']['class'][] = 'btn-default';
  $form['actions']['delete']['#attributes']['class'][] = 'btn-error';
}

/**
 * Implements hook_commerce_shipping_addresses().
 */
function arch_addressbook_commerce_shipping_addresses() {
  $current_user = \Drupal::currentUser();
  // For anonymous users, we do not want to display any existing address.
  if ($current_user->isAnonymous()) {
    return [];
  }

  /** @var \Drupal\arch_addressbook\Services\UserAddressesServiceInterface $address_service */
  $address_service = \Drupal::service('addressbookitem.user_addresses');
  try {
    $addresses = $address_service->getByUser(NULL, TRUE);
  }
  catch (\Exception $e) {
    // @todo log/handle error.
    return [];
  }

  $fields = [
    'organization' => ' | ',
    'country_code' => '-',
    'postal_code' => ' ',
    'locality' => ', ',
    'dependent_locality' => ', ',
    'address_line1' => ' ',
    'address_line2' => ' ',
  ];
  foreach ($addresses as $id => $addressbookitem) {
    $parts = [];
    $addressfields = $addressbookitem->get('address')->first()->getValue();
    foreach ($fields as $field => $suffix) {
      if (
        isset($addressfields[$field])
        && !empty($addressfields[$field])
      ) {
        $parts[] = $addressfields[$field] . $suffix;
      }
    }

    $addresses['addressbookitem:' . $id] = implode('', $parts);
  }

  return $addresses;
}

/**
 * Implements hook_entity_extra_field_info().
 */
function arch_addressbook_entity_extra_field_info() {
  $extra = [];

  $extra['user']['user']['display']['addresses'] = [
    'label' => t('Address book: Addresses'),
    'visible' => FALSE,
  ];

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function arch_addressbook_user_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  /** @var \Drupal\user\UserInterface $entity */
  /** @var \Drupal\arch_addressbook\Services\UserAddressesService $service */
  $addressbook_service = \Drupal::service('addressbookitem.user_addresses');

  /** @var \Drupal\arch_addressbook\Entity\AddressbookitemViewBuilder $view_builder */
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('addressbookitem');

  if ($display->getComponent('addresses')) {
    $build['addresses'] = arch_addressbook_render_addresses($addressbook_service, $view_builder, $entity, $view_mode);
    if (
      isset($build['addresses']['addresses']['#items'])
      && !count($build['addresses']['addresses']['#items'])
    ) {
      $build['addresses']['addnew'] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'add-new',
          ],
        ],
        'actions' => [
          '#type' => 'actions',
          'new' => Link::createFromRoute(
            t('Add new address', [], ['context' => 'arch_addressbook']),
            'addressbookitem.add_to_user',
            ['user' => $entity->id()]
          ),
        ],
      ];
    }
  }
}

/**
 * Render addressbookitem entities with the given address type & view mode.
 *
 * @param \Drupal\arch_addressbook\Services\UserAddressesService $addressbook_service
 *   Addressbook service.
 * @param \Drupal\arch_addressbook\Entity\AddressbookitemViewBuilder $view_builder
 *   Addressbookitem entity view builder.
 * @param \Drupal\Core\Session\AccountInterface $account
 *   Specify account to render addresses for.
 * @param string $view_mode
 *   View mode for the 'addressbookitem' entity.
 *
 * @return array|null
 *   Item list with addresses, or NULL if no address found.
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 */
function arch_addressbook_render_addresses(UserAddressesService $addressbook_service, AddressbookitemViewBuilder $view_builder, AccountInterface $account, $view_mode = 'address') {
  $items = [];
  /** @var \Drupal\arch_addressbook\Entity\Addressbookitem[] $address_ids */
  $addresses = $addressbook_service->getByUser($account, TRUE);
  if (empty($addresses)) {
    return NULL;
  }

  foreach ($addresses as $address) {
    $items[] = $view_builder->view($address, $view_mode);
  }

  return [
    '#type' => 'container',
    '#attributes' => [
      'class' => [
        'addressbook',
      ],
    ],
    'addresses' => [
      '#theme' => 'item_list',
      '#items' => $items,
      '#attributes' => [
        'class' => [
          'addressbookitem',
        ],
      ],
    ],
  ];
}

/**
 * Allowed value function: Values of Addressbookitem country_code field.
 *
 * @return array
 *   List of available countries in the address book.
 */
function arch_addressbook_allowed_values_country_code() {
  $countries = [
    'HU' => t('Hungary'),
  ];

  /** @var \Drupal\Core\Extension\ModuleHandlerInterface $module_handler */
  $module_handler = \Drupal::moduleHandler();

  $countries += $module_handler->invokeAll('addressbook_countries');
  $module_handler->alter('addressbook_countries', $countries);

  return $countries;
}

/**
 * Implements hook_preprocess_menu_local_action().
 */
function arch_addressbook_preprocess_menu_local_action(array &$variables) {
  if (
    !empty($variables['link']['#url'])
    && $variables['link']['#url'] instanceof Url
    && in_array(
      $variables['link']['#url']->getRouteName(),
      ['addressbookitem.add', 'addressbookitem.add_to_user']
    )
  ) {
    $variables['#cache']['contexts'][] = 'url';
    $variables['link']['#cache']['contexts'][] = 'url';
    $variables['element']['#cache']['contexts'][] = 'url';

    /** @var \Drupal\Core\Url $url */
    $url = $variables['link']['#url'];
    $query = $url->getOption('query');
    $query['destination'] = \Drupal::destination()->get();
    $url->setOption('query', $query);
  }
}

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

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