Set field value for a node programmatically in Drupal 10
To set a field value programmatically in Drupal 10, you typically load the entity (like a node, user, or taxonomy term), then set the field value, and save the entity.
Make sure the field name (field_example) matches the machine name in your content type.
use Drupal\node\Entity\Node;
// Load the node (replace with your node ID).
$nid = 1;
$node = Node::load($nid);
if ($node) {
// Set value for a text field (replace 'field_example' with your field machine name).
$node->set('field_example', 'New value');
// Save the node.
$node->save();
}
For Different Field Types
1. Text field (single value):
$node->set('field_text', 'My text value');
2. Text field (multiple values):
$node->set('field_text_multi', ['Item 1', 'Item 2']);
3. Entity reference:
// Set reference to another node ID (e.g. node 5).
$node->set('field_reference', ['target_id' => 5]);
4. Boolean:
$node->set('field_boolean', 1); // or 0
5. Image/File field:
$node->set('field_image', ['target_id' => $fid]);