Skip to content

Instantly share code, notes, and snippets.

@denmarkin
Created December 24, 2010 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denmarkin/754517 to your computer and use it in GitHub Desktop.
Save denmarkin/754517 to your computer and use it in GitHub Desktop.
Extended version of http://www.nicklewis.org/node/967 recipe for partial nested form update
// Lastly, here's a help function pulled from Nick Lewis's blog to alter the form
// see: http://www.nicklewis.org/node/967
// Nested fields are implemented by denmarkin.
// Usage example: $output .= _ahah_render($form, array('block_settings', 'module_block_'.$delta, 'custom_fields'));
function _ahah_render($fields, $name) {
$form_state = array('submitted' => FALSE);
$form_build_id = $_POST['form_build_id'];
// Add the new element to the stored form. Without adding the element to the
// form, Drupal is not aware of this new elements existence and will not
// process it. We retreive the cached form, add the element, and resave.
$form = form_get_cache($form_build_id, $form_state);
if (!is_array($name)) {
$form[$name] = $fields;
} else {
// map nested fields
$nestedFormPath = 'form';
for ($i = 0; $i < count($name); $i++) {
$target_el = $name[$i];
$nestedFormPath .= "['$target_el']";
// $form = $form[$target_el];
if (isset($fields[$target_el])) {
$fields = $fields[$target_el];
}
}
eval("\$$nestedFormPath = \$fields;");
}
// print_r($form);die;
form_set_cache($form_build_id, $form, $form_state);
$form += array(
'#post' => $_POST,
'#programmed' => FALSE,
);
// Rebuild the form.
$form = form_builder($_POST['form_id'], $form, $form_state);
// Render the new output.
if (!is_array($name)) {
$new_form = $form[$name];
} else {
eval("\$new_form = \$$nestedFormPath;");
}
return drupal_render($new_form);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment