6

我正在尝试使用 Drupal 7 的实体和字段 API 来正确构建一个新模块。我从文档中无法理解的是使用新 API 创建具有多个设置字段的“内容类型”(不是节点类型)的正确方法,例如 Body。

我正在尝试使用 hook_entity_info 设置实体,然后我相信我需要使用 field_create_instance 添加正文字段,但我似乎无法让它工作。

在 mycontenttype.module 中:

/**
 * Implements hook_entity_info().
 */
function mycontenttype_entity_info() {
  $return = array(
    'mycontenttype' => array(
      'label' => t('My Content Type'),
      'controller class' => 'MyContentTypeEntityController',
      'base table' => 'content_type',
      'uri callback' => 'content_type_uri',
      'entity keys' => array(
        'id' => 'cid',
        'label' => 'title',
      ),
      'bundles' => array(
        'mycontenttype' => array(
          'label' => 'My Content Type',
          'admin' => array(
            'path' => 'admin/contenttype',
            'access arguments' => array('administer contenttype'),
          ),
        ),
      ),
      'fieldable' => true,
    ),
  );
  return $return;
}

/**
 * Implements hook_field_extra_fields().
 */
function mycontenttype_field_extra_fields() {
  $return['mycontenttype']['mycontenttype'] = array(
    'form' => array(
      'body' => array(
        'label' => 'Body',
        'description' => t('Body content'),
        'weight' => 0,
      ),
    ),
  );
  return $return;
} 

那么这是否在 .install 文件中?

function mycontenttype_install() {
  $field = array(
    'field_name' => 'body',
    'type' => 'text_with_summary',
    'entity_types' => array('survey'),
    'translatable' => TRUE,
  );
  field_create_field($field);

  $instance = array(
    'entity_type' => 'mycontenttype',
    'field_name' => 'body',
    'bundle' => 'mycontenttype',
    'label' => 'Body',
    'widget_type' => 'text_textarea_with_summary',
    'settings' => array('display_summary' => TRUE),
    'display' => array(
      'default' => array(
        'label' => 'hidden',
        'type' => 'text_default',
      ),
      'teaser' => array(
        'label' => 'hidden',
        'type' => 'text_summary_or_trimmed',
      ),
    ),
  );
  field_create_instance($instance);
}
4

4 回答 4

1

每个字段都有一个数组属性 entity_types,它限制了字段可以附加到的实体。我能找到的最好的 Drupal 解决方案 hook_field_create_field 可以在创建字段时更改它们,但这对安装时创建的 body 字段没有好处。所以我的解决方案就是直接在我的 hook_install 中编辑数据库

  $data_col = db_query("SELECT data from field_config where field_name = 'body'")->fetchAssoc();
  $data = unserialize($data_col['data']);
  $data['entity_types'][] = 'MY_ENTITY_TYPE';
  db_update('field_config')
    ->fields(array('data' => array('data' => serialize($data))))
    ->条件('field_name','body')
    ->执行();
于 2011-03-12T17:01:45.393 回答
1

刚开始走同样的路 这里是fago 的视频

于 2011-03-24T19:17:49.790 回答
1

我认为您的问题是,如果安装了节点模块,则已经有一个名为“body”的字段。您应该将您的字段重命名为“mycontenttype_body”(comment.module 使用comment_body),或者重新使用“body”字段并跳过添加字段部分并跳过添加它的实例。前者优于后者。

于 2011-01-16T06:42:39.317 回答
0

这是一个很好的回购开始:立法者实体

于 2014-07-29T11:45:47.957 回答