I'm a newcomer to Drupal and I'm having problems wrapping my mind around form processing. I have been researching all day, browsing the web and stepping through the code, and I still can't figure out what I need to do to perform what should be a relatively simple function. Any help would be sincerely appreciated.
I have set up a new content type and with hook_form I can create the standard create / edit / delete form. So far so good.
I have a date field in my type and instead of having the user enter the date (using a date or date popup type element on the form which I can do, no problem), I want to allow them to click a button which will populate the field with the current date & time. The code I have come up is as follows.
function my_type_form(&$node, $form_state) {
$weight = 0;
// if his value is set, we're rebuilding the form after updating the last contact date
if (isset($form_state['values']['last_contact'])) {
$last_contact = $form_state['values']['last_contact']['value'];
// otherwise, we're building the form for the first time, use the value retrieved from the database
} else {
$last_contact = $node->last_contact;
$form['last_contact'] = array(
'#type' => 'value',
'#value' => $last_contact,
);
}
$form['last_contact_display'] = array(
'#type' => 'item',
'#title' => t('Last Contact'),
'#value' => !empty($last_contact) ? date('D, M j, Y, g:i a', strtotime($last_contact)) : '',
'#weight' => $weight++,
);
$form['reset_last_contact'] = array(
'#type' => 'submit',
'#value' => 'reset',
'#submit' => array ('my_type_reset_last_contact'),
'#weight' => $weight++,
);
return $form;
}
function my_type_reset_last_contact($form, &$form_state) {
$date = date('Y-m-d H:i');
$form_state['values']['last_contact']['value'] = $date;
$form_state['rebuild'] = TRUE;
}
Everything works fine until I get to the hook_update function, at which time it appears that $node->last_contact has not been populated.
I have stepped through the code several times and I can not figure out why this is not working. I know it would work if I defined it as a text field. I thought value element types were passed through to the submit.
Many thanks in advance!
Comments
$form_state['storage']['last_
seems to work a better than
This introduces a new problem though. Now the form does not redirect to the view screen but stays on the edit screen. I guess I need to unset $form_state['storage'] when I'm done with it...but where?
So I use hook_form_alter to
So I use hook_form_alter to add a submit handler to the 'submit' button, then clear $form_state['storage'] in the submit handler.
What a rat's nest.