1

I have a drupal form that contains a select box. Next to the select box is a link that pops a ctools modal up with an inner form that adds a value to the database table that drives the original select box. When someone clicks submit on the modal form, I would like to rebuild the select box on the original form and set the new value to the default. I've had success with adding the new elements to the select box by doing some ajax in the form_submit hook for the modal form, but it seems like Drupal ignores the value in #default_value in my render array. I have the following in my form_submit hook after the database update and after getting the render array from another function:

if(isset($id)) {
   $newdata['data_source']['#default_value'] = $id;
}
$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', drupal_render($newdata));
print ajax_render($commands);
exit();

Again, the select box is getting the new value, and my render array seems fine. I just can't get it to select the new value by default.

  • I'm pretty sure default_value is out of the picture by that point, try setting $form_state['input']['data_source'] = $id; or $form_state['values']['data_source'] = $id;. I've had varying levels of success in the past with something similar – Clive Mar 25 '14 at 21:44
  • Thanks for the reply. I thought of that but I would need to modify the $form_state on the original form, while in the hook_submit of the modal form. Is it possible to modify one form's $form_state from a different form on the same page? – A.J. Mar 25 '14 at 23:39
0

Alright, so this is slightly hackey, but I got this to work. I totally gave up on trying to set a default value in the render array, and instead did the drupal_render and set it to a variable. I then modified the html directly in the variable. The code I originally posted now looks like this:

if(isset($id) && is_numeric($id)) {
  $newrender = drupal_render($newdata);
  $newrender = str_replace('value="'.$id.'"', 'value="'.$id.'"  selected="selected"', $newrender);
}

$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', $newrender);
print ajax_render($commands);
exit();

If anyone on here has a more elegant solution, I'd be happy to know the "correct way" of doing this, but this produces the desired result.

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.