Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

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

By editor , 13 January, 2017
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');

Tags

  • Drupal 8
  • Code
  • Field
  • Add new comment
Custom Content Entity Field types of drupal 8
Get field value of a Node / Entity

Comments4

Plain text

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

Sanal M (not verified)

9 years 10 months ago

saving the code

But where i have save this code on my drupal.

  • Reply

editor

9 years 10 months ago

In reply to saving the code by Sanal M (not verified)

Create a new Module

For that, you must create a new module. Follow this tutorial: /en/tutoriels/3/create-a-simple-module-for-drupal-8 and /en/tutoriels/5/create-a-simple-module-for-drupal-8-step-2-create-simple-page

  • Reply

Fawad Ali (not verified)

8 years 3 months ago

compare D7 field code to D8

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

  • Reply

André (not verified)

8 years 3 months ago

Creating other field types

Where I can find the configuration for other field types?
I want to add a media field.

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer