1

using Drupal 7

I'm trying to write a module that alters the node add form of a certain content type. This content type has a node reference field that normally displays as a drop-down. I'm also attaching this node add form to the bottom of the content it references, what I'm trying to do is populate the node reference field by using hook_form_alter() and passing in arg(1) of the page (passing it the nid of node I want it to reference).

I'm trying to figure out exactly how to do this. I've tried to do a drupal_set_message('<pre>'. print_r($form, TRUE) .'</pre>'); on the form to see how exactly to pass in the node reference, but it just prints out a huge nested array, and I'm unable to really figure out how I would format that as input I know it's going to look something like this;

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "my_node_form")
    {
        $form['title']['required'] = FALSE;
        $form['node_reference_field_name']['nid'] = arg(1);    
    }

}

but I'm still really confused on the actual syntax

1

ok, figured this out incase anyone is interested, may only work for my use case but perhaps it will help someone else.

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "rating_node_form")
    {
        // dont require title
        $form['title']['required'] = FALSE;
        // validate
        $form['#validate'][] = 'mymodule_form_validate';
        // call after form is built
        $form['#after_build'][] = 'mymodule_after_build';
    }
}

function mymodule_after_build($form, &$form_state) {
       //set the nid to the argument of the nide you are viewing
       $form['field_bar_name']['und']['nid']['#value'][0] = arg(1);
       //set the default value
       $form['field_bar_name']['und'][0]['nid']['#default_value'] = arg(1);
       //set form value
       $form['field_bar_name']['und'][0]['nid']['#value'] = arg(1);
       return $form;
}
  • also, for some reason you need to have the node reference url widget enabled, I suppose this has something to do with arg(1) being available. – user379468 Dec 29 '11 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.