1

I am pretty new to Drupal dev world. I wanted to know how to insert a select box before the search box. I used the below code to alter the search form and set the #weight to a higher value but the select box still shows up after the search box.

function mymodule_form_search_block_form_alter(&$form, &$form_state) {
  $form['my_field']= array(
    '#type' => 'select', 
    '#title' => t('whatever'), 
    '#options' => array(
      0 => 'option1',
      1 => 'option2',
    ), 
    '#default_value' => 255,
    '#weight' => 10,
  );
}

2 Answers 2

0

If you need the form field to be placed before any other form field present in the form, you need to use, for the weight, a lower value than the one used from the present form fields. The default value is 0; use a negative value to be sure the form field is always shown first (e.g. −200).

search_box() doesn't use any value for the field's weight, which means the default value is used.

  $form[$form_id] = array(
    '#type' => 'textfield', 
    '#title' => t('Search'), 
    '#title_display' => 'invisible', 
    '#size' => 15, 
    '#default_value' => '', 
    '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );
  $form['#submit'][] = 'search_box_form_submit';

I have used the following code in a test module.

function code_testing_form_search_block_form_alter(&$form, &$form_state) {
  $form['my_field'] = array(
    '#type' => 'select', 
    '#title' => t('whatever'), 
    '#options' => array(
      0 => 'option1',
      1 => 'option2',
    ), 
    '#default_value' => 255,
    '#weight' => -200,
  );
}

The search form appears as in the following screenshot.

screenshot

1
  • In mymodule_form_search_block_form_alter(), I lowered the #weight of the select box but the select box still shows after the search textfield. I verified that with the Devel module, and it says the weight of the search_block_form is 0 and the select box -200.
    – jax
    Commented Jun 8, 2012 at 18:02
0

Lowering the #weight will float and increasing it will sink the element in the form.

The #weight property is always honored by drupal_render() function only if whole form is rendered at once. But if form is rendered manually by parts then there is no way except to override it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.