Monday, October 8, 2012

Adding a submit function without changing the current

I created a custom table in the database for my module and would like to save a field to that database upon submit of the user_profile_form.

I did this by creating a custom submit handler using the hook_form_alter() function
But instead of just changing the $form['submit'] I added a submit handler as first value of the $form['submit'] array like so:
array_unshift($form['#submit'], 'job_agent_user_profile_form_submit');

Resulting in the following function:

 * Implements hook_form_alter()
function job_agent_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'user_profile_form') {
// get job agent value from db for user that is being edited
$account = $form_state['user'];
$job_agent = db_select('job_agent_searches', 'j')
->condition('uid', $account->uid)

// add extra field job agent field to the form
$form['job_agent'] = array(
'#title' => t('Job Agent'),
'#type' => 'checkbox',
// table: job_agent_searches field: enabled where uid = uid
'#default_value' => $job_agent,
'#description' => t('zet hier je job agent op basis van jouw profiel aan of uit.')
// add submit handler 'on top' of submit array instead of overwriting it leaving other submit functions there to work as well.
array_unshift($form['#submit'], 'job_agent_user_profile_form_submit');
return $form;

And finally create the custom submit handler function:

 * Custom submit handler to be added to user_profile_form
 * saves job_agent field to job_agent database for the user that is being edited.
function job_agent_user_profile_form_submit($form, &$form_state) {
$account = $form_state['user'];
// save job agent field to the db here.
->condition('uid', $account->uid)
->expression('enabled',':enabled', array(':enabled' => $form_state['values']['job_agent']))