Fine-grained #weight values in Drupal

This may not be immediately obvious but whenever you need to assign #weight values in Drupal, for example when ordering form elements, you can use floats as well as integers. This is useful if you need to insert a field in between two fields with weights that are 1 apart:

$form['field_a']['#weight'] = 1;
$form['field_b']['#weight'] = 1.5;
$form['field_c']['#weight'] = 2;

I found this to be useful sometimes when I need to insert a field (in hook_form_alter) in between two fields generated by other modules, e.g. to insert field_b above field_c, I'll just do:

$form['field_b']['#weight'] = $form['field_b']['#weight'] - 0.5;

Job done.

Filed under  //  cms   drupal   forms  
Posted by Farez Rahman