1

I have created a checkbox in user edit using form alter and based checkbox state I want to print the message. For this I used below code

function module_form_user_profile_form_alter(&$form, &$form_state) {

  $form['account']['checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => 'Test check',
   );
   $form['#submit'][] = 'module_simplenews_unsubscribe';
}

//~ //Submit handler for Subscribe/unsubscribe newsletter.
function module_simplenews_unsubscribe($form, &$form_state) {

  if ($form['account']['checkbox']['#value'] == 0) {
    drupal_set_message(t("You are checked"));
  }
 if ($form['account']['checkbox']['#value'] == 1) {

    drupal_set_message(t("You are unchecked"));
  }
}

It works fine. When checkbox is checked/unchecked and user saves the profile it prints respective message. But when user doesn't modify this checkbox field and modify some other field and saves, again it prints message based on checkbox state.

I want to display the message only when checkbox field is modified. How can I achieve this?

1 Answer 1

1

You can use form_state instead of form in your submit handler and use default_value of check box in your form alter

$form['account']['checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => 'Test check',
    '#default_value' => 0,
   );

and then your submit handler will go like this

function module_simplenews_unsubscribe($form, &$form_state) {

  if ($form_state['values']['checkbox'] == 0) {
    drupal_set_message(t("You are checked"));
  }
 if ($form_state['values']['checkbox'] == 1) {

    drupal_set_message(t("You are unchecked"));
  }

Use debug tools for proper index of form_state for checkbox.

2
  • Giving same result. It prints the message if checkbox is not modified @Shabir
    – user50991
    Commented Nov 6, 2015 at 11:55
  • I observed you didn't add default_value '#default_value' => 0' use something like this in your form alter
    – Shabir A.
    Commented Nov 6, 2015 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.