无法在Drupal 7

时间:2017-02-05 18:03:11

标签: drupal drupal-7 drupal-views

我使用模块为View创建了自定义字段。为了更好地在这里可视化,我简化了它:自定义字段只生成1到10之间的随机数。

我想“排序”这个随机数。但是,在Views:

中使用此设置时收到以下错误

SQLSTATE [42S22]:找不到列:1054'字段列表'中的未知列'my_custom_field'

我正在努力在我的代码中找到错误。

感谢您在我的模块代码中提供的任何帮助!!

以下是我的文件:

my_custom_module.info

name = My Custom Module
description = Implement random number in views.
core = 7.x
files[] = includes/views_handler_my_custom_field.inc

my_custom_module.module

<?php
/**
 * Implements hook_views_api().
 */
function my_custom_module_views_api() {
  return array(
    'api' => 3,
  );
}

my_custom_module.views.inc

<?php
/**
 * Implements hook_views_data().
 */
function my_custom_module_views_data() {
  $data['my_custom_module']['table']['group'] = t('My custom module');
  $data['my_custom_module']['table']['join'] = array(
    // Exist in all views.
    '#global' => array(),
  );

  $data['my_custom_module']['my_custom_field'] = array(
    'title' => t('My custom field'),
    'help' => t('My custom field displays a random number.'),
    'field' => array(
      'handler' => 'views_handler_my_custom_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
  );

  return $data;
}

views_handler_my_custom_field.inc

<?php
/**
 * @file
 * Custom views handler definition.
 */

/**
 * Custom handler class.
 *
 * @ingroup views_field_handlers
 */
class views_handler_my_custom_field extends views_handler_field {
  /**
   * {@inheritdoc}
   *
   * Perform any database or cache data retrieval here. In this example there is
   * none.
   */
  function query() {

  }

  /**
   * {@inheritdoc}
   *
   * Modify any end user views settings here. Debug $options to view the field
   * settings you can change.
   */
  function option_definition() {
    $options = parent::option_definition();
    return $options;
  }

  /**
   * {@inheritdoc}
   *
   * Make changes to the field settings form seen by the end user when adding
   * your field.
   */
  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
  }

  /**
   * Render the random field.
   */
  public function render($values) {
    $random = rand(1, 10);
    return $random;
  }
}

1 个答案:

答案 0 :(得分:0)

简短回答:没有合适的数据库字段,您无法对视图进行排序。

更长的答案:hook_views_data()的主要目的是向Views描述数据库表。您确实使用'#global' => array()显示了数据库中并不存在的字段,但由于该特定字段不是SQL查询的一部分,您根本无法对其进行排序。甚至在views_handler_my_custom_field->render()方法中获得的随机数的值也是在视图生成并执行SQL查询之后生成的,在所有排序已经发生的时刻。