Programmatically creating a draft using Workbench Moderation

Submitted by Gold on Thu, 09/04/2014 - 14:46

If you're here after this detail you already know about Workbench Moderation so I won't go into the 2 paragraph explanation about what it is and why you should use it. Hopefully you're here because you're having trouble programmatically creating drafts. This was a stumbling block for me too until I started hunting through the modules to see what was going on in the guts of things. Doing that resulted in a really nice and simple solution.

This solution was also just posted to Stack Exchange.

Key things;

  • The content type is under moderation via the workbench moderation module
  • Set the new moderation state
  • Set the node as being a new revision
  • Drupal takes care of the rest

$node = node_load($nid);
$node->body[LANGUAGE_NONE][0]['value'] = 'My new body content';
// We're wanting drupal to create a new revision
$node->revision = 1;
// We want workbench moderation to treat the new revision as a new draft
$node->workbench_moderation_state_new = workbench_moderation_state_none();

Hopefully this helps someone out there...