Create new content type programmatically using Configuration API | Drupal 8

Create new content type programmatically using Configuration API

Submitted by editor on Thu, 04/14/2016 - 17:07
Question

How to create a new custom content type (CT) programmatically using Configuration API ?

Module Name = my_module
Content Type = my_new_content

Create content type

Put this two files into my_module/config/install/

# File 1 
# node.type.my_new_content.yml
langcode: en
status: true
dependencies:
  enforced:
    module:
      - my_module
name: 'My New Content'
type: my_new_content
description: 'Content type that can be used to provide <em>Test content</em>'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true

 

Add existing field

# File 2
#field.field.node.my_new_content.body.yml
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.body
    - node.type.my_new_content
  module:
    - text
id: node.my_new_content.body
field_name: body
entity_type: node
bundle: my_new_content
label: 'Message Body'
description: 'Content of the new CT'
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  display_summary: true
field_type: text_with_summary

 

 

Create a field configuration file

Step 1.    Create the field from the user interface.
Step 2. Export to a file from /admin/config/development/configuration/single/export
        Field Storage (then Field) and Select your field (Here node.field_my_test_text)
        Copy name ftom the bottom of the textarea (Ex: field.storage.node.field_my_test_text.yml)
        Create a config file (Here field.storage.node.field_my_test_text.yml) on /config/install
        Copy the text except 'uudd' line
Step 3. Install or Update your module
        If update, follow update procedure of this tutorial.

Update a Field instance.

Step 1. Update yml file.
Step 2. Create an update in my_module.install , like:

function my_module_update_8001() {
  $config_path = drupal_get_path('module', 'my_module') . '/config/install/field.field.node.my_new_content.body.yml';
  $data = \Symfony\Component\Yaml\Yaml::parse($config_path);
  \Drupal::configFactory()
    ->getEditable('field.field.node.my_new_content.body')
    ->setData($data)
    ->save(TRUE);
  return 'The Field has been updated.';
}

Creating a custom content type in Drupal 8
Tuto : https://www.drupal.org/node/2629550

Creating a content entity type in Drupal 8
https://www.drupal.org/node/2192175

Comments

Add new comment

Plain text

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