Updating nodes via ajax from the node edit form

How to save a node via JSON from the node edit page ("what??")

For any non-technical Drupal folk out there – be ye warned. This is a technical post. The intent with these types of posts is to share some knowledge we’ve discovered and share it with the community.

On the agenda? node_save().

Here’s a question: What if, by some odd twist of fate, you needed to update a nodes value via an ajax hook on the node edit page? This was a recent request from a client. Seems a bit odd, but it does have a certain type of logic to it. The client has a very proprietary workflow in place that uses a node reference to a Workflow Status node (so if you have a node revision that’s ready to be reviewed by someone, you can update the Workflow Status node reference to point to the “Ready for Review” workflow node).

So it generally happens that content revisions need to have their statuses updated as they move through the queue, but we don’t actually want to edit the content of the node – or rather, any other fields. So that’s tricky, yeah? If you save the node, you may publish a new revision, or at the very least, update the “edited” timestamp.

We exposed a json dropdown box for certain user roles on a special workflow page and on the node view page – which are a piece of cake.

But how to do this on the node edit page? Sure, you can do it just as we did on the other pages. But then if you actually do change a node value along with that update, you’re going to get the dreaded “This node has already been modified by another user”. Why? Because it has! By you!

So…what trickery gives away your stealth json update? Is it a flag somewhere? Some timestamp on all the cck fields that you have to track down? Do you have to just do a pure db_query to update the value and miss out on all the node_save() goodness?

Well, turns out it’s simple. The form on submit just checks last edited timestamp that it expects with the value that is actually in the node table.

So if you want to get around this, it’s as simple as doing a node_load(), getting the last edited timestamp, modifying your value, doing a node_save(), and then the kicker: do a db_update to update the node row with the timestamp from before the node_save().

Easy peasy. After that, you won’t get the “This node has already been modified by another user” warning message on node save.

Good luck!