4

I have some nodes with the following fields:

  • Title
  • Body
  • Image

I want to programmatically set the body field as empty.

This is the code I used.

$this_node = node_load($nid);
$this_node->body = array();
node_save($this_node);

This code causes the following exception.

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '104418' for key 'PRIMARY': INSERT INTO {node} (nid, vid, type, language, title, uid, status, created, changed, comment, promote, sticky, tnid, translate, uuid) VALUES (placeholders and their values) in drupal_write_record() (line 7170 of /var/www/rotary.local/docroot/includes/common.inc).

How can I set an empty body field?

I don't want to use field_attach_update() for caching purposes.

0

2 Answers 2

4

To remove the value from you field you should do like this before saving it:

$this_node->body[$this_node->language] = array();
3
  • After testing the code with your suggestion I found that it still gives the error. However I am able to save the node using field_attach_update. What could be causing this?
    – kmdhrm
    Feb 17, 2014 at 10:31
  • @DipakYadav - That seems very strange, what error do you get? Feb 17, 2014 at 10:57
  • The error was being caused because of a whole lot different reason.
    – kmdhrm
    Feb 17, 2014 at 11:36
-1

To make body field empty you should implement hook_node_presave() and inside this, use-

   $node->body[LANGUAGE_NONE][0]['value'] = '';

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.