Drupal: визуализировать форму, включая результаты, но не дублировать запрос набора результатов - PullRequest
0 голосов
/ 31 декабря 2010

Цель состоит в том, чтобы отобразить форму со стандартным набором результатов на странице и позволить зрителю отфильтровать результаты на странице при отправке формы. Эта часть работает.

Однако: Если включен набор результатов по умолчанию, то при первоначальной отправке создаются два набора результатов для отображения. Последующие представления формируют только один набор результатов. Помимо этой дополнительной сборки набора результатов, она работает как задумано.

A пара из вопросов задавали вопросы об отображении форм и результатов на той же странице ранее, и есть статья Lullabot для Drupal5.

Вот код, который я сейчас использую (доступен на Github @ example_formandresults.module )

<?php

/**
 * Implementation of hook_menu().
 */
function example_formandresults_menu() {
  $items['example_formandresults'] = array(
    'title' => 'Example: Form and Results',
    'description' => 'Show a form and its results on the same page.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array( 'example_formandresults_form' ),
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  ) ;
  return $items ;
}

/**
 * Form builder function.
 */
function example_formandresults_form(&$form_state = NULL) {
  /* Setting rebuild to true should prevent the results table being built twice. */
  $form_state['rebuild'] = TRUE ;

  if ( is_null($form_state) || !$form_state['submitted'] ) {
    drupal_set_message('Form has not been submitted.');
    /* set default 'since' value to unix timestamp of "one week ago" */
    $form_state['storage']['since'] = strtotime('-1 week');
  }
  else {
    $form_state['storage']['since'] = strtotime($form_state['values']['since']['year'] .'-'. $form_state['values']['since']['month'] .'-'. $form_state['values']['since']['day']);
  }

  $form['since'] = array(
    '#type' => 'date',
    '#title' => t('Since'),
    '#description' => t('Show entries since the selected date.'),
    '#default_value' => array(
      'month' => format_date($form_state['storage']['since'], 'custom', 'n'),
      'day'   => format_date($form_state['storage']['since'], 'custom', 'j'),
      'year'  => format_date($form_state['storage']['since'], 'custom', 'Y'),
    ),
    '#weight' => 5,
  ) ;

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#weight' => 10,
  ) ;

  if ( $form_state['submitted'] ) {
    $form['results'] = array(
      '#value' => example_formandresults_resultstable($form_state),
      '#type' => 'markup',
      '#weight' => 10, // bottom of form
    ) ;
  }

  return $form ;
}

/**
 * Build results table.
 */
function example_formandresults_resultstable($form_state) {
  drupal_set_message('Building results table.', 'status', TRUE);
  dpm($form_state, 'form state');
  $sql = "SELECT uid FROM {users} WHERE login >= %d ORDER BY login";
  $qry = db_query($sql, $form_state['storage']['since']);
  while ( $uid = db_result($qry) ) {
    $account = user_load($uid);
    /* there are plenty of good examples on how to theme tables in
     * forms; this isn't one. 
     */
    $rows[] = array(
      $account->name,
      format_date($account->login),
    ) ;
  }
  // dpm($rows, 'rows');
  $headers = array( 'Name', 'Last Login' );
  $result = t("<h3>Accounts logged in since: %since</h3>", array('%since' => format_date($form_state['storage']['since']))) ;
  $result .= theme('table', $header, $rows) ;
  return $result ;
}

1 Ответ

0 голосов
/ 24 января 2011

Попробуйте проверить счетчик ($ form_state ['values']) или даже $ form_state ['post'], чтобы узнать, была ли отправлена ​​форма.

...