1

I am maintaining a cache of data in my module using $_SESSION, which gets rebuilt after an amount of time has passed. This works fine, but I now need the cache (session object) to be cleared when the user submits a change to the module settings.

Is there a hook I can implement that will be called on form submission? I have already implemented mymodule_form_validate, but this doesn't feel like the right place for it, I would prefer a hook that fires only when validation is successful.

I have tried checking for the rebuild flag in mymodule_form, but that doesn't seem to work:

function mymodule_form($form, &$form_state) {
    if($form_state['rebuild'] === true) unset($_SESSION['mymodule_cache']);
    //form elements and stuff...
}

Update

Trying to follow marcvangend's answer, but I'm struggling. I've implemented hook_form_FORM_ID_alter:

function mymodule_form_mymodule_form_alter(&$form, &$form_state, $form_id) {
    echo $form_id.'<br>';  // mymodule_form
    $form['#submit'][] = 'mymodule_form_submit';
}

and this seems to work, in so much as the form id traces out as expected. The trace in my submit function never seems to appear and the session object is unchanged, although the form values do submit:

function mymodule_form_submit($form, &$form_state) {
    echo 'form submit';
    $_SESSION['mymodule_cache'] = array();
}
  • 2
    I'm not sure if its because of that but you've a double == after session assignment. – yvan Dec 6 '11 at 10:53
  • Yup, there is nowhere to hide from rookie mistakes. – shanethehat Dec 6 '11 at 11:02
  • 2
    I'm correcting the code in your answer, to prevent people from copy-pasting broken code. – marcvangend Dec 6 '11 at 14:25
3

You can implement hook_form_alter or hook_form_FORM_ID_alter and add a custom submit handler to the form in which you can clear the session data. It would look something like this:

<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {   
  if ($form_id == "some_form") {
    $form['#submit'][] = 'mymodule_some_form_submit';
  }
}

function mymodule_some_form_submit($form, &$form_state){
  // Do your fancy stuff here.
}
?>

This example implements hook_form_alter. If you only have one form to alter, I recommend using hook_form_FORM_ID_alter because it results in cleaner code.

  • Thank you. I'm having a bit of trouble though, please see my updated question. – shanethehat Dec 6 '11 at 10:45
  • Nevermind, it was a stupid typo. See the comparison instead of assignment in the submit function! – shanethehat Dec 6 '11 at 10:54
  • Yup, there's a big difference between = and == (and a slightly smaller difference between == and ===). Welcome to the fascinating world of programming :-) – marcvangend Dec 6 '11 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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