【问题标题】:Get the value of a Text field in Drupal custom module获取 Drupal 自定义模块中文本字段的值
【发布时间】:2015-05-19 16:45:32
【问题描述】:

我正在开发一个自定义模块,它允许我创建一个自定义文本字段,我需要在其中插入一个 HTTP 请求的 URL。

我现在唯一想做的就是从文本字段中获取值并显示在节点的某个位置。

这是 .install 代码:

function graph_field_enable() {
  $field = array(
    'field_name' => 'graph_field',
    'type' => 'text',
  );
  field_create_field($field);


/**
   * Bind field to a entity bundle.
   */
  $instance = array(
    'field_name' => $field['field_name'],
    'entity_type' => 'node',
    'bundle' => 'station',
  );
  field_create_instance($instance);
}
/**
 * Implements hook_disable().
 *
 * Remove field from node bundle (content type) and then delete the field.
 */

function graph_field_disable() {
  $instance = array(
    'field_name' => 'graph_field',
    'entity_type' => 'node',
    'bundle' => 'station',
  );
  field_delete_instance($instance);
  field_delete_field($instance['field_name']);
  print 'Removed ' . $instance['field_name'] . "\n";
}

.module 文件只包含:

<?php

我对 Drupal 很陌生,我想我讨厌它。

【问题讨论】:

    标签: php drupal drupal-7 drupal-modules


    【解决方案1】:

    (抱歉,我想帮助充实 Neha Singhania 答案,但还没有足够的代表对此发表评论。)

    如果您还没有表示节点的关联数组,请使用节点 ID 加载它:

    $node = node_load($nid);
    

    一旦你得到了它,你可以使用其中任何一个来访问任何文本字段值,我相信:

    $node->field_textfieldname['und'][0]['value'];
    $node->field_textfieldname[LANGUAGE_NONE][0]['value'];
    

    数组中的第一个键指定什么语言(在这些情况下未定义/无),第二个键/索引表示字段的哪个值(如果您有一个多值字段),第三个是实际的肉和土豆。对于文本字段,您还会看到:

    $node->field_textfieldname[LANGUAGE_NONE][0]['safe_value'];
    

    我相信这是在 node_save($nid) 上创建/更新的,它会清除任何非法/不安全值的值。

    许多字段类型都相同,但并非全部。但是方法是一样的。例如,如果您想要 entity_reference 字段类型的值,它看起来像这样。

    $node->field_entityrferencefieldname['und'][0]['target_id'];
    

    其中 target_id 是它所引用的任何内部实体(节点 ID、用户 ID 等)的整数/ID 编号。我强烈建议安装 devel 模块,它为您提供 dpm() 功能;基本上,它是一个漂亮的 print_r 版本,并且会显示为 Drupal 消息。

    如果您坚持使用 Drupal,您有时会认为自己讨厌它。很多。我知道。但这仍然很值得。 (而且,根据我自己的经验,似乎真的很容易找到工作......)

    另外,这个问题应该可以继续drupal.stackexchange.com

    【讨论】:

      【解决方案2】:

      检查一下:

      $node = node_load( $nid );
      print_r( $node->graph_field );
      

      或者你可以打印整个节点:

      print_r( $node );
      

      【讨论】:

      • 我必须把这段代码放在哪里? $nid 变量是什么?
      • $nid 是节点 ID。放在你想显示graph_field的内容的地方。
      【解决方案3】:

      要以编程方式获取任何节点的信息,请使用节点 ID 加载节点。
      $nid = '1';//这是你站点的第一个节点
      $node_info = node_load($nid);
      print_r($node_info->field_custom_field[LANGUAGE_NONE][0]['value']);//这将打印field_custom_field的值。您可以在此处使用任何字段名称。
      并且直接在 hook_init 函数中检查这些信息进行测试,以后你可以在你想要的地方使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多