Информация о покупателе при генерации PDF [РЕШЕНО]

Главные вкладки

Аватар пользователя KIREAL KIREAL 8 июля 2015 в 4:20

Для небольшого сервиса регистрации на мероприятия необходима печать пригласительных.
Реализовано это через модули:
- commerce -выбор мероприятия
- customer-profiles -собираю дополнительную информацию
- Commerce Event Ticket -высылаю билеты в pdf
По дефолту на пригласительном очень мало информации(картинка в приложении).
Необходимо вставить данные, которые введены в поля customer-profiles
они хранятся в commerce_customer_custuser_profile_id['fields']

Вопрос следующий - как передать значения из commerce_customer_custuser_profile_id в скрипт генерации приглашения?

Для создания PDF используется скрипт:

<?php
/**
 * file
 * Theme functions for the Commerce Event Ticket PDF module.
 */

/**
 * Preprocess function for theming the information on an event ticket PDF.
 */

function template_preprocess_commerce_event_ticket_pdf_info(&$variables) {
  
$ticket $variables['ticket'];
  
$order commerce_order_load($ticket->order_id);
  
$product commerce_product_load($ticket->product_id);
  
$owner user_load($order->uid);
  
$node node_load($ticket->nid);
  
  
  if (
$node) {
    
$variables['nid'] = $node->nid;
    
$variables['node_title'] = check_plain($node->title);
    
$variables['node_path'] = 'node/' $node->nid;
    
$node_products_count commerce_event_ticket_count_node_products($node);
    global 
$base_url;
    if (
$base_url && ($domain parse_url($base_urlPHP_URL_HOST))) {
      
$variables['node_shortlink'] = $domain base_path() . $variables['node_path'];
    }
  }

  

$variables['display_product_title'] = !$node || ($node_products_count && $product->title != $node->title);
  
$variables['product_title'] = check_plain($product->title);

  

$variables['data'] = array(
    
t('Order number') => $order->order_number,
    
t('Order date') => format_date($order->created),
    
t('Customer') => format_username($owner),
    
t('Тестовый текст') => $name,
  );

  

$unit_price commerce_event_ticket_get_unit_price($ticket);
  if (
$unit_price) {
    
$variables['data'][t('Unit price')] = $unit_price;
  }
}

/**
 * Theme the information on an event ticket PDF.
 */
function theme_commerce_event_ticket_pdf_info($variables) {
  
$output = array();
  
$output['title'] = array(
    
'#prefix' => '<h1>',
    
'#suffix' => '</h1>',
    
'#markup' => t('БИЛЕТ'),
  );
  if (isset(
$variables['nid'])) {
    
$output['subtitle'] = array(
      
'#prefix' => '<h2>',
      
'#suffix' => '</h2>',
      
'#markup' => $variables['node_title'],
    );
    if (isset(
$variables['node_shortlink'])) {
      
$output['shortlink'] = array(
        
'#prefix' => '<p>',
        
'#suffix' => '</p>',
        
'#markup' => l(
          
$variables['node_shortlink'],
          
$variables['node_path'],
          array(
'absolute' => TRUE'html' => TRUE)
        ),
      );
    }
  }
  if (
$variables['display_product_title']) {
    
$output['product_title'] = array(
      
'#prefix' => '<p>',
      
'#suffix' => '</p>',
      
'#markup' => t('Product: !title', array('!title' => $variables['product_title'])),
    );
  }
  
$rows = array();
  foreach (
$variables['data'] as $label => $value) {
    
$rows[] = array('<strong>' $label '</strong>'$value);
  }
  
$output['table'] = array(
    
'#theme' => 'table',
    
'#header' => array(),
    
'#rows' => $rows,
    
'#attributes' => array(
      
'cellpadding' => '10',
    ),
  );
  return 
drupal_render($output);
}
?>

При помощи связей во views я получил полный/требуемый вывод данных, но не знаю как это сделать в скрипте выше.

ВложениеРазмер
Иконка изображения ticket_0.png27.84 КБ

Комментарии

Аватар пользователя Orion76 Orion76 8 июля 2015 в 7:14

Непонятно в чем трудности.
В $variables "скрипта" (на самом деле это стандартный hook_preprocess функции темизации)
скорее всего всего есть идентификаторы пользователя или его "профиля".
"Загрузите" необходимые данные и работайте с ними.
Пользователь "грузиться" функцией user_load($uid) ($uid - идентификатор пользователя).
Customer profile скорее всего грузиться функцией что-то типа customer_profile_load($cid), посмотрите как это делается в самом модуле (customer profile).

В некоторых случаях для подобного можно использовать функцию entity_load('тип сущности','идентификатор сущности').

Аватар пользователя KIREAL KIREAL 10 июля 2015 в 0:40

Описываю решение
В файле отвечающем за вывод шаблона html, который позже будет превращен в pdf
www\sites\all\modules\commerce_event_ticket\modules\pdf\includes\commerce_event_ticket_pdf.theme.inc
получаем массив с значениями переменных customer_profile при помощи сущностей
в функции template_preprocess_commerce_event_ticket_pdf_info(&$variables)

<?php
$query 
= new EntityFieldQuery();
$query->entityCondition('entity_type''commerce_customer_profile')
  ->
propertyCondition('uid'$order->uid);

$results $query->execute();

if (!empty(

$results['commerce_customer_profile'])) {
  
$profiles commerce_customer_profile_load_multiple(array_keys($results['commerce_customer_profile']));
  
  foreach (
$profiles as $profile) {
// тут можно поработать с массивом
  
}
  }
?>

Получаем значения необходимых полей
<?php$variables['name'] = check_plain($profile->field_name[LANGUAGE_NONE][0]['value']);?>
знаю, что лучше через field_get_items, но не умею (буду благодарен если подскажете как исправить)
Выводим поля в шаблон html
в функции theme_commerce_event_ticket_pdf_info($variables) вводим поля в массив $output

<?php
  
if ($variables['name']) {
    
$output['name'] = array(
      
'#prefix' => '<p>',
      
'#suffix' => '</p>',
      
'#markup' => $variables['name'],
    );
  }
?>

Если есть ошибки,исправлю.