field_create_field

  1. drupal
    1. 8
    2. 7
Versions
7 – 8 field_create_field($field)

Creates a field.

This function does not bind the field to any bundle; use field_create_instance() for that.

@throw FieldException

See: Field API data structures.

Parameters

$field A field definition array. The field_name and type properties are required. Other properties, if omitted, will be given the following default values:

  • cardinality: 1
  • locked: FALSE
  • indexes: the field-type indexes, specified by the field type's hook_field_schema(). The indexes specified in $field are added to those default indexes. It is possible to override the definition of a field-type index by providing an index with the same name, or to remove it by redefining it as an empty array of columns. Overriding field-type indexes should be done carefully, for it might seriously affect the site's performance.
  • settings: each omitted setting is given the default value defined in hook_field_info().
  • storage:
    • type: the storage backend specified in the 'field_storage_default' system variable.
    • settings: each omitted setting is given the default value specified in hook_field_storage_info().

Return value

The $field array with the id property filled in.

Related topics

▾ 64 functions call field_create_field()

AJAXMultiFormTestCase::setUp in modules/simpletest/tests/ajax.test
Generates a random database prefix, runs the install scripts on the prefixed database and enable the specified modules. After installation many caches are flushed and the internal browser is setup so that the page requests will run on the new prefix.…
EntityFieldQueryTestCase::setUp in modules/simpletest/tests/entity_query.test
Generates a random database prefix, runs the install scripts on the prefixed database and enable the specified modules. After installation many caches are flushed and the internal browser is setup so that the page requests will run on the new prefix.…
FieldAttachStorageTestCase::testFieldAttachDeleteBundle in modules/field/tests/field.test
Test field_attach_delete_bundle().
FieldAttachStorageTestCase::testFieldAttachLoadMultiple in modules/field/tests/field.test
Test the 'multiple' load feature.
FieldAttachStorageTestCase::testFieldAttachSaveLoadDifferentStorage in modules/field/tests/field.test
Test saving and loading fields using different storage backends.
FieldAttachStorageTestCase::testFieldStorageDetailsAlter in modules/field/tests/field.test
Test storage details alteration.
FieldAttachTestCase::setUp in modules/field/tests/field.test
Set the default field storage backend for fields created during tests.
FieldBulkDeleteTestCase::setUp in modules/field/tests/field.test
Set the default field storage backend for fields created during tests.
FieldCrudTestCase::testActive in modules/field/tests/field.test
Test that fields are properly marked active or inactive.
FieldCrudTestCase::testCreateField in modules/field/tests/field.test
Test the creation of a field.
FieldCrudTestCase::testCreateFieldFail in modules/field/tests/field.test
Test failure to create a field.
FieldCrudTestCase::testDeleteField in modules/field/tests/field.test
Test the deletion of a field.
FieldCrudTestCase::testFieldIndexes in modules/field/tests/field.test
Test creation of indexes on data column.
FieldCrudTestCase::testReadField in modules/field/tests/field.test
Test reading back a field definition.
FieldCrudTestCase::testUpdateField in modules/field/tests/field.test
Test updating a field.
FieldCrudTestCase::testUpdateFieldForbid in modules/field/tests/field.test
Test field type modules forbidding an update.
FieldCrudTestCase::testUpdateFieldType in modules/field/tests/field.test
FieldDisplayAPITestCase::setUp in modules/field/tests/field.test
Set the default field storage backend for fields created during tests.
FieldFormTestCase::testFieldFormAccess in modules/field/tests/field.test
Tests fields with no 'edit' access.
FieldFormTestCase::testFieldFormJSAddMore in modules/field/tests/field.test
FieldFormTestCase::testFieldFormMultipleWidget in modules/field/tests/field.test
Tests widgets handling multiple values.
FieldFormTestCase::testFieldFormSingle in modules/field/tests/field.test
FieldFormTestCase::testFieldFormSingleRequired in modules/field/tests/field.test
FieldFormTestCase::testFieldFormUnlimited in modules/field/tests/field.test
FieldFormTestCase::testNestedFieldForm in modules/field/tests/field.test
Tests Field API form integration within a subform.
FieldInfoTestCase::testFieldInfo in modules/field/tests/field.test
Test that field types and field definitions are correcly cached.
FieldInfoTestCase::testFieldPrepare in modules/field/tests/field.test
Test that cached field definitions are ready for current runtime context.
FieldInfoTestCase::testInstanceDisabledEntityType in modules/field/tests/field.test
Test that instances on disabled entity types are filtered out.
FieldInfoTestCase::testInstancePrepare in modules/field/tests/field.test
Test that cached instance definitions are ready for current runtime context.
FieldInstanceCrudTestCase::setUp in modules/field/tests/field.test
Set the default field storage backend for fields created during tests.
FieldInstanceCrudTestCase::testCreateFieldInstance in modules/field/tests/field.test
Test the creation of a field instance.
FieldSqlStorageTestCase::setUp in modules/field/modules/field_sql_storage/field_sql_storage.test
FieldSqlStorageTestCase::testFieldSqlStorageForeignKeys in modules/field/modules/field_sql_storage/field_sql_storage.test
Test foreign key support.
FieldSqlStorageTestCase::testFieldUpdateIndexesWithData in modules/field/modules/field_sql_storage/field_sql_storage.test
Test adding and removing indexes while data is present.
FieldSqlStorageTestCase::testUpdateFieldSchemaWithData in modules/field/modules/field_sql_storage/field_sql_storage.test
Test trying to update a field with data.
FieldTranslationsTestCase::setUp in modules/field/tests/field.test
Set the default field storage backend for fields created during tests.
FieldTranslationsTestCase::testFieldDisplayLanguage in modules/field/tests/field.test
Tests display language logic for translatable fields.
FieldUIManageFieldsTestCase::testDefaultValue in modules/field_ui/field_ui.test
Tests that default value is correctly validated and saved.
FieldUIManageFieldsTestCase::testHiddenFields in modules/field_ui/field_ui.test
Test that Field UI respects the 'no_ui' option in hook_field_info().
field_ui_field_overview_form_submit in modules/field_ui/field_ui.admin.inc
Submit handler for the field overview form.
FileFieldTestCase::createFileField in modules/file/tests/file.test
Create a new file field.
FormsArbitraryRebuildTestCase::setUp in modules/simpletest/tests/form.test
Generates a random database prefix, runs the install scripts on the prefixed database and enable the specified modules. After installation many caches are flushed and the internal browser is setup so that the page requests will run on the new prefix.…
FormsRebuildTestCase::testPreserveFormActionAfterAJAX in modules/simpletest/tests/form.test
Tests that a form's action is retained after an Ajax submission.
forum_enable in modules/forum/forum.install
Implements hook_enable().
ImageFieldTestCase::createImageField in modules/image/image.test
Create a new image field.
ListFieldTestCase::setUp in modules/field/modules/list/tests/list.test
Set the default field storage backend for fields created during tests.
ListFieldTestCase::testUpdateAllowedValues in modules/field/modules/list/tests/list.test
Test that allowed values can be updated.
ListFieldUITestCase::createListField in modules/field/modules/list/tests/list.test
Helper function to create list field of a given type.
node_add_body_field in modules/node/node.module
Add default body field to a node type.
node_example_install in examples/node_example/node_example.install
Implements hook_install().
NumberFieldTestCase::testNumberDecimalField in modules/field/modules/number/number.test
Test number_decimal field.
OptionsWidgetsTestCase::setUp in modules/field/modules/options/options.test
Set the default field storage backend for fields created during tests.
RdfRdfaMarkupTestCase::testAttributesInMarkupFile in modules/rdf/rdf.test
Ensure that file fields have the correct resource as the object in RDFa when displayed as a teaser.
standard_install in profiles/standard/standard.install
Implements hook_install().
TaxonomyTermFieldTestCase::setUp in modules/taxonomy/taxonomy.test
Generates a random database prefix, runs the install scripts on the prefixed database and enable the specified modules. After installation many caches are flushed and the internal browser is setup so that the page requests will run on the new prefix.…
TaxonomyTermTestCase::setUp in modules/taxonomy/taxonomy.test
Generates a random database prefix, runs the install scripts on the prefixed database and enable the specified modules. After installation many caches are flushed and the internal browser is setup so that the page requests will run on the new prefix.…
TaxonomyTokenReplaceTestCase::setUp in modules/taxonomy/taxonomy.test
Generates a random database prefix, runs the install scripts on the prefixed database and enable the specified modules. After installation many caches are flushed and the internal browser is setup so that the page requests will run on the new prefix.…
TaxonomyVocabularyUnitTest::testTaxonomyVocabularyChangeMachineName in modules/taxonomy/taxonomy.test
Tests that machine name changes are properly reflected.
TaxonomyVocabularyUnitTest::testUninstallReinstall in modules/taxonomy/taxonomy.test
Test uninstall and reinstall of the taxonomy module.
TextFieldTestCase::testTextFieldValidation in modules/field/modules/text/text.test
Test text field validation.
TextFieldTestCase::_testTextfieldWidgets in modules/field/modules/text/text.test
Helper function for testTextfieldWidgets().
TextFieldTestCase::_testTextfieldWidgetsFormatted in modules/field/modules/text/text.test
Helper function for testTextfieldWidgetsFormatted().
UserRegistrationTestCase::testRegistrationWithUserFields in modules/user/user.test
Tests Field API fields on user registration forms.
_comment_body_field_create in modules/comment/comment.module
Creates a comment_body field instance for a given node type.

Code

modules/field/field.crud.inc, line 52

<?php
function field_create_field($field) {
  // Field name is required.
  if (empty($field['field_name'])) {
    throw new FieldException('Attempt to create an unnamed field.');
  }
  // Field type is required.
  if (empty($field['type'])) {
    throw new FieldException('Attempt to create a field with no type.');
  }
  // Field name cannot contain invalid characters.
  if (!preg_match('/^[_a-z]+[_a-z0-9]*$/', $field['field_name'])) {
    throw new FieldException('Attempt to create a field with invalid characters. Only lowercase alphanumeric characters and underscores are allowed, and only lowercase letters and underscore are allowed as the first character');
  }

  // Field name cannot be longer than 32 characters. We use drupal_strlen()
  // because the DB layer assumes that column widths are given in characters,
  // not bytes.
  if (drupal_strlen($field['field_name']) > 32) {
    throw new FieldException(t('Attempt to create a field with a name longer than 32 characters: %name', 
      array('%name' => $field['field_name'])));
  }

  // Ensure the field name is unique over active and disabled fields.
  // We do not care about deleted fields.
  $prior_field = field_read_field($field['field_name'], array('include_inactive' => TRUE));
  if (!empty($prior_field)) {
    $message = $prior_field['active'] ?
      t('Attempt to create field name %name which already exists and is active.', array('%name' => $field['field_name'])) :
      t('Attempt to create field name %name which already exists, although it is inactive.', array('%name' => $field['field_name']));
    throw new FieldException($message);
  }

  // Disallow reserved field names. This can't prevent all field name
  // collisions with existing entity properties, but some is better
  // than none.
  foreach (entity_get_info() as $type => $info) {
    if (in_array($field['field_name'], $info['entity keys'])) {
      throw new FieldException(t('Attempt to create field name %name which is reserved by entity type %type.', array('%name' => $field['field_name'], '%type' => $type)));
    }
  }

  $field += array(
    'entity_types' => array(), 
    'cardinality' => 1, 
    'translatable' => FALSE, 
    'locked' => FALSE, 
    'settings' => array(), 
    'storage' => array(), 
    'deleted' => 0,
  );

  // Check that the field type is known.
  $field_type = field_info_field_types($field['type']);
  if (!$field_type) {
    throw new FieldException(t('Attempt to create a field of unknown type %type.', array('%type' => $field['type'])));
  }
  // Create all per-field-type properties (needed here as long as we have
  // settings that impact column definitions).
  $field['settings'] += field_info_field_settings($field['type']);
  $field['module'] = $field_type['module'];
  $field['active'] = 1;

  // Provide default storage.
  $field['storage'] += array(
    'type' => variable_get('field_storage_default', 'field_sql_storage'), 
    'settings' => array(),
  );
  // Check that the storage type is known.
  $storage_type = field_info_storage_types($field['storage']['type']);
  if (!$storage_type) {
    throw new FieldException(t('Attempt to create a field with unknown storage type %type.', array('%type' => $field['storage']['type'])));
  }
  // Provide default storage settings.
  $field['storage']['settings'] += field_info_storage_settings($field['storage']['type']);
  $field['storage']['module'] = $storage_type['module'];
  $field['storage']['active'] = 1;
  // Collect storage information.
  module_load_install($field['module']);
  $schema = (array) module_invoke($field['module'], 'field_schema', $field);
  $schema += array(
    'columns' => array(),
    'indexes' => array(),
    'foreign keys' => array(),
  );
  // 'columns' are hardcoded in the field type.
  $field['columns'] = $schema['columns'];
  // 'foreign keys' are hardcoded in the field type.
  $field['foreign keys'] = $schema['foreign keys'];
  // 'indexes' can be both hardcoded in the field type, and specified in the
  // incoming $field definition.
  $field += array(
    'indexes' => array(),
  );
  $field['indexes'] += $schema['indexes'];

  // The serialized 'data' column contains everything from $field that does not
  // have its own column and is not automatically populated when the field is
  // read.
  $data = $field;
  unset($data['columns'], $data['field_name'], $data['type'], $data['active'], $data['module'], $data['storage_type'], $data['storage_active'], $data['storage_module'], $data['locked'], $data['cardinality'], $data['deleted']);
  // Additionally, do not save the 'bundles' property populated by
  // field_info_field().
  unset($data['bundles']);

  $record = array(
    'field_name' => $field['field_name'], 
    'type' => $field['type'], 
    'module' => $field['module'], 
    'active' => $field['active'], 
    'storage_type' => $field['storage']['type'], 
    'storage_module' => $field['storage']['module'], 
    'storage_active' => $field['storage']['active'], 
    'locked' => $field['locked'], 
    'data' => $data, 
    'cardinality' => $field['cardinality'], 
    'translatable' => $field['translatable'], 
    'deleted' => $field['deleted'],
  );

  // Store the field and get the id back.
  drupal_write_record('field_config', $record);
  $field['id'] = $record['id'];

  // Invoke hook_field_storage_create_field after the field is
  // complete (e.g. it has its id).
  try {
    // Invoke hook_field_storage_create_field after
    // drupal_write_record() sets the field id.
    module_invoke($storage_type['module'], 'field_storage_create_field', $field);
  }
  catch (Exception $e) {
    // If storage creation failed, remove the field_config record before
    // rethrowing the exception.
    db_delete('field_config')
      ->condition('id', $field['id'])
      ->execute();
    throw $e;
  }

  // Clear caches
  field_cache_clear(TRUE);

  // Invoke external hooks after the cache is cleared for API consistency.
  module_invoke_all('field_create_field', $field);

  return $field;
}
?>