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

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

Fawad Ali (not verified)

Wed, 08/15/2018 - 14:01

I want you to compare the D7 field creation code to the D8 field creation i.e we use field_info hook to create new field in D7 and I want you to compare that D7 code to D8. Thanks

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.