正确使用Drupal 7实体和Field API的方法

Mar*_*tts 6 drupal drupal-7 drupal-modules

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

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

在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;
} 
Run Code Online (Sandbox Code Playgroud)

然后这会进入.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);
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*eid 1

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