在Drupal 7中向现有内容类型添加新字段

时间:2013-10-24 20:25:05

标签: php drupal-7

我是Drupal的新手,我正在寻找一种方法来为Drupal 7中已经安装的内容类型添加一个新字段。请注意,数据库中已经存在一些内容。此外,我需要以编程方式执行此操作,而不是通过GUI。

谷歌搜索,我已经找到了以下文件,似乎是相关的:

https://api.drupal.org/api/drupal/modules!field!field.module/group/field/7

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_update_N/7

尽管如此,我的想法有点困惑,一个基本的例子可以澄清事情。

1 个答案:

答案 0 :(得分:6)

这段代码应该让你入门。它是在Drupal Stackexchange上发现的。我建议你先来检查一下。

https://drupal.stackexchange.com/questions/8284/programmatically-create-fields-in-drupal-7

$myField_name = "my_new_field_name";
if(!field_info_field($myField_name)) // check if the field already exists.
{
    $field = array(
        'field_name'    => $myField_name,
        'type'          => 'image',
    );
    field_create_field($field);

    $field_instance = array(
        'field_name'    => $myField_name,
        'entity_type'   => 'node',
        'bundle'        => 'CONTENT_TYPE_NAME',
        'label'         => t('Select an image'),
        'description'   => t(''),
        'widget'        => array(
            'type'      => 'image_image',
            'weight'    => 10,
        ),
        'formatter'     => array(
            'label'     => t('label'),
            'format'    => 'image'
        ),
        'settings'      => array(
            'file_directory'        => 'photos', // save inside "public://photos"
            'max_filesize'          => '4M',
            'preview_image_style'   => 'thumbnail',
            'title_field'           => TRUE,
            'alt_field'             => FALSE,
        )
    );
    field_create_instance($field_instance);
    drupal_set_message("Field created successfully!");
}

您可以无数种方式执行此代码。我不了解您项目的要求,因此我很难提出建议。你可以将它挂钩到更新/安装函数中,或者你可以将它构建到模块中的页面挂钩中,或者你可以使用它来引导根目录中的任何新的php文件:

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);