[development] How to validate a $node?

Robrecht Jacques robrechtj+drupal at gmail.com
Wed Jun 7 01:15:27 UTC 2006


Hi all,

For the node_import module which tries to import a whole set of nodes from a
CSV file, I have the following problem: how does one validate a "$node"
before "node_save()"ing it?

Let me explain:

In 4.6 we had the "node_validate($node)" function which validates the node
(calling "hook_validate()" and "hook_nodeapi('validate')" as needed). If
this was succesful (no "form_get_errors()"), then we could safely
"node_save($node)" it.

Now, in 4.7, most (if not all) validation is done using the form API, in
things like "#validate" and "#required". For example, "story.module"
requires that the title is not empty. It does that by setting a "#required"
on the title-textfield. If I do:
$node = (object) array('type' => 'story', 'uid' => 42, 'title' => '');
the node will pass "node_validate($node)", but this is because the
validation inside "$form" was not run!

So my questions are:
- how does one validate a node programmatically *correctly*?
- what is the point of the "node_validate()" function and the hooks if it
doesn't actually *validate* the node at all? At least rename it to
"node_noop()" so things are clear.
- really, why have "node_validate()" at all? Does anyone do anything usefull
in it?
- and the real question: how does the following sequence of 4.6 translate
into 4.7:

$node->type = 'story';
$node->uid = 1;
$node->title = ''; // invalid empty title!
$node->body = ''; // invalid empty body!

$node = node_validate($node); // if life was only that
                              // that easy in 4.7...

if (form_get_errors()) {
  // we detected the error... do something
  unset($GLOBALS['form']);

  // note: we unset $GLOBALS['form'] so the next time we
  // try this trick, form_get_errors() return the errors
  // of the last run and not of the previous.
  // If something like this would be possible in 4.7 it
  // would be great, but form_set_error() in 4.7 saves the
  // errors in a static variable inside form_set_error()
  // instead of in $GLOBALS['form']. I see no way to unset
  // that...
  $output .= node_view($node);
}
else {
  // no errors? hmm, great, save it... quickly before
  // "they" introduce something else that breaks
  // "common sense". Really: why call something
  // foobar_validate() if it doesn't validate anything
  // at all... Am I alone in this? I guess so.
  node_save($node);
}

Anyway, I have a solution, but that is so hackerish that I hope others know
"The Right Solution(tm)".

Thanks,
Robrecht
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.drupal.org/pipermail/development/attachments/20060607/210ca89e/attachment.htm


More information about the development mailing list