itsututa
itsututa

Reputation: 157

Drupal 7 add a field to the search block form configuration

I want to build a module that adds an extra field on the search form block configuration page to store text that will be displayed as the HTML5 placeholder attribute. What hooks do I need to use and how do I modify just the search form block to have that extra texbox that then gets printed on the page?

Upvotes: 1

Views: 2614

Answers (2)

itsututa
itsututa

Reputation: 157

This is the code that finally worked, thanks for your help:

function yourmodule_form_alter(&$form, &$form_state, $form_id) {  
  if (($form_id == 'block_admin_configure') && ($form['module']['#value'] == 'search')) {
    $form['settings']['theplaceholder'] = array(
      '#type' => 'textfield', 
      '#title' => t('Add placeholder text'), 
      '#default_value' => variable_get('theplaceholder'),
      '#maxlength' => 64,
      '#description' => 'Override the default placeholder',
      '#weight' => 2,
      '#access' => TRUE,
    );
    $form['#submit'][] = 'yourmodule_submit_function';
  }

if ($form_id == 'search_block_form') {
    $form['search_block_form']['#attributes']['placeholder'] = variable_get('theplaceholder');
  }
}
function yourmodule_submit_function($delta = '', $edit = array()){  
    variable_set('theplaceholder', $edit['values']['theplaceholder']);
}

Upvotes: 2

Boriana Ditcheva
Boriana Ditcheva

Reputation: 2015

You can use the following hook to modify any form:

function MODULE_NAME_form_FORM_ID_alter(&$form, &$form_state, $form_id) {

}

Insert your own module name and the form id of the form you're trying to change. In your case it would be search-form or search-block-form for just the block. Find out the id of the form you're trying to change by viewing the page's html source and getting the id from the element.

In any case, once you've figured out the proper id to insert, start adding elements to the form:

function MODULE_NAME_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $form['my_new_field'] = array(
    '#type' => 'item',
    '#markup' => t('Just testing'),
    '#weight' => 10, 
  );
}

Load the form up to make sure your new label, field or whatever is showing up.

Did that work for you?

More documentation on this function is here: http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_FORM_ID_alter/7

Upvotes: 1

Related Questions