开发者

Loading the previous revision of a node

When you get a node, how do you load the p开发者_开发问答revious version (revision)?

I know how loading a revision but not how getting the previous revision number ($node->vid is the current revision).

thanks


Supposing that you have a node object $node, you can use the following code to get the previous revision.

$previous_vid = db_result( 
  db_query('SELECT MAX(vid) AS vid FROM {node_revisions} WHERE vid < %d AND nid = %d', $node->vid, $node->nid)
);

Once you have the previous revision, you can load the new node object with node_load(array('nid' => $node-nid, 'vid' => $previous_vid)).

The code should check if db_result() returns FALSE, in the case there isn't a previous revision. To note that the field vid is global for each node; it doesn't contain the same value for different nodes.


Thanks all.

I found also an other solution:

  $revisions = node_revision_list($node);
  next($revisions);
  if ($preview_key = key($revisions)) {
    $preview_revision = $revisions[$preview_key];
    $old_node = node_load($node->nid, $preview_revision->vid);
  }

But if you have a lot of revision you get a big array.


If I understand what you're trying to do; you want to get the preview of the node after someone submits changes?

The preview button has its own submit handler, node_form_build_preview(). There, it creates a new node object using the data in $form_state and runs node_preview(), which returns the markup for the preview.

If you want to capture that preview when the user clicks the preview button, you'll need to use hook_form_alter to add another submit handler to the preview button:

$['form']['buttons']['preview']['#submit'][] = 'mymodule_custom_preview';

where mymodule_custom_preview is the name of your custom submit function. Take a look at node_form_build_preview() for guidance, but your submit function is going to look something like this:

function mymodule_custom_preview($form, &$form_state) {
  $node = node_form_submit_build_node($form, $form_state);
  $preview = node_preview($node);
}

Also take a look at node_form(), which gives you an idea of how the node form is structured. When you're all done, you're going to have code in your module that looks something like this:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (strstr($form_id, '_node_form') !== FALSE) {
    $['form']['buttons']['preview']['#submit'][] = 'mymodule_custom_preview';
  }
}

function mymodule_custom_preview($form, &$form_state) {
  $node = node_form_submit_build_node($form, $form_state);
  $preview = node_preview($node);

  // Do what you will with $preview.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜