Basic usage

Last updated on
12 September 2023

From the admin UI

Visit the admin settings page at Configuration > Development > Create Field Programmatically.

Paste your configuration for each Entity Type you want to declare fields to. An example file exists with detailed explanations about the custom YAML file expected from this module to work correctly.

See the complete example of the expected YAML configuration in the module example folder: field_create.node.settings.yml.

Alternatively if you are not confortable writing in YAML, you can enabled the field_create_from_json submodule and use JSON input instead. It will be converted automatically when you save the admin settings form. An example file is provided in the module too. at node_fields.json

Save your settings.

Run the creation by clicking on the CREATE FIELDS button.

Enjoy!

From a custom module

You can use a custom module to declare fields to field_create service.

You can either (option 1) place custom configuration files in the install folder and/or (option 2) implement a hook to declare your fields.

(Option 1) Manually create configuration files

Create your custom configurations files and place them in either your site's Config Sync folder or inside a module.

If you use a module, place your files under /config/install and (re)install your module for Drupal to import them.
Example: /mymodule/config/install/field_create.node.settings.yml

Here is a very basic example of a configuration file to create fields and attach them to the Page and Article node types.

demo_field:
  name: demo_field
  label: This is my field
  type: string
  force: true
  bundles:
    page:
      label: This is a custom label for Pages
    article:
      label: This is a custom label for Articles

(Option 2) Using the hook_field_create_definition()

Implements this hook in your mymodule.module file:

/**
 * Implements hook_field_create_definitions().
 */
function mymodule_field_create_definitions_alter(array &$definitions) {
  // Define your fields here by entity type.
  $definitions['node'] = [
    'demo_field' => [
      'name'    => 'demo_field',
      'label'   => 'This is my field',
      'type'    => 'string',
      'force'   => FALSE, // No update once field exists.
      'bundles' => [
        'page' => [],
        'article' => [],
      ],
    ],
  ];
}

Create the fields

Now that you have declared your fields, the module is ready to create your fields for you.

Simply run this Drush command: drush field_create

Filter the field creation by entity type if you want, as follow: drush field_create --entity-type-id node

Help improve this page

Page status: No known problems

You can: