I'm attempting to allow users to enter a number of node types in an entity reference field inside a custom config form. However I can't seem to supply it with a proper default value. My field in the form looks like this:

$config = $this->config('contentform.settings');
    $form['content_types'] = [
        '#type'          => 'entity_autocomplete',
        '#description'   => t('Choose what content types to map'),
        '#target_type'   => 'node_type',
        '#default_value' => $config->get('content_type'),

However $config->get('content_type') only supplies me with the label of the content type.

So I get the following error

InvalidArgumentException: The #default_value property has to be an entity object or an array of entity objects

I'm saving the value in the submit function like so:

    $content_type = $form_state->getValue('content_types');
         ->set('content_type', $content_type)

I've also tried $form_state->get('content_types') and $form_state->get('content_types')->entity; But those didn't work either.

How would I get the node_type entity or object instead of just the label? Or is there a way to load the node_type from just the name?

1 Answer 1


You can load a node_type entity by specifying the node type id

$node_type_entity = \Drupal\node\Entity\NodeType::load($node_type_id);

or if you have multiple node types an array of entities:

$node_type_entities = \Drupal\node\Entity\NodeType::loadMultiple($node_type_ids);
  • How would I get the id if it's based on input from an entity reference autocomplete field?
    – Amy
    Jan 11, 2017 at 19:52
  • In configuration you store the id's, which are the machine names of the content types.
    – 4uk4
    Jan 11, 2017 at 19:56

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.