how to set default option of node reference cck field through form alter

2k views Asked by At

I accept the arg from the url and according to the arg value I need to set the default option value, here is the code:

function ims_form_alter(&$form, $form_state, $form_id) {


switch ($form_id) {

  case 'media_content_node_form':

    unset($form['buttons']['preview']);

    $form['#redirect'] = 'mediacontent';

    if(is_numeric(arg(3)))
    {
      $arg_nid = arg(3);
      foreach($form['field_media_model']['#options'] as $k=>$v)
              {
        if($v==$arg_nid)
        {
        $form['field_media_model']['#default_value'] = $v;
        } 

      }
    }

    break;
  }

}
2

There are 2 answers

2
berkes On BEST ANSWER

First you should steer away from a switch construction if you are only testing one thing; use an if.

Second, as per your own comment, you were using the variables wrong.

And third, why all the extra cruft, such as unsetting values, looping trough #options, and redirecting?

function ims_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'media_content_node_form') {
    $nid = arg(3);

    if(($nid = arg(3)) && is_int($nid)) {
      $form['field_media_model']['#default_value'][0]['nid'] = $nid;
    }
  }
}
1
Punit On

i was accessing the value of element wrongly, because it's a node reference field the right way to access that element is $form['field_media_model']['#default_value'][0]['nid']