Drupal - How to programmatically create Fields?

Use field_create_field() to create the field itself and field_create_instance() to have an instance for the given entity bundle.

When creating fields as part of a custom module, you may or may not want to delete the field when the module is uninstalled. To do so, you can use field_delete_field() if you want to delete the field and all field instance, or if you want to delete specific instances you can use field_delete_instance().


Example on how to programatically add fields to the user profile and how to avail them, or not, into the User Registration form.


function MYMODULE_enable() {
  // Check if our field is not already created.
  if (!field_info_field('field_myField')) {

    // Create the field base.
    $field = array(
      'field_name' => 'field_myField', 
      'type' => 'text', 
    );
    field_create_field($field);

    // Create the field instance on the bundle.
    $instance = array(
      'field_name' => 'field_myField', 
      'entity_type' => 'user', 
      'label' => 'My Field Name', 
      'bundle' => 'user', 
      // If you don't set the "required" property then the field wont be required by default.
      'required' => TRUE,
      'settings' => array(
        // Here you inform either or not you want this field showing up on the registration form.
        'user_register_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ), 
    );
    field_create_instance($instance);
  }
}

If you need to quickly create / delete fields from an existing Content Type or or Entity, without neither using the UI nor programming, you can use these little-known Drush commands:

drush field-create <bundle(for nodes)> <field_name>,<field_type>,[widget_name] --entity_type : Type of entity (e.g. node, user, comment). Defaults to node.

E.g.: Create two new fields for Article:

drush field-create article city,text,text_textfield subtitle,text,text_textfield

Other commands:

drush field-delete <field_name> [--bundle] [--entity_type]
drush field-info [field | types]
drush field-update <field_name> Return URL for field editing web page.
drush field-clone <source_field_name> <dst_field_name>

Tags:

Entities

7