Set a text field value on node creation

Public

I wanted to demonstrate usage of `hook_node_insert`. I needed to set a text value on a node only once, during node creation. I also decided to implement `hook_form_alter` to prevent all access to the field on node add/edit forms.

Get raw version
php
  1. /**
  2.  * Implement hook_node_insert
  3.  */
  4. function MODULE_node_insert($node) {
  5. // Set a value for FIELD_NAME on NODE_TYPE nodes during node creation
  6. if ($node->type == 'NODE_TYPE') {
  7. // This works for setting the value of text fields. Other field types may
  8. // require different data properties to be set. The Devel module
  9. // (https://drupal.org/project/devel) `dpm` function is useful for
  10. // exploring what values need to be set to populate a field.
  11. $node->FIELD_NAME[$node->language][0]['value'] = 'FIELD VALUE';
  12. // http://timonweb.com/how-save-yourself-some-hair-when-manipulating-node-fields
  13. // (note: The linked article is a little sparse on details. Anyone care to
  14. // help elaborate?)
  15. field_attach_update('node', $node);
  16. }
  17. }
  18.  
  19. // Optionally, you can prevent the field from being displayed on any forms,
  20. // which will prevent any modification of the field's values by end users.
  21. // See the following two links for a description of the `#disabled` and
  22. // `#access` properties:
  23. // https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#disabled
  24. // https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#access
  25. /**
  26.  * Implement hook_form_alter
  27.  */
  28. function MODULE_form_alter(&$form, &$form_state) {
  29. // Prevent direct modification of FIELD_NAME
  30. if (isset($form['FIELD_NAME'])) {
  31. if (empty($form_state['node']->nid)) {
  32. // Hide the field completely on node creation forms
  33. $form['FIELD_NAME']['#access'] = FALSE;
  34. } else {
  35. // Set the field to disabled on edit forms (disabled fields are shown
  36. // but are not editable)
  37. $form['FIELD_NAME']['#disabled'] = TRUE;
  38. }
  39. }
  40. }