drupal 8 programmatically saving node doesn't save custom field values

Drupal 8 Programmatically Saving Node Doesn't Save Custom Field Values

If you're facing a problem where your custom field values are not being saved when you programmatically save a node in Drupal 8, then you're not alone. This issue may arise due to various reasons such as incorrect field name, incorrect field type, or something else. Here are some possible solutions:

Check if the Field Value is Set Correctly

The first thing you need to do is to check if the custom field value is set correctly. You can do this by using the set() method and passing the correct field name and value.


$node = Node::create([
  'type' => 'article',
  'title' => 'My Article',
  'field_custom' => [
    'value' => 'My custom field value',
  ],
]);

Make sure that the field_custom is the correct field name and value is the correct field type.

Check if the Field is Attached to the Content Type

If the custom field value is still not being saved, then you need to check if the field is attached to the content type. You can do this by going to Structure > Content types > [Content Type] > Manage fields and checking if the custom field is present.

If it's not present, then you need to add it first by clicking on the Add field button and adding the field with the correct field name and type.

Check if the Field is Set to be Displayed

If the custom field is still not being saved, then you need to check if the field is set to be displayed. You can do this by going to Structure > Content types > [Content Type] > Manage display and checking if the custom field is present.

If it's not present, then you need to add it first by clicking on the Add field button and adding the field with the correct field name.

Check if the Field Storage Settings are Correct

If the custom field is still not being saved, then you need to check if the field storage settings are correct. You can do this by going to Configuration > Content authoring > Content types > [Content Type] > Manage fields -> [Field Name] -> Edit.

Make sure that the field storage settings are correct and match the type of data you're trying to save.

Use Entity API instead of Node API

If all else fails, you can try using the Entity API instead of the Node API. You can do this by creating an instance of the entity and using the save() method to save it.


$node = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'article',
  'title' => 'My Article',
  'field_custom' => [
    'value' => 'My custom field value',
  ],
]);
$node->save();

This should save the custom field value along with the node.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe