如何以编程方式为内容类型创建字段,并将其添加到内容类型表单中


8

假设我有此字段“ map_description”。我知道我会使用此函数来定义字段:

$field = array(
  'field_name' => 'map_description',
  'cardinality' => 1,
  'type' => 'text',
);
field_create_field($field);

我有这个代码,我不确定它会做什么,但是我被告知我将需要它:

 $instance = array(
    'field_name' => 'map_description',
    'label' => 'The map description.',
    'bundle' => 'my_content_type',
    'entity_type' => 'node',
    'widget' => array(
    'type' => 'text_textfield',
 );
 field_create_instance($instance)

这两个代码位都在我的安装挂钩中,并且在我安装模块时运行。但是,尽管实际上创建了字段,但我必须通过“管理字段”将它们手动分配给内容类型,有没有办法自动将字段分配给内容类型?

Answers:


10

您快到了。

从您的代码:

'bundle' => 'my_content_type',

my_content_type替换为您要附加的内容类型的名称。

这是将Alias文本字段添加到Article内容类型的完整示例。(来自monarchdigital.com

/**
 * Update hook to add a field to a node.
 */
function my_module_update_7000() {
  $field_name = 'field_alias';
  // Make sure the field doesn't already exist.
  if (!field_info_field($field_name)) {
    // Create the field.
    $field = array(
      'field_name' => $field_name,
      'type' => 'text',
      'settings' => array('max_length' => 64),
    );
    field_create_field($field);

    // Create the instance.
    $instance = array( 'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Alias',
      'description' => 'The article alias.',
      'required' => TRUE,
    );
    field_create_instance($instance);

    watchdog('my_module', t('!field_name was added successfully.', array('!field_name' => $field_name)));
  }
  else {
    watchdog('my_module', t('!field_name already exists.', array('!field_name' => $field_name)));
  }
}

0

在您的代码中进行小的更改。在字段中

$t = get_t();
$field = array(
   'field_name' => 'map_description',
    'label' => $t('My Description'),
    'type' => 'text',

);
field_create_field($ field);

& Write this in Instance

$t = get_t();
return array(
  'map_description' => array(
    'field_name' => 'map_description',
    'type' => 'text',
    'label' => $t('Map Description'),
    'bundle' => 'your_custom_content_type',
    'entity_type' => 'node',
    'widget' => array(
      'type' => 'text_textfield'
    ),
    'display' => array(
      'example_node_list' => array(
        'label' => $t('Map Description'),
        'type' => 'text'
      )
    )
  ),
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.