User login

Insert immediately before or after an element in a form

If you just want to insert something first in an array, as to make sure that your validation function is called first, you can do something like this:

<?php
  array_unshift
($form['#validate'], 'mymodule_form_expert_bio_node_validate_title');
?>

(Note on validation: You cannot get in front of the Drupal form checking if a value is required, so if you are filling in a value with a validation function, form_alter the field to not be required.)

Based on http://civicactions.com/blog/drupal_programming_trick_add_an_element_before_after_another_element_in_form_alter

Untested because the module I was adding it to didn't need it; prefix and suffix were good enough.

$new['new_form_element_name'] = array('value' => 'markup!');

_au_insert_in_form($form, $new, 'title', TRUE)

<?php
/**
 * Insert immediately before or after an element in a form.
 *
 * Agaric Utility function.
 */
function _au_insert_in_form(&$form, $new, $element, $after = FALSE);
// add the option before the buttons
 
$pos = array_search($element, array_keys($form_values));
  if (
$after) {
   
$pos = $pos + 1;
  }
 
$form = array_merge(
   
array_slice($form, 0, $pos),
   
$new,
   
array_slice($form, $pos)
  );
}
?>

Note from ben: I've since tested just the last part (i already knew the position) and it works great.

<?php
    $output
= array_merge(
     
array_slice($output, 0, 1),
     
$book,
     
array_slice($output, 1)
    );
?>

I was implementing hook_menu_local_tasks_alter(&$data, $router_item, $root_path) and that $output variable is actually $output =& $data['tabs'][0]['output'];

Searched words: 
place form drupal array_splice merge form drupal 7 validate function split array add value into array add to beginning of array

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.