4
votes

I'm new to Drupal and I'm looking for a way to add a new field to an already installed content-type in Drupal 7. Please note that some content is already present in the database. Also, I need to do this programmatically and not via a GUI.

Googling, I have already found the following documents, which seem to be related:

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

Still, my ideas are a bit confused and a basic example would clarify things.

1

1 Answers

6
votes

This snippet should get you started. It was found on the Drupal Stackexchange. I suggest you check there first in the future.

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!");
}

You can execute this code countless ways. I am not privy to the requirements of your project so its hard for me to make a recommendation. You could hook this into the update/install functions, or you could build it into a page hook in a module, or you could just bootstrap any new php file in the root directory with this:

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