Search code examples
drupalhook-form-alterform-alter

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


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;
  }

}

Solution

  • 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;
        }
      }
    }