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');
Comments4
saving the code
But where i have save this code on my drupal.
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
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
Creating other field types
Where I can find the configuration for other field types?
I want to add a media field.