Drupal is one of the most commonly used open source CMS. In this CMS most of the developers are not aware of how to modify existing forms. Drupal providing a functionality to modify existing form, custom validation or submitting or adding extra fields to a existing form or core module's form. In my experiences most of the developers are not know this feature in drupal. So they are going to write new module for the same functionalities. This will cause the performance of the site and it make the site to costly.
This document helping you to customize an existing form mainly modifying core module's forms. The solution is use form_alter_hook "hook_form_alter()". It perform alterations before a form is rendered. You can use this function any where in your module. The hook_form_alter() is called for all forms, you can also use hook_form_FORM_ID_alter() to alter a specific form.
Example code
In this example, I am adding additional field in User Login form and add custom validation for this.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id=='user_login'){
$form['key'] = array(
'#title' => 'key Value',
'#type' => 'textfield',
);
//adding custom validation
$form['#validate'] = array('_custom_form_validate');
}
return $form;
}
/**
*You custom validation function
**/
function _custom_form_validate(){
//your validation code here
}
The above example is for all forms, you can use this function for modifying one or more forms by using if condition,.
If you want to modify specific form you can use hook_form_FORM_ID_alter() function
eg:
function mymodule_form_user_login_alter(&$form, &$form_state) {
$form['key'] = array(
'#title' => 'key Value',
'#type' => 'textfield',
);
//adding custom validation
$form['#validate'] = array('_custom_form_validate');
return $form;
}
/**
*You custom validation function
**/
function _custom_form_validate(){
//your validation code here
}
$form['key'] = array(
'#title' => 'key Value',
'#type' => 'textfield',
);
//adding custom validation
$form['#validate'] = array('_custom_form_validate');
return $form;
}
/**
*You custom validation function
**/
function _custom_form_validate(){
//your validation code here
}
0 comments:
Post a Comment