In Drupal 8, how can I create content programmatically ? From the "Drupal 8" administration, I created a new type "House" (contain a description, an image, a reference field to users ...). How can I create a entity type "House" from a custom module ?

In my custom module, I have a form file (contain a class who extends FormBase). In the submit callback, I want create a new "house" and set values and save the new Entity.

I don't find examples on the web, in core...

  • Your second question "How can I create a entity type 'House'?" is a little confusing. I think the question is "How can I create a node of the node type "House" from a custom module?" The ambiguity stems from the use of "entity type" which has a very specific meaning in Drupal and the question could be "How can I create a custom entity type called 'House' from a custom module?" or "How can I create a custom entity which uses the bundle 'House'"?
    – mradcliffe
    Nov 5, 2015 at 14:13

2 Answers 2


The following code creates a node in Drupal 8.

$data = [
  'type' => 'article', 
  'title' => 'My new title', 
  'uid' => 1
$node = Drupal::entityTypeManager()

For testing code snippets like this, drush core-cli works great.

  • 1
    Before the save, with the entityManager, is it possible to know for each field : what type of data must be set ? (text for text field, fid for file etc...) Nov 5, 2015 at 20:18
  • 1
    The only way I know at the moment is to use another deprecated method, EntityManager::getDefinitions(), but I think if you instantiate an EntityDataDefinition via the static create method you can call getPropertyDefinitions(). Both will return definitions for each property such as title or a field. There is also the getFieldStorageDefinitions() which returns the same thing, but from storage entity (see getStorage('node') above). However this may not be available for non-SQL drivers.
    – mradcliffe
    Nov 5, 2015 at 20:46

As of Drupal 8 nodes are now treated as entities. You can simple create a node by the following code

$new_page_values = array();
$new_page_values['type'] = 'my_content_type';
$new_page_values['title'] = $form_state['values']['page_title'];
$new_page_values['path'] = $new_page_path;

$new_page = entity_create('node', $new_page_values);
  • 3
    entity_create() is a deprecated method that we should avoid using. Injecting the EntityManager into the Form class or using \Drupal::entityManager are the standard ways of managing entities.
    – mradcliffe
    Nov 5, 2015 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.