【问题标题】:Accessing Drupal Entity fields in custom templates访问自定义模板中的 Drupal 实体字段
【发布时间】:2015-07-08 23:29:20
【问题描述】:

首先让我说这是我在 Drupal 的第一个项目,我仍然很困惑,如果我的问题很愚蠢,我深表歉意。

我使用实体 API 在 Drupal 7 中创建了一个自定义实体。自定义实体表示高尔夫球场。

我用过这个教程:http://www.sitepoint.com/series/build-your-own-custom-entities-in-drupal/ 然后我尝试添加一个自定义主题,为此我遵循了这个:https://www.drupal.org/node/1238606

我的回调函数如下所示:

function view_golf_course($id) {
  $courses = entity_load('golf_course', array($id));
  $course = $courses[$id];
  drupal_set_title($course->name);
  $output = entity_view('golf_course', array($course));
  $output += array(
    '#theme'     => 'golf_course',
    '#element'   => $output,
    '#view_mode' => 'full',
    '#language'  => LANGUAGE_NONE,
  );
  return $output;
}

这是我的hook_theme()

function golf_course_theme($existing, $type, $theme, $path) {
  return array(
    'golf_course' => array(
      'variables' => array('element' => null),
      'template' => 'golf_course',
    ),
  );
}

问题是在golf_course.tpl.php我只能这样访问高尔夫球场变量(在这个例子中我将访问地址):

render($element['golf_course']['The Lakes Golf Club']['address']['#markup'])

如您所见,为了访问该地址,我必须使用“The Lakes Golf Club”(这是当前显示的高尔夫球场的名称)作为键,但显然该名称会改变每次我展示不同的高尔夫球场,所以我的问题是:

如何在不使用高尔夫球场名称作为键的情况下访问高尔夫球场属性?

编辑

entity_view() (http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity_view/7) 的文档如下:

返回值

可渲染数组,以实体类型和实体为键 标识符,如果存在则使用实体名称 - 请参阅 实体 ID()。如果没有关于如何查看实体的信息, 返回 FALSE。

那么如何避免数组以实体名称为键呢?如果它是由 id 键入的,那就没问题了,因为我在范围内有 $id 变量。

【问题讨论】:

    标签: drupal drupal-7


    【解决方案1】:

    对于寻找此问题答案的任何人: 如果查询的结果集包含多行,则 entity_view 将创建一个索引为空的数组,如下所示:

    $element['golf_course']['']
    

    现在您可以通过访问['#entity'] 数组来访问结果集中所有行的所有实体字段,如下所示:

    $element['golf_course']['']['#entity'] // all golf courses
    $element['golf_course']['']['#entity'][0] // first golf course in the result set
    $element['golf_course']['']['#entity'][0]['label'] // label of first golf course
    $element['golf_course']['']['#entity'][0]['address'] // address of first golf course
    

    附带说明,如果你的模板是纯 PHP 的,你可以避免使用 entity_view(),你会得到一个更干净的数组(你没有 ['golf_course']['']['#entity'] 部分)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多