Create a field in a node entity programmatically on Drupal 8.

Submitted by editor on Fri, 01/13/2017 - 11:37
Question

How to create a custom field in a node entity programmatically, using field API on  drupal 8.

Example.
Step 1 : Create field storage.
\Drupal\field\Entity\FieldStorageConfig::create(array(
  'field_name' => 'field_text',
  'entity_type' => 'node',
  'type' => 'text',
  'cardinality' => -1,
))->save();

Step 2 : Attach an instance of the field to the page content type.
\Drupal\field\Entity\FieldConfig::create([
  'field_name' => 'field_text',
  'entity_type' => 'node',
  'bundle' => 'page',
  'label' => 'A Text field',
])->save();

Step 3 : Set From Display
entity_get_form_display('node', 'page', 'default')
  ->setComponent('field_text', array(
    'type' => 'text_textfield',
  ))
  ->save();

Step 4 : Set Display
entity_get_display('node', 'page', 'default')
  ->setComponent('field_text', array(
    'type' => 'text_default',
  ))
  ->save();

Tips

Load the field:
$field_config = \Drupal\field\Entity\FieldStorageConfig::loadByName('node', 'field_text');

Comments

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.