MiBerG
MiBerG

Reputation: 35

How to programmatically load a form for a given node, modify it's values and then submit it?

when I click on the "edit" tab of one of my forum nodes, I get a form displayed such as this:

Edit view of a forum node

When I select any option in the "Forums"-drop-down-menu (and thus choose a forum container) and click on "Submit", the forum node gets moved to the chosen forum container.

Now, what I need to do is to trigger all this programmatically from somewhere in my code. I have to move a lot of forum nodes to a lot of different forum containers, that's why I need to do this that way.

What I was thinking about how this could be done is this:

  1. Load the form data of the "forum_node_form" so that the data of a specific forum node is included (the forum node I'd like to move to another forum container).
  2. Change the parameter $form_state['values']['forum_tid'] to the tid of the forum container I'd like to move the forum node to.
  3. Save the form data by using drupal_form_submit().

However, this proves to be harder than I expected. Can someone point out for me what's the right way to do this?

So far, I've logged the content of $form_state['values'] during a manual test using var_export($form_state['values'], true). I've then changed $form_state['values']['forum_tid'] to the tid of the forum container I'd like to move the forum to and then submitted the data using drupal_form_submit('forum_node_form', $form_state);

That led to the error message:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 795 of /"PATH"/includes/form.inc).

I've found some advice to use form_load_include() and therefore added this line:

form_load_include($form_state, 'inc', 'node', 'node.pages');

...which leads to some new errors:

  • Warning: Missing argument 3 for node_form() in node_form() (line 83 of /"PATH"/modules/node/node.pages.inc).
  • EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7539 of /"PATH"/includes/common.inc).

Argument 3 of node_form() is the node object $node and I don't know how to solve this problem and I actually feel that this is not the right way to solve the whole issue.

Any help is greatly appreciated.

Upvotes: 0

Views: 1446

Answers (1)

mmiles
mmiles

Reputation: 961

Instead of going through the pain of loading the node form, you can just load the node object (using node_load), change the forum tid value, and save the node (using node_save) to update it.

Example:

<?php

function mymodule_updatemynode($nid,$new_forum_tid){
    if ($node = node_load($nid)){
        // not exactly sure what the forum tid field is called
        // just an example
        $node->field_forum_tid['und'][0]['#value'] = $new_forum_tid;
        node_save($node);
    }
}

Upvotes: 1

Related Questions