1

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

}
Laxman13
  • 5,226
  • 3
  • 23
  • 27
Punit
  • 1,110
  • 1
  • 8
  • 14
  • What type of widget is field_media_model using? – Clive Sep 20 '11 at 11:51
  • thanks for your attention: it's select box - node reference. I got the answer, i was accessing the values wrongly, now i am using $form['field_media_model']['#default_value'][0]['nid'] to set default value; – Punit Sep 20 '11 at 12:55
  • Stop suggesting invalid edits to [this question](http://stackoverflow.com/questions/7656378/how-to-display-mysql-record-using-a-combobox-in-php-ajax) - they are rejected because you removed the image. If you don't know how to edit properly, don't do it. Thank you. – Shadow The GPT Wizard Oct 05 '11 at 07:30

2 Answers2

2

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;
    }
  }
}
berkes
  • 26,996
  • 27
  • 115
  • 206
  • the question is simplified to understand the scenario, their are multiple cases and all other stuff is according to my custom needs,i have done with this problem it's resolved now **(mentioned as comment section of question itself.)** – Punit Oct 11 '11 at 09:26
  • For me it worked when i used: $form['field_media_model'][LANGUAGE_NONE]['#default_value'][] = $nid; – devunder Feb 04 '14 at 09:12
0

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']

Punit
  • 1,110
  • 1
  • 8
  • 14